@molecule/api-ai-tools
Core interface · ai · API (Node) · v2.2.3 · Apache-2.0
Shared AI agent tools with backend abstraction for sandbox and local execution
npm install @molecule/api-ai-toolsHow it works
@molecule/api-ai-tools is the ai core interface on the API (Node) side: the API your app calls, with no vendor inside.
Bond a provider to choose the implementation.
import { buildAgentPrompt, buildTools, createLocalBackend } from '@molecule/api-ai-tools'
import { requireProvider } from '@molecule/api-ai'
const backend = createLocalBackend('/path/to/project')
const tools = buildTools(backend, { include: ['read_file', 'edit_file', 'search_files'] })
const system = buildAgentPrompt({
agentName: 'My Agent',
projectRoot: backend.projectRoot,
tools: tools.map((t) => t.name),
})
// Hand them to the bonded AI provider (or an @molecule/api-ai-agents run).
for await (const event of requireProvider().chat({ system, tools, messages, stream: true })) {
// forward text chunks; tool calls are executed against the backend
}Works with: @molecule/api-ai
Reference
Shared AI agent tool set for molecule.dev — filesystem, search, and shell tools an LLM agent can call, with a swappable execution backend.
buildTools(backend) returns ready-to-use AITools (the @molecule/api-ai
tool shape): list_files, read_file, write_file, edit_file,
search_files, find_files, create_directory, rename_file,
delete_file, exec_command, save_plan, load_skill. The backend decides
WHERE they act: createLocalBackend(projectRoot) (host filesystem) or
createSandboxBackend(...) (an isolated @molecule/api-code-sandbox
container). buildAgentPrompt(ctx) composes a matching system prompt
(identity, tool listing, project docs, discovered skills).
Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit
src/index.tsJSDoc, not this file.
Quick Start
import { buildAgentPrompt, buildTools, createLocalBackend } from '@molecule/api-ai-tools'
import { requireProvider } from '@molecule/api-ai'
const backend = createLocalBackend('/path/to/project')
const tools = buildTools(backend, { include: ['read_file', 'edit_file', 'search_files'] })
const system = buildAgentPrompt({
agentName: 'My Agent',
projectRoot: backend.projectRoot,
tools: tools.map((t) => t.name),
})
// Hand them to the bonded AI provider (or an @molecule/api-ai-agents run).
for await (const event of requireProvider().chat({ system, tools, messages, stream: true })) {
// forward text chunks; tool calls are executed against the backend
}
Type
core
Installation
npm install @molecule/api-ai-tools @molecule/api-ai typescript
API
Interfaces
BrowserProbeLeak
A browser launch bound to a variable, proven to have no cleanup path.
interface BrowserProbeLeak {
/** The variable the launched browser is bound to (`browser` in the probe above). */
readonly variable: string
}
ForegroundBrowserProbe
A foreground command that directly executes such a script.
interface ForegroundBrowserProbe extends BrowserProbeLeak {
/** The script file as the command named it. */
readonly script: string
}
CommandPlanStep
One sequential command, with boundaries emitted by its launcher around execution.
interface CommandPlanStep {
/** Launcher's stable step identity. */
id: string
/** The logical command actually executed, including launch rewrites. */
command: string
/** Printed on its own line immediately before this step runs. */
startMarker: string
/** Printed on its own line after this step settles. */
endMarker: string
}
CommandPlan
A wrapper's ordered commands; metadata describes execution, never proof or completion.
interface CommandPlan {
/** Per-launch boundary identity, preventing ordinary suite output from matching a boundary. */
id: string
/** Steps execute in this order. */
steps: CommandPlanStep[]
}
CommandSegment
One statement or pipeline stage of a shell command: what it runs, and with what.
interface CommandSegment {
/**
* The word in command position, its directory removed (`/usr/bin/hurl` → `hurl`): the program
* the shell would run once whatever wrappers stood in front of it are taken away. When a
* wrapper runs a tool's own CLI by file, this is the tool's name — `node
* <path>/node_modules/.bin/playwright test` is a `playwright` invocation, not a `node` one.
*/
program: string
/** The words after it, as written — quotes kept, so a quoted `"a|b"` is one word. */
args: readonly string[]
/** The program and its arguments as one line — what a runner pattern is matched against. */
text: string
/**
* The seconds the segment's own `timeout` wrapper allows the command it runs
* (`timeout 280 hurl --test …` → 280), or null when it carries none.
*/
timeoutSeconds: number | null
/**
* True when the statement sits in a loop (`for`/`select`/`while`/`until` … `done`, its
* condition included), so it may run many times: its own `timeout` bounds each pass, not the
* command. Absent for a statement that runs once.
*/
repeated?: true
}
ExecutedCommand
One command a shell command actually executes, wherever the shell runs it.
interface ExecutedCommand {
/**
* The word in command position, its directory removed (`/usr/bin/printenv` → `printenv`) — or
* the launcher itself when it runs alone and nothing follows it (`x | env` → `env`).
*/
program: string
/**
* Its arguments, as written with quotes kept — the statement's own words AFTER the program,
* including an input redirect's path (`< /proc/self/environ`), so a reader of secret files sees
* the file it reads.
*/
args: readonly string[]
/** The program and its arguments as one line, what a pattern anchored at the program matches. */
text: string
}
LocatedCommandSegment
One statement of a shell command, with where it sits and the variables it sets for itself.
commandSegments answers WHAT runs; this answers where, and what the shell binds to it — the
two things a caller that WRITES into a command needs. The platform composes a run from the
executor's own command in more than one place, and a value written for the runner belongs in
the runner's own statement: APP_BASE=https://… cd app && npx playwright test sets the variable
for cd alone, so the Playwright config falls back to the local app while the command line
still names the deployed host.
interface LocatedCommandSegment {
/**
* Directory-scope ancestry supplied by the existing shell parse, outermost first.
* Parenthesized groups and nested `sh -c` strings have their own shell directory;
* braces share their parent's. Identities are opaque and local to this invocation.
* Absent for ordinary statements in the outer shell, preserving their existing shape.
*/
shellScope?: readonly string[]
/**
* What the statement runs, or null when it only sets variables (`BASE=http://…` on its own):
* that shape persists in the shell, so a caller following assignments across `;`/`&&` has to
* see it.
*/
segment: CommandSegment | null
/** The statement's own leading `NAME=value` words, as written (`TEST_MODE=fullstack`). */
assignments: readonly string[]
/**
* Assignments whose values expand at this source statement, when different from
* inherited environment bindings. A nested `sh -c` carries outer bindings into
* every entry, but expands its caller's assignment values only before its first
* command. Absent when the ordinary `assignments` list is also the source list.
*/
sourceAssignments?: readonly string[]
/**
* The offset in the command of the statement's first word, or null for a segment inside a
* nested `sh -c '<command>'` string — its positions are offsets in THAT string, not in this
* command, so nothing may be spliced at them.
*/
start: number | null
/**
* The offset in the command just before the word the statement runs — after its own leading
* `NAME=value` words and their whitespace. A `NAME=value` written here is in the environment of
* the program the statement runs (`… TEST_MODE=fullstack <here>npx playwright test`). Null
* inside a nested `sh -c` string, for the same reason as `start`.
*/
assignmentOffset: number | null
/**
* The offset in the command one past the statement's last word — where an option of this
* statement's program belongs, before whatever closes it. Null inside a nested `sh -c` string.
*/
end: number | null
/**
* The offset in the command of the word in command position — the program, once every wrapper
* in front of it is taken away (`npx --prefix /app <here>playwright test`). Null inside a
* nested `sh -c` string, and for a statement that only sets variables.
*/
programOffset: number | null
/**
* The separator the shell split at immediately before this statement — `|`, `||`, `&&`, `;`,
* a newline or `&` — or '' when it is the first statement of the command. It is the parse's own
* answer, so it is known even where the offsets are not, and a caller deciding whether two
* statements are one pipeline (`|`, never `;`) asks it instead of reading the text between them.
*/
separator: string
/**
* The separator that ENDED this statement — `&` when the shell backgrounds it (so the process
* writes its own output, not the command's), '' for the last statement of a command.
*/
terminator: string
/**
* The file this statement sends its own output to (`> out.log`, `>> log`, `&> run.log`,
* `| tee file`), or null. Only a redirect written at the command's own level counts: one
* inside a `( … )` / `{ … }` group writes through that group, and one that feeds a heredoc's
* file (`cat > cfg.ts <<'EOF'`) is writing a config.
*/
redirectTarget: string | null
}
SuiteSummary
What a runner's own closing summary reports, and whether it accounts for the whole run.
A summary is not by itself proof that the run finished. Playwright prints one when its process
is stopped too (SIGTERM/SIGINT), listing only the tests it reached — so a run killed at 36 of
139 tests ends with the same 36 passed (2.5m) line as a run that walked all 139. The only
thing that separates them is the total the runner announced before it started
(Running 139 tests using 1 worker), which suiteSummary reconciles the summary against.
interface SuiteSummary {
/**
* The total the runner announced before its first test, or null when it announced none (Hurl
* announces nothing; Vitest's own summary line carries its total in parentheses).
*/
announced: number | null
/**
* Every test the summary accounts for — the ones it passed, failed, marked flaky, timed out,
* interrupted, skipped or left "did not run". This is how far the walk got, which is what a
* stopped run's sentence says; a summary that accounts for fewer than `announced` was
* printed by a process that stopped early.
*/
accounted: number
/** Whether the summary accounts for every test the runner announced. */
finished: boolean
}
CutRun
A run a budget stopped, as its result reports it.
interface CutRun {
/** The bound the run was allowed, in seconds. */
seconds: number
/** Whether this tool's budget stopped it or the `timeout` the command carried. */
stoppedBy: CutBy
/**
* Whether this was a detached background task, read with no budget of this tool's own
* (`commandCutRun`'s `budgetSeconds` is 0). A background run is bounded by what its own
* command carries — so a `command-timeout` cut there is that prefix killing the walk, and the
* executor must be told to drop the prefix, never to start the run in the background it is
* already in.
*/
background: boolean
/**
* The exit code the run's own process reported, or null when the code in the result belongs to
* the pipeline's filter (`… | tail`) rather than to the run — the case that read as success.
*/
exitCode: number | null
/**
* How far the run got, as its own output counts it — the files that finished, or the tests its
* summary accounts for — or null when the output says nothing.
*/
ran: number | null
/**
* How many the run was walking: the total its runner announced (`Running 139 tests`), or
* Playwright's `[n/K]`, whichever the output carries; null when neither does.
*/
total: number | null
/** The noun the runner counts in. */
noun: 'files' | 'tests'
/** The last thing the run printed — the line a reader looks at first. */
doing: string | null
/**
* The interpreter of an inline program that only touches local files (`python3`, `node`, …), or
* null. Such a program is stopped by its short budget because it is stuck, never because the work
* is slow, so the sentence must not send it to the background.
*/
inlineScript?: string | null
/**
* The variable a leaked standalone browser launch is bound to, when the command ran such a probe
* and the cut reader could only classify it after the run. A leaked
* handle is not a slow workload: the background is the one place it must not be sent, so the
* sentence names the close instead.
*/
browserProbe?: string | null
}
RunFailureClass
One failure a runner printed, classified by the layer that failed.
interface RunFailureClass {
/** The layer that failed. */
kind: RunFailureKind
/** For a `connection` failure, what the transport did. */
connection?: ConnectionFailureKind
/** How long the request waited before the transport gave up, in seconds, when printed. */
seconds?: number
/** The `file:line` the runner printed for the failure, when it printed one. */
at?: string
}
NormalizableSchema
The JSON-Schema-ish shape every tool in this package declares.
interface NormalizableSchema {
name: string
parameters?: {
type?: string
properties?: Record<string, { type?: string; description?: string }>
required?: string[]
}
}
NormalizedInput
The result of normalizing one tool call's input.
interface NormalizedInput {
/** The input to hand the handler, with aliases moved onto the declared names. */
input: Record<string, unknown>
/** Declared-required parameters still absent after aliasing. */
missing: string[]
/** `alias→declared` pairs that were moved, for logging. */
aliased: string[]
}
GuardOptions
Options shared by guardToolExecute and guardAITool.
interface GuardOptions {
/**
* Redactor applied to a THROWN error's message before it is returned to the
* model. Defaults to this package's `redactSecrets`.
*/
redactError?: (message: string) => string
}
RunnerOutputFilter
A cutting stage that follows the runner, and the command with the whole pipe removed.
interface RunnerOutputFilter {
/**
* The stage exactly as the runner's command wrote it — `tail -6`. When several cutting filters
* follow the runner, this is the whole trailing chain as written, pipes included:
* `grep -E "Failure|actual" | head -40`.
*/
stage: string
/** The pipe as a sentence names it — `| tail -6`, or the whole chain `| grep … | head -40`. */
pipe: string
/**
* The command with the pipe and the stage removed — `hurl --variable uid=… --test /tmp/t.hurl
* 2>&1`. This is a command to send again as written, not a re-typing of it: it is a slice of the
* original with the filter's own range cut out, so every other word, quote and redirect stays.
*/
command: string
}
PlaywrightTimingStep
Native action clocks plus the hook title used to locate teardown; titles never enter the output.
interface PlaywrightTimingStep {
/** Native hook title, used only to locate the teardown boundary; never serialized. */
title?: string
category: string
startTime: Date
duration: number
location?: { file: string; line: number; column: number }
error?: unknown
steps: PlaywrightTimingStep[]
}
PlaywrightAttemptTimings
A bounded timeline of the actions Playwright already recorded for one attempt.
interface PlaywrightAttemptTimings {
version: 1
startTime: string | null
durationMs: number
steps: {
parent: number | null
category: string
startTime: string | null
/** Native duration, or elapsed time to the attempt cutoff for an unfinished step. */
durationMs: number | null
/** The native step never ended. Null duration means its clock cannot establish elapsed time. */
unfinished?: true
location?: { file: string; line: number; column: number }
failed: boolean
}[]
omittedSteps: number
}
FeedbackSource
A source file already read by the caller. Paths are absolute.
interface FeedbackSource {
path: string
content: string
}
FeedbackSpec
One project spec, with its normal, locally targeted runner command.
interface FeedbackSpec extends FeedbackSource {
command: string
cwd: string
}
FeedbackProject
The inputs the host already knows; no suite discovery or vendor selection in the scheduler.
interface FeedbackProject {
/** Base for relative source-change paths, already resolved by the host. */
root?: string
sources: FeedbackSource[]
specs: FeedbackSpec[]
/**
* Complete, absolute roots/files of test definitions, config and selection inputs, when
* the caller knows them. Writes there invalidate test identities as well as results.
* Omit when unknown: writes to the spec itself still invalidate its native selection.
*/
testRoots?: string[]
}
PlaywrightFeedbackFailure
A native failure, never a static prediction or a completed-suite proof.
interface PlaywrightFeedbackFailure {
spec: string
line: number
error: string
/** The native runner's locator, assertion or timed-out browser operation, apart from redaction. */
locator: string
/** Native test identity, when the reporter provided one. */
testId?: string
/** Playwright's own failure-time accessibility snapshot, when recorded. */
rendered?: string
/** The paths that triggered this run. They do not establish a failure cause. */
sourceFiles: string[]
}
PlaywrightFeedbackResult
A diagnosis of one spec file at one source revision. A pass is not whole-suite proof.
skipped means the runner completed and every selected test skipped itself (a spec's own
test.skip(condition)): nothing to verify in this environment, neither a pass nor an outage.
interface PlaywrightFeedbackResult {
spec: string
revision: number
durationMs: number
status: 'passed' | 'failed' | 'skipped' | 'unavailable' | 'cancelled'
failures: PlaywrightFeedbackFailure[]
/** Native counts for this one diagnostic selection, never whole-suite proof. */
nativeStats?: PlaywrightReportStats
reason?: string
/** Native completed tests, including tests from a stopped file. */
tests?: FeedbackTestOutcome[]
/** This run’s native selection. Partial selections never replace a file’s full inventory. */
selectedTests?: string[]
/**
* Playwright's own last-run record (`.last-run.json`: the ids of the tests that failed or did
* not run) from a failed run, when the runner wrote one. A later checkpoint hands it back so
* the runner re-runs only those tests (`--last-failed`). A `cancelled` run carries one in the
* same shape naming only the tests it saw fail before it stopped, when there were any.
*/
lastRun?: string
/**
* The ids of the tests a `cancelled` run saw pass before it stopped, in the same form as
* `lastRun`'s. They leave the spec's known failures; tests it never reached stay as known.
* A finished `last-failed` run names the tests it passed the same way.
*/
passedTests?: string[]
/**
* Each outermost serial group (`test.describe.serial`, `describe.configure({ mode: 'serial' })`)
* the run selected, by test id. Its tests depend on each other, so a record that names one of
* them names all of them: `--last-failed` would otherwise run a later test without the ones it
* needs. A record this run returns (`lastRun`) already does.
*/
serialGroups?: string[][]
/**
* `last-failed` when the run selected only the tests an earlier run's record names. Its pass
* clears those failures; on its own it never stands for the whole file.
*/
selection?: 'last-failed'
}
PlaywrightFeedbackOptions
Host operations for the same checkpoints in a CLI process or a remote sandbox.
interface PlaywrightFeedbackOptions {
load: () => Promise<FeedbackProject>
/**
* Run one spec file for a checkpoint. Every call is explicit verification the caller is waiting
* for: hosts run it with `runPlaywrightFeedback`'s `foreground`, unless the host process itself
* runs beside other work (a CLI watcher), where it may yield to that work.
*/
run: (
spec: FeedbackSpec,
sources: string[],
revision: number,
/** Receives native failures as they arrive; checkpoints read the returned result instead. */
emit: (result: PlaywrightFeedbackResult) => void,
/** Stop the owned native process group when cancelled; never wait for the tests to finish. */
signal: AbortSignal,
/**
* The spec's known failures in the last-run shape, on a known-failures checkpoint. Hand it to
* `runPlaywrightFeedback` as `lastFailed` so only those tests run; a host that ignores it
* runs the whole file.
*/
lastRun?: string,
) => Promise<PlaywrightFeedbackResult>
/** Every native result a checkpoint ran, as operational state apart from defect feedback. */
onResult?: (result: PlaywrightFeedbackResult) => void
}
PlaywrightFeedbackCheckOptions
What an explicit checkpoint runs.
interface PlaywrightFeedbackCheckOptions {
/**
* Re-run only the spec files in `PlaywrightFeedback.failingSpecs`. With none, the
* checkpoint loads and runs nothing and returns no results.
* Within such a file only the tests its last failed run names are re-run, when the runner
* recorded them; the whole file runs when it did not, or when that record selects no test.
* Their pass clears the known failure; the rest of the file is left to explicit runs.
*/
failedOnly?: boolean
}
PlaywrightFeedback
Source-write tracking with explicit native checkpoints. Nothing runs on a write.
interface PlaywrightFeedback {
/**
* Record source writes: the revision advances and passes reused by checkpoints are dropped. A
* write during a checkpoint interrupts it and discards its partial result.
*/
changed: (paths: readonly string[]) => void
/**
* Verify the current revision before an explicit action, reusing completed native results.
* Stops at the first failing or unavailable spec; a skipped spec does not stop it. A source
* write interrupts the checkpoint and discards its partial result. Concurrent checkpoints share
* the same work.
*/
check: (options?: PlaywrightFeedbackCheckOptions) => Promise<PlaywrightFeedbackResult[]>
/** Spec files whose latest native outcome failed and that have not passed or skipped since. */
failingSpecs: () => string[]
/**
* The current source revision. Read it before starting a native run of your own and pass it to
* `PlaywrightFeedback.record` with that run's outcomes.
*/
revision: () => number
/**
* Record outcomes of a native run the host started itself (an explicit local test command with
* the same spec command, or a deployed walk), so `PlaywrightFeedback.check` reuses them
* instead of running the spec again. Ignored when a source write landed after `revision` was
* read. Failures become known failures, with the runner's failed-test record, for the next
* known-failures checkpoint to re-run. A pass or self-skip clears the known failure. Cancelled
* and unavailable runs change nothing. Partial selections are diagnosis and never replace
* whole-file checkpoint coverage.
*/
record: (results: readonly PlaywrightFeedbackResult[], revision: number) => void
/** Stop: a running checkpoint is cancelled and awaited, and later calls do nothing. */
close: () => Promise<void>
}
PlaywrightReportAttachment
One artifact the runner saved for one test, as the report records it.
interface PlaywrightReportAttachment {
/** The attachment's name (`trace`, `screenshot`, …). */
name: string
/** Its media type, when the runner recorded one. */
contentType: string | null
/** This attempt's published artifact path; a per-call copy when retention succeeded. */
path: string
}
PlaywrightReportTest
One failing (or flaky) test's identity and evidence, as the runner recorded them.
The identity fields are Playwright's own — never reconstructed from printed headings — so a reader can tell exactly which test an attachment belongs to.
interface PlaywrightReportTest {
/** The spec's stable id, when the report carries one. */
id: string | null
/** The Playwright project the test ran in. */
project: string | null
/** The spec file, relative to the config's root directory as the report writes it. */
file: string
/** The test's declaration line. */
line: number
/** The test's declaration column. */
column: number
/** The full title path (`['describe', …, 'test title']`), empty when none is readable. */
titlePath: string[]
/** The test's own title (the last entry of `titlePath`). */
title: string
/** Playwright's outcome for the test: `unexpected`, `flaky`, `skipped` or `expected`. */
status: string
/** How many attempts the runner made (1 when it was not retried). */
attempts: number
/** The retry index of the attempt whose evidence is reported (0 when not retried). */
retry: number
/** That attempt's own duration, in milliseconds. */
durationMs: number
/** That attempt's error message, bounded and redacted, or null. */
error: string | null
/** The artifacts the runner saved for THAT attempt — `trace` first. */
attachments: PlaywrightReportAttachment[]
}
PlaywrightReportStats
The runner's own tally, read straight from the report. Never a verdict this module derives.
interface PlaywrightReportStats {
/** Tests that ended as expected. */
expected: number
/** Tests the runner skipped. */
skipped: number
/** Tests that did not end as expected. */
unexpected: number
/** Tests that failed and then passed on a retry. */
flaky: number
/** The run's own duration, in milliseconds. */
durationMs: number
}
PlaywrightRunReport
What one run's standard machine report says, bounded for a tool result.
A reader that needs evidence this record does not carry reads path in the sandbox.
interface PlaywrightRunReport {
/** Whether the published attachment paths were retained outside the runner's mutable output. */
artifactRetention?: {
status: 'retained' | 'partial' | 'unavailable'
omittedAttachments: number
bytes: number
/** The per-call snapshot root for readers of the retained trace tree. */
directory?: string
}
/** How much of the report was read — see `PlaywrightReportStatus`. */
status: PlaywrightReportStatus
/** Where the report file is, for the full evidence. Always the runner's own file. */
path: string
/** One short phrase saying why a record is not `complete`, when it is not. */
reason?: string
/** The runner's tally, or null when the report did not carry one. */
stats: PlaywrightReportStats | null
/** The failing and flaky tests, in report order, bounded by `MAX_REPORTED_FAILURES`. */
failures: PlaywrightReportTest[]
/** How many failing tests did not fit the bound above. */
omittedFailures: number
/** Every identity past the detailed-record cap, never silently omitted from the model's copy. */
omittedFailureNames?: string[]
}
ToolSchema
JSON-schema-backed definition for a single agent tool.
interface ToolSchema {
name: string
description: string
parameters: JSONSchema
}
ForegroundServer
A foreground command that starts a server, as the refusal names it.
interface ForegroundServer {
/** The program (and script, when there is one) that serves. */
readonly program: string
}
LeadingSleep
The leading sleep a command opens with, and the command that follows it.
interface LeadingSleep {
/** How many seconds the statement would have slept (GNU sleep sums its operands). */
seconds: number
/** What follows the leading statement, trimmed — '' when the sleep was the whole command. */
rest: string
}
RunEnvSetting
One NAME=value the request requires of a suite run.
interface RunEnvSetting {
name: string
value: string
}
SuiteRunInFlight
One suite run, as the rule that decides whether a second may start beside it reads it.
Both callers describe the runs in flight the same way and ask the same question of them; what differs is only which runs each one knows about — the hold reads its ledger of background runs, the note reads the one run it is waiting on.
interface SuiteRunInFlight {
/** Whether the run invokes a suite at all: a `vitest`/`jest` run is not one, and cannot be. */
runsSuite: boolean
/** The app and database the run measures, as `suiteCommandTarget` keys it. */
target: string
/**
* Whether the command being judged STOPS this run before starting its own — a kill comes first,
* so a run the command itself stops is not in the way (`kill 19408 … ; npx playwright test …`).
*/
stoppedByCommand?: boolean
}
DiagnosisRunContext
What a caller knows about the run being judged beyond its command text.
interface DiagnosisRunContext {
/**
* The test titles the person's request excludes by name — the same reading molecule-dev's
* `excludedTestTitles` gives the rest of the platform.
*/
approvedExclusions?: readonly string[]
/**
* Whether the caller is STARTING this command as the graded proof itself — the run the app is
* judged by, composed and launched by the platform — rather than the executor's own diagnosis.
*
* A redeploy's proof is the targeted set the last walk left: its command names the failures it
* re-runs (`file:line`, and the specs they live in), so it reads as a narrowed run. That
* selection is the proof's own scope, so the graded run keeps the suite's retries instead of
* walking each failure once the way a diagnosis does. Only the selection is excused — a failed
* cap, a title filter, a last-failed set and a local targeted selection stay diagnoses whatever the caller
* says here — and only a command the PLATFORM composes and launches is ever the proof.
*
* Host code marks the launch input with `PLATFORM_PROOF` rather than a JSON key: tool
* input a model sends is JSON, and JSON has no symbol keys, so no model call can claim this.
*/
platformProof?: boolean
}
DeferredToolCatalogOptions
Options for exposing a small tool set while retaining access to other allowed tools.
interface DeferredToolCatalogOptions {
/** The caller's current permission/mode-filtered tools. Discovery never grants access. */
available: () => readonly AITool[]
/** Tools that should be offered without a discovery call. */
initialNames: ReadonlySet<string>
/** Previously loaded names, in load order; useful across turns and compaction. */
loadedNames?: readonly string[]
/** Persist names after a successful load. No tool content is passed to this callback. */
onLoad?: (names: string[]) => void
}
DeferredToolCatalog
A provider-independent deferred catalog. The caller still executes and authorizes tools.
interface DeferredToolCatalog {
loader: AITool
/** Initial tools, loader, then requested tools in stable load order. */
select: () => AITool[]
}
InstalledPackageFacts
What the filesystem says about a write target under node_modules — the half
of the decision a path's spelling cannot make.
interface InstalledPackageFacts {
/** Whether the `node_modules` entry the path goes through is a symbolic link. */
readonly symlink: boolean
/** Whether a package is really installed there: a `package.json` resolves under the entry. */
readonly installed: boolean
}
TraceRequest
One request a traced page made, as *.network records it.
interface TraceRequest {
/** The HTTP method (`POST`). */
method: string
/** The request's path (`/api/articles/x/favorite`), or the whole URL when it is cross-origin. */
path: string
/**
* The response status as the trace recorded it. Playwright writes `-1` when a request was never
* answered (its HAR entry starts at `-1` and only a response event overwrites it); `0` is the
* same absence when the snapshot carried no response at all. Neither alone proves a server failure.
*/
status: number
/**
* Playwright's own error text for a request that failed WITHOUT a response
* (`net::ERR_CONNECTION_REFUSED`) — a real failure. A request that got no response and recorded
* no text may still have been in flight when recording ended. Missing text or an explicit
* cancellation cannot establish either a server failure or server health.
*/
failure?: string
/**
* What the page SENT, for a 4xx answered by the app's own API — bounded (see
* `MAX_TRACED_BODY_CHARS`). A body wrapped as `{"data":{…}}` is visible here in one line:
* app-http's verbs take the body as their second argument, so a helper that passes
* `{ data: body }` there ships the wrapper.
*/
sent?: string
/** What came back for that 4xx, bounded the same way — the API's own error body. */
got?: string
/**
* The browser's own resource type (`document`, `fetch`, `xhr`, `font`, `image`, `stylesheet`,
* `script`, …). `document` when the request was the page load itself; when it ended in a
* `net::ERR_*`, nothing rendered and no selector or app request was measured.
*/
type?: string
/**
* When the request started, on the trace's own monotonic clock (ms) — the same clock the
* `TraceAction`s carry, so a request can be attributed to the action that caused it.
* Absent on traces whose network entries recorded no clock (an older Playwright, a synthetic
* fixture), in which case only recording order is available.
*/
startedAt?: number
/**
* Whether the request carried an `Authorization` header at all. Its VALUE is never recorded.
*
* A 401 cannot be read without this: the API's own body said
* `{"errors":{"token":["is missing"]}}` while the note told the run to read the API handler,
* when the header's absence proved the CLIENT never attached the token
* A header present moves the answer to the server: the API
* refused a token it was sent.
*/
sentAuthorization?: boolean
/**
* The scheme WORD of an `Authorization` header (`Bearer`, `Token`), or undefined when there is
* no header or its first word does not parse as a scheme (a value pasted without one is a
* credential, and is never copied here).
*/
authorization?: string
/**
* Whether the request carried a `Cookie` header — never the cookies themselves. An app that
* signs in with a session cookie has no `Authorization` header by design, so this tells a
* credential-less request from one whose credential is a cookie.
*/
sentCookie?: boolean
/**
* The trace member this request came from — the browser context Playwright numbered (`1`, `3`).
* A test that opens a second browser context writes one trace member per context, and a test's
* request is only evidence about the page it was made on.
*/
context?: string
/** The page the request was made on, as the HAR entry's `pageref` records it. */
pageId?: string
}
TraceLastAction
The test's LAST user action before the failing assertion, and the requests it caused.
An assertion after a navigation is not explained by the page's last call (GET /api/tags on
whatever page the app redirected to); it is explained by what the action the test took sent and
what came back (13 then 12 failing tests, every trace row leading with
GET /api/tags → 200, while the register POST /api/users and its answer — the fact that
explains the signed-out page — was never shown).
interface TraceLastAction {
/** The Playwright API the trace names: `Locator.click`, `Locator.fill`, `Frame.goto`. */
api: string
/** When the action started, on the trace's monotonic clock (ms). */
start: number
/** When it finished, or null when the run ended before it did. */
end: number | null
/**
* The requests the action caused — started after it and before the failing assertion, the app's
* own API calls first, static assets and the page shell's own files left out. Empty when the
* action sent none.
*/
requests: TraceRequest[]
/** The main frame's URL when the action ran, when the trace recorded frame snapshots. */
pageBefore?: string
/** The last main-frame URL the trace recorded — where the page ended up. */
pageAfter?: string
}
TraceAction
One action the traced page performed, with the trace's own timing for it.
interface TraceAction {
/** The Playwright API the entry names: `Frame.goto`, `Locator.fill`, `Locator.click`. */
api: string
/** When the action started, on the trace's own monotonic clock (ms). */
start: number
/** When it finished, or null when the run ended before it did. */
end: number | null
/** The browser context the action was recorded in (`1`, `3`), when the trace names one. */
context?: string
/** The page the action ran on, from the frame snapshot the trace paired with it. */
pageId?: string
/** The frame the action ran in, from the same snapshot. */
frameId?: string
/**
* The selector a `fill`/`type`/`selectOption` acted on (`textarea[name="bio"]`), from the
* trace's own params. Kept so the note can compare what the test typed with what the page
* submitted (a field typed into and sent empty).
*/
selector?: string
/**
* The value a `fill`/`type`/`selectOption` typed or chose, from the trace's own params —
* absent when the action carried none (a `selectOption` by label only).
*/
value?: string
}
TraceContextEvidence
What a browser context OTHER than the failing page's recorded — the second context a two-context test opens for its own setup.
Its actions and requests belong to a different page: a request it sent is not the failing action's effect, and the URL it left the page on is not where the assertion's page went (the helper context created an article in an editor page while the primary page moved to the profile the assertion then failed on, and the note called the editor page the failing page).
interface TraceContextEvidence {
/** The trace member's context id (`3`). */
context: string
/**
* The app requests that context made, bounded — failures first, then the answered ones — each
* labelled by the note as set-up work rather than the failing page's.
*/
requests: TraceRequest[]
}
TraceMissingText
The text a failing assertion waited for that a same-page API response carried and the page never rendered.
The assertion's own error names the text (a has-text(…) / getByText(…) / toContainText(…)
argument), and the trace's network log holds the response that contained it. That pair is the
whole diagnosis: the API returned the value and the page dropped it before rendering, so the cut
is in the component that maps the response onto the list — not in the API, the route or the
selector. One run spent its fix rounds on the wrong component and on a
markup detail while GET /api/tags was returning the missing "trending" and PopularTags
sliced the response to its first 20 entries (a top-N cut, in the frontend).
The text must be a value the response held, never a substring of one: a whole JSON string or
number value, or a word bounded by non-alphanumerics. A text of 2 characters or fewer, or one
made of digits only, must be a whole JSON value. A pagination assertion
waited for "2" and the raw substring hit pag1792394785820 in a tags response, so the note led
with a response that had nothing to do with the failure; when no response holds the text that
way, the field is absent and the note leads with its next finding.
interface TraceMissingText {
/** The text the assertion waited for (`trending`). */
text: string
/** The method of the response that carried it (`GET`). */
method: string
/** The path of the response that carried it (`/api/tags`). */
path: string
/**
* Whether the trace PROVES the page dropped the text: the named response is a successful GET
* of the collection that started after the last navigation, and the text is absent from the
* page's own failure snapshot (`traceArtifactsScript`).
*
* Absent when the evidence is weaker — a creation POST carried the text (a button failure
* was not a missing article), the snapshot still showed it, or the trace recorded no clock —
* and the note then says only that a response contained the text.
*/
dropped?: true
}
TraceReadContradiction
A write the trace recorded answering a boolean field, and a LATER GET of the same resource answering the opposite for that field.
This is the pair that reads as a frontend race and is not one: a follow
test sent POST /api/profiles/:username/follow and the API answered
{"profile":{…,"following":true}}, then a GET /api/profiles/:username answered
{"profile":{…,"following":false}} — the READ route never saw the viewer, so it hydrated
following from nobody. The run rewrote the profile component twice, the API client once, and
added optimistic state before anyone read the route's middleware; the write itself was fine.
interface TraceReadContradiction {
/** The boolean field both answered (`following`, `favorited`). */
field: string
/** What the write's response said it is. */
writeValue: boolean
/** What the later read's response said it is. */
readValue: boolean
/** The write that answered it (`POST /api/profiles/x/follow`). */
write: TraceRequest
/** The later GET of the same resource (`GET /api/profiles/x`). */
read: TraceRequest
}
TraceHiddenBox
A visibility failure whose locator RESOLVED: Playwright calls an element with a zero-size box "hidden" even when it is painted, so the useful fact is why the box is empty. The trace's own failure snapshot carries the element's children — read here, never guessed.
interface TraceHiddenBox {
/** The locator the assertion printed (`locator('a.navbar-brand')`), or the element it names. */
locator: string
/** The element's tag, lowercased (`a`). */
tag: string
/** The element's own inline style, when the snapshot carries one. */
style?: string
/**
* The `<img>` the element wraps when that image is its only element child and the element has
* no text of its own: the size the box would collapse to.
*/
image?: {
/** The image's `src`, bounded. */
src?: string
/** Its `width` attribute. */
width?: string
/** Its `height` attribute. */
height?: string
/** Its inline `style`. */
style?: string
/** Its `class`. */
className?: string
/** Its `alt` text. */
alt?: string
}
/** True when the element has no text and no element children at all. */
empty?: true
}
TraceCountMatch
One element a failing locator count matched, read from the trace's own failure snapshot.
A count assertion reports only Expected: 3 / Received: 4; the element that made it 4 is not
in the error. Playwright's trace does hold it — either marked __playwright_target__ in the
failure snapshot (expect(locator).toHaveCount(n)), or recoverable by replaying the recorded
selector against the snapshot's DOM in a browser (locator.count() then expect(n).toBe(k)) —
so each match is named by what it is and where it sits, never by a guess.
interface TraceCountMatch {
/** The element's tag, lowercased (`div`). */
tag: string
/** Its `class` attribute, bounded (`card-block`). */
classes?: string
/** Its own text, whitespace-collapsed and bounded. */
text?: string
/** Its ancestors, outermost first (`body > div.comment-form > div.card`), bounded. */
path?: string
/** True when a `<form>` is one of its ancestors — the shape of an extra form-internal match. */
inForm?: true
}
TraceCountMismatch
A failing assertion that compared a LOCATOR COUNT (expect(await locator.count()).toBe(n) or
expect(locator).toHaveCount(n)), with the locator the trace recorded and, when the failure
snapshot can supply them, the elements it matched.
A comments.spec.ts:86 assertion sat on Expected: 3 / Received: 4 for ~30
minutes and three whole suite walks: the helper counted .card:not(.comment-form) .card-block,
the app's comment form was a .comment-form wrapper around a plain .card, and the form's own
.card-block made the fourth. The trace had the selector (its Frame.queryCount entry) and the
four elements (its failure snapshot); the note printed neither. This reading prints both, and
fails closed — a selector outside the browser's own CSS support, a missing browser, or a replay
that disagrees with the recorded count names no elements rather than inventing them.
interface TraceCountMismatch {
/** The locator as the trace or the assertion printed it (`locator('.card:not(…')`). */
locator: string
/** The selector inside that locator, when the trace recorded one. */
selector?: string
/** The number the assertion expected. */
expected: number
/** The number the page matched. */
received: number
/**
* Where the locator came from: the assertion's own message, or the `locator.count()` entry the
* trace recorded just before the failing assertion.
*/
source: 'assertion' | 'locator-count'
/** The matched elements, bounded to `MAX_COUNT_MATCHES` in document order. */
matched?: TraceCountMatch[]
/** How many elements matched in total, before the display bound. */
matchedTotal?: number
/**
* How the elements were read: Playwright's own `__playwright_target__` marks in the failure
* snapshot, or the recorded selector replayed against that snapshot in a browser.
*/
matchedFrom?: 'snapshot-targets' | 'selector-replay'
/**
* Why no elements are named, when they are not. `unsupported-selector` is a selector the
* browser's `querySelectorAll` rejects (a `getByRole`/`getByText` engine, `>>` chaining);
* `no-snapshot` is a trace with no readable DOM snapshot at the failure; `count-mismatch` is a
* replay that disagreed with the recorded count, so the snapshot is not evidence for this
* assertion; `browser-unavailable` is a project whose Playwright module or recorded engine
* executable could not be resolved, so the selector could not be replayed at all.
*/
unreadable?: 'unsupported-selector' | 'no-snapshot' | 'count-mismatch' | 'browser-unavailable'
}
TraceArtifact
What one trace says: the test it belongs to, the requests it made, and its console lines.
interface TraceArtifact {
/** The failure's spec file, relative to the run's directory, when the trace names one. */
spec: string | null
/** The line of the test's last traced step, 0 when the trace names no spec. */
line: number
/** The requests the page made, the interesting ones first (`traceArtifactsScript`). */
requests: TraceRequest[]
/**
* This attempt's recorded whole-test timeout, with successful response waits covering at least
* half its budget and one wait of at least one second. Overlapping waits count once, across
* this test's contexts, before request display caps. A final browser wait that began before
* the last fifth of the budget, an HTTP failure or a page error leaves this absent: earlier
* slow traffic must not excuse a long missing-locator wait or a concrete application error.
* Request groups at the existing `TRACE_NOTE_LOOP_REPEATS` threshold keep their loop diagnosis.
* These are browser response clocks, not measurements of server CPU or proof the app is correct.
*/
timeoutTiming?: {
budgetMs: number
responseWaitMs: number
slowest: { method: string; path: string; status: number; waitMs: number; totalMs: number }[]
}
/**
* The request the failing step itself sent: the first answered request the test's last user
* action caused (`TraceArtifact.lastAction`), else — on a trace with no action clock — the
* trace's LAST `fetch`/`xhr` in recording order, else its document. It leads the note's row when
* `lastAction` is absent, because a click that changed nothing is explained by the request
* the click sent and what came back — a Follow click sent
* `DELETE /api/profiles/x/follow → 200` (its `following` state was stale) and the note listed only
* the test's earlier, answered requests.
*
* Absent when the trace recorded neither, and on traces read before this field existed.
*/
lead?: TraceRequest
/**
* The console lines and page errors the page raised: its errors first, then a line that names a
* session decision or comes from a molecule package, then any other warning, then the browser's
* own resource error (`traceArtifactsScript`).
*/
console: string[]
/**
* The test's LAST user action before the failing assertion ON THE PAGE THE ASSERTION RAN ON, and
* the requests it caused — what the row leads with, when the trace carries the action times
* (`TraceLastAction`).
*
* A test that opens a second browser context writes one trace member per context, and the
* archive does not order them by time: the last action of the concatenation may belong to the
* helper's page while the assertion failed on another. The action is
* therefore the failing page's own, and its `pageAfter` is that page's last frame snapshot.
*
* Absent on traces read before this field existed, on traces whose network entries recorded no
* clock, and on a trace with more than one used context whose failing page cannot be identified
* (`TraceArtifact.unattributed`) — the row then falls back to `lead`, or to no
* causal claim at all.
*/
lastAction?: TraceLastAction
/**
* The page's own actions in the order the trace recorded them, bounded — what a test that ran
* out of a per-test budget spends its time on. A test that repeats one action prints it once per
* repeat, so the gap between two starts is one repeat's measured cost. Scoped to the page the
* failing assertion ran on; a second browser context's actions are not this test's page.
*/
actions: TraceAction[]
/**
* True when the trace held more than one browser context and none of them could be tied to the
* failing assertion's page. The note then makes no causal claim — no "the test's last action",
* no "the page stayed at …" — rather than attributing one context's click and URL to another
* context's assertion.
*/
unattributed?: true
/**
* The browser contexts the test opened BESIDES the failing assertion's page, with the app
* requests each made. Kept apart so the note can name them as set-up work instead of printing
* their requests as the failing action's effects.
*
* Absent when the trace recorded one context only, when every other context made no request,
* and on traces read before this field existed.
*/
otherContexts?: TraceContextEvidence[]
/**
* The text the failing assertion waited for and a same-page API response carried, when the trace
* recorded both. The note leads with it: the value reached the browser and the page did not
* render it, so the next read is where that response is mapped — never the API or the selector.
*
* Absent when the assertion waited for no text (a text-free selector, a strict-mode violation),
* when no page-scoped `fetch`/`xhr` answered 2xx/3xx with the text in its body, and on traces
* read before this field existed.
*/
missingText?: TraceMissingText
/**
* A write's answer a later GET of the same resource contradicted — the read route does not see
* the viewer (a `following` flag that reads as `false`). The note leads with it and sends the
* run at
* the route's middleware, not the page's state handling.
*
* Absent when no write and later read in the trace answered the same boolean field differently,
* and on traces read before this field existed.
*/
readContradiction?: TraceReadContradiction
/**
* A visibility failure whose locator RESOLVED into an empty box — Playwright's "hidden" — with
* the element's children read from the failure snapshot (`TraceHiddenBox`). The note uses
* it to name why the box is empty (an `<img>` with no CSS size, a textless element) instead of
* leaving the run to probe computed styles.
*/
hiddenBox?: TraceHiddenBox
/**
* A failing assertion that compared a locator count, with the locator the trace recorded and the
* elements its failure snapshot matched (`TraceCountMismatch`). The row prints them, so a
* count that is off by one names the extra element instead of leaving the run to probe for it
* (a 30-minute `Expected: 3 / Received: 4` hunt).
*/
countMismatch?: TraceCountMismatch
/**
* The method+path groups this test's page sent `TRACE_NOTE_LOOP_REPEATS` times or more,
* most-repeated first — a render loop the note leads with (2,106
* `GET /api/articles/<slug>` in one test, printed as four identical `→ 200` lines). Counted over
* every network entry of the failing page, not the capped `TraceArtifact.requests` list.
*
* Absent when no group reached the threshold, and on traces read before this field existed.
*/
repeated?: TraceRequestRepeat[]
/**
* The directory the trace was read from, relative to the root the reader was given.
*
* Playwright saves one directory per test attempt under the run's `outputDir`, and every artifact
* of that attempt — `trace.zip` included — sits in it. The run's own machine report records each
* test that wrote a trace with its attachment path, so this relative directory is the exact mark
* binding THIS artifact to the test that wrote it, with no join by spec line needed
* (`./playwright-report.js`).
*
* Absent on traces read before this field existed.
*/
dir?: string
}
TraceRunFailure
What the runner's own report says about ONE failing test: where the test is declared, which Playwright call its failure names, and the per-test deadline the failure measured against.
A trace cannot tell a navigation that ran out of budget from a selector wait that did. A 15 s
page.waitForSelector timeout can leave a trace whose Frame.goto
never finished (the test was cut off mid-navigation) with a /src/components/*.tsx module still
pending when the context closed — and the note read that as an asset hang, then sent the run to
re-run the same tests unchanged against the same dev server while the same result's
testRunNote was telling it to measure a production build.
interface TraceRunFailure {
/** The spec file the runner's heading names (`e2e/url-navigation.spec.ts`). */
spec: string
/** The line the test is DECLARED on, from that heading (`206`). */
line: number
/** The Playwright call the failure names (`page.waitForSelector`, `page.goto`), or null. */
operation: string | null
/** The per-test deadline the failure names, in ms (`15000`), or null when it names none. */
budgetMs: number | null
}
TraceRunReport
The runner's own report, beside the traces it wrote.
interface TraceRunReport {
/**
* One entry per failing test, as the runner printed them. Empty when the caller supplied none:
* without the runner's reported operation a pending asset is never called the cause.
*/
failures?: readonly TraceRunFailure[]
/**
* True when the same result's `testRunNote` already names a production build as the next
* measurement (a local dev-server walk that ran out of its per-test budget). The note then
* states the ONE next step instead of directing an unchanged same-target re-run that
* contradicts it.
*/
productionBuildAdvised?: boolean
/**
* The endpoints the app's own auth config names for a credential exchange — a login, a
* registration, a token endpoint (`loginEndpoint: '/users/login'`, resolved from the app's
* source). A 401/403 there answers credentials the app was ASKED to check, never a token the
* client failed to attach, so the note says so even when the path is mounted somewhere unusual.
* Empty when the caller could not read the app's config.
*/
authEndpoints?: readonly string[]
/**
* The app source files whose code sends a repeated request, read by the caller from the
* project (`app/src/**`) before this note is written. A loop's sentence names the component to
* read instead of leaving the run to search for it (the component's own file).
* Empty when the caller could not read the app or no file states the path.
*/
callSites?: readonly { method: string; path: string; file: string }[]
}
DiagnosisTraceRewrite
A command with the trace flag this platform decided to add, and the sentence to report it in.
interface DiagnosisTraceRewrite {
/** The command to run. */
command: string
/** One sentence naming the flag and why, or null when nothing was added. */
change: string | null
}
ExecutionBackend
Abstraction over the execution environment. Implemented by SandboxBackend (Docker) and LocalBackend (host filesystem).
interface ExecutionBackend {
/** The root directory for all operations (e.g. '/workspace' or '/Users/.../project'). */
readonly projectRoot: string
/**
* Marks backends that operate DIRECTLY on the host filesystem (the local
* backend), as opposed to a contained sandbox. Consumers use it to judge
* how loud to be about disabled safety guards — a `..` path or symlink
* escape on a host backend reaches the operator's real files, while the
* same escape in a sandbox stays contained.
*/
readonly hostFs?: boolean
/** Read a file's content as UTF-8 string. */
readFile(path: string): Promise<string>
/** Write content to a file. Creates parent directories as needed. */
writeFile(path: string, content: string): Promise<void>
/**
* Optional single-call path check and bounded text read for write/edit tools.
* `realPath` must be resolved before reading; never read outside `symlinkRoot`.
* Null `content` means missing; omit it for a native read (large/unreadable text).
* Returned text must match readFile's decoding and honor any host file-method wrappers.
* Implementations must use this backend's `run` so host command wrappers still apply.
*/
readFileForUpdate?(
path: string,
symlinkRoot?: string,
): Promise<{ realPath: string; content?: string | null }>
/**
* Optional write followed by the supplied parse command in one transport call.
* Null means unsupported BEFORE a successful write; the caller uses writeFile/run.
* Never retry a transport error after a write may have landed. After-write and
* file-change hooks use the ordinary path so their ordering before parsing stays intact.
*/
writeFileAndCheck?(
path: string,
content: string,
command: string,
): Promise<{ stdout: string; stderr: string; exitCode: number } | null>
/**
* Optional whole-file replacement in ONE transport call: resolve `path`, refuse it when it
* resolves outside `symlinkRoot` (nothing written), read the previous text, write, then run
* `command` (the parse check) when one is given.
* Null means nothing was written (unsupported, a file whose text does not fit, a host
* file wrapper); the caller then uses readFileForUpdate/writeFileAndCheck or the native APIs.
* `check` is null when there is no command or its output was cut: the caller reruns the check.
* Never retry a transport error: the write may have landed.
*/
replaceFileAndCheck?(
path: string,
content: string,
command: string | null,
symlinkRoot?: string,
): Promise<
| { realPath: string; refused: true }
| {
realPath: string
refused?: false
oldContent: string | null
check: { stdout: string; stderr: string; exitCode: number } | null
}
| null
>
/** Delete a file. */
deleteFile(path: string): Promise<void>
/** List entries in a directory. */
readDir(path: string): Promise<Array<{ name: string; type: 'file' | 'directory' }>>
/**
* Run a shell command. Returns stdout, stderr, and exit code.
* Backends implement this safely (sandbox.exec for Docker, execFile for local).
*/
run(
command: string,
opts?: {
cwd?: string
timeout?: number
/**
* A budget (ms) the backend enforces INSIDE its own shell, after any
* environment sourcing a consumer wraps around the command — so an
* overrun is stopped where it runs and the output so far still comes
* back, with exit code 124. A backend that cannot enforce it ignores it.
*/
budgetMs?: number
},
): Promise<{ stdout: string; stderr: string; exitCode: number }>
}
SuiteBudgetPin
The supplied suite's own settings, put back on a run whose runner config changes them.
A graded suite is walked by the grader under its own per-test budget, worker count and
timeouts. An executor's run that reads a config setting different numbers measures a run the
grader never sees: a shorter budget fails tests the graded walk passes, a longer one passes
tests the graded walk times out on. The platform that knows the suite supplies these values
before the run (ToolBuildConfig.suiteBudget); the shared tool puts the flags on the
runner's own command line, where Playwright lets them win over every config file.
interface SuiteBudgetPin {
/**
* The Playwright flags that carry the suite's own settings onto the command
* (`--timeout=15000`, `--workers=1`), as the consumer's own scan reads them. Empty when the
* difference is in settings no flag carries.
*/
flags: string[]
/** One sentence for the run's result: which of the suite's own settings this run uses. */
note: string
/**
* A config file the consumer wrote OUTSIDE the supplied suite, which re-imports the config the
* run selected and pins the settings no Playwright flag can carry (`expect.timeout`,
* `use.actionTimeout`, `use.navigationTimeout`). When present, the run is launched with
* `--config <this path>` in place of the config it named, so those settings are the suite's own
* rather than the executor's. Absent when the consumer could not write one.
*/
config?: string
/**
* Every setting the derived config (`config`) pins at the suite's own value, by the scan's
* key (`timeout`, `expect.timeout`, `actionTimeout`, `navigationTimeout`), in milliseconds as
* digits. Empty when no derived config was placed.
*/
values?: Record<string, string>
/**
* Every setting the run's own config makes different from the suite's, as the consumer's scan
* read them: the value this run's config writes and the suite's own. The tool reports the ones
* its placement did NOT put back, so a result never claims a drift it carried.
*/
drift?: Record<string, { used: string; suite: string }>
}
ToolBuildConfig
Configuration for building the tool set. Allows consumers to customize security, callbacks, and tool selection.
interface ToolBuildConfig {
/** Which tools to include. Defaults to all. */
include?: string[]
/** Which tools to exclude. Applied after include. */
exclude?: string[]
/** Whether to validate paths stay within projectRoot. Default: true. */
pathGuards?: boolean
/** Whether to check symlinks resolve within projectRoot. Default: false (sandbox-only). */
symlinkGuards?: boolean
/** Whether to redact secrets in file reads and command output. Default: true. */
redactSecrets?: boolean
/** Whether to block dangerous shell commands (env dumps, /proc access). Default: false. */
blockDangerousCommands?: boolean
/**
* Consumer-specific command guard for `exec_command`, checked BEFORE execution (after
* the built-in dangerous-command check). Return an error string to block the command —
* it is returned to the model verbatim, so make it actionable (say what to do instead) —
* or `null`/`undefined` to allow it. Keeps environment-specific rules (e.g. an IDE
* sandbox forbidding installs that would break its preinstalled library) out of this
* shared package.
*
* @param command - The shell command the model asked to run.
* @param cwd - The resolved working directory it would run in.
* @returns An error string to block, or null/undefined to allow.
*/
blockCommand?: (command: string, cwd: string) => string | null | undefined
/**
* Timeout (ms) for a single `exec_command` run. `exec_command` legitimately
* runs LONG — `npm install`, a production build, a test suite — so the default
* is generous (2 min); the old 30 s hardcap killed those spuriously. A consumer
* that wraps tool calls in its own outer timeout should set this to match (or
* slightly exceed) that budget so its own timeout is the effective bound and
* produces the nicer "tool timed out" message. Quick commands are unaffected —
* this is only the ceiling before a wedged command is killed.
*/
execTimeoutMs?: number
/**
* Budget (ms) for a single `exec_command`, passed to `backend.run` as
* `budgetMs`: the backend runs the command under `timeout` in its own shell,
* so when it overruns it is stopped there and the tool still returns
* everything it printed until then (exit code 124 plus an `error` naming
* the limit). Without this, an outer per-tool timeout races the run and
* discards minutes of build or test output along with the result. Set it a
* little under that outer timeout. Unset = no budget.
*/
commandBudgetMs?: number
/**
* Maximum time (ms) one `wait_for_task` call may wait, independently of the foreground
* `commandBudgetMs`. The caller's requested `timeout` is honoured up to this budget.
* Leave unset to keep the legacy ceiling: `commandBudgetMs` (or 290 s) less a 10 s result
* margin. A host that raises this must also give the tool call a longer outer watchdog.
*/
waitBudgetMs?: number
/**
* Opt in to partial diagnostics for new final failure causes at this known deployed URL.
* Return null when the task has completed or its history is unknown. Repeated causes are silent.
* Only a real suite command with a complete inline failure report can yield; it remains
* running, with no exit code or completed proof. Absent leaves ordinary waits unchanged.
*/
yieldOnFirstFailureFor?: (taskId: string) => string | null
/**
* How long (ms) exec_command waits for a command it backgrounded only because the
* command asked for more than `commandBudgetMs`, before handing back a task
* id; one that finishes inside it returns like a foreground run. Default 45000.
*/
overCeilingGraceMs?: number
/**
* Directory names `search_files` and `find_files` skip (VS Code
* `search.exclude` semantics). Defaults to `DEFAULT_SEARCH_EXCLUDED_DIRS`
* (node_modules, VCS dirs, build output). Pass the consumer's per-project
* setting so every search surface shares ONE synchronized set.
*/
searchExcludedDirs?: string[]
/**
* Whether a LARGE HTML document should come back as its OUTLINE — the head's
* tags and the tags that open each body section, one line each, plus a note
* naming the offset/limit that returns the whole document — instead of its
* whole text. Over `MAX_HTML_INLINE_CHARS`, and only when the read named
* no line window.
*
* A getter, not a boolean, because the answer belongs to the TURN, not to the
* tool set: a host that plans first and builds after wants an outline while the
* executor is researching (where a read it cannot act on is pure context cost)
* and the document itself while it is writing the page. Unset means every big
* HTML read returns its text, which is what a host with no such phases wants.
*
* @returns True when a large HTML read should be outlined rather than returned.
*/
outlineLargeHtml?: () => boolean
/**
* The test titles the person's request EXCLUDES by name (molecule-dev's `excludedTestTitles`),
* asked when a finished suite run's cause note is built. Their failures are not causes to fix:
* the note drops them, says so at the end, and inverts them out of the narrowed re-run it hands
* over — a result must never name a test beside "it does not count" (an executor once spent a
* turn and an edit on the excluded test).
*
* A getter, not an array, because the request is read per turn while the tool set is built
* once. Unset means no test is excluded.
*
* @returns The quoted titles the request carves out.
*/
excludedTestTitles?: () => readonly string[]
/** The `NAME=value` settings the person's request REQUIRES of a suite run (molecule-dev's `requiredRunSettings` — its mode, say), asked when the cause note compos… */
requiredSuiteEnv?: (
command: string,
cwd: string,
) => Promise<readonly { name: string; value: string }[] | null | undefined>
/** The supplied suite's own budget, when the Playwright config a command would load sets different settings, asked BEFORE the run executes. */
suiteBudget?: (command: string, cwd: string) => Promise<SuiteBudgetPin | null | undefined>
/**
* A whole walk's duration in ms, as the consumer measured it. A suite run the executor detached
* whose own `timeout` is shorter than this is lifted; unset lifts only a bound no longer
* than this tool's ceiling.
*
* @param command - The suite command.
* @param cwd - The run's working directory.
* @returns The duration in ms, or null.
*/
suiteRunMs?: (command: string, cwd: string) => Promise<number | null | undefined>
/** Post-write hook (e.g. auto-format via Prettier/ESLint). Called after every write_file/edit_file. */
onAfterWrite?: (path: string) => Promise<void>
/**
* Prepare a background command script after it is written, before launching it.
* Hosts may validate or rewrite this script without overriding ordinary file writes
* (which would disable safe transport batching). A rejection prevents launch.
* The script runs in `BACKGROUND_SCRIPT_SHELL` (bash); a parse check asks that same shell.
*/
prepareBackgroundScript?: (path: string, content: string) => Promise<void>
/** Diff tracking callback. Called before writes with old/new content. */
onFileDiff?: (event: FileDiffEvent) => void
/**
* Change notification, called once the change is on disk: on write_file, edit_file,
* create_directory, delete_file and rename_file. It only reports; the tool does not wait for it
* and does not re-read the file after it, so a hook that changes the file it was told about
* (a formatter) belongs in `ToolBuildConfig.onAfterWrite`, which is awaited before the
* parse check. Setting it keeps the batched write-and-check transport.
*/
onFileChange?: (event: FileChangeEvent) => void
}
(The 2 longest member comments are shortened to their first sentence to fit; the full declaration is in node_modules/@molecule/api-ai-tools/dist/types.d.ts.)
FileDiffEvent
Payload emitted when a tracked file changes contents.
interface FileDiffEvent {
path: string
oldContent: string | null
newContent: string
}
FileChangeEvent
Payload emitted when a file is created, modified, or deleted structurally.
interface FileChangeEvent {
type: 'created' | 'modified' | 'deleted'
path: string
}
SkillEntry
Metadata for a discovered skill (used in PromptContext).
interface SkillEntry {
/** Skill name. */
name: string
/** Short description. */
description: string
/** Relative path to the SKILL.md file. */
path: string
}
PromptContext
Context for building a composable system prompt.
interface PromptContext {
/** Agent identity (e.g. 'Synthase', 'Polish Agent'). */
agentName: string
/** Project root path. */
projectRoot: string
/** Names of available tools (for the tool listing section). */
tools: string[]
/** Project-specific rules (AGENTS.md or CLAUDE.md content). */
projectDocs?: string
/** Additional skill/reference content to inject. */
skills?: string[]
/** Discovered skills to list in the prompt (use load_skill to read on demand). */
discoveredSkills?: SkillEntry[]
/** Custom sections to append to the prompt. */
customSections?: string[]
}
SuiteFilterStrip
A command with the output filters after its suite runner removed.
interface SuiteFilterStrip {
/** The command to run. */
command: string
/**
* The pipeline stages dropped, as written (`| grep … | tail -20`), or '' when none were. A
* command with several suite runs lists one group per run, joined by a space.
*/
dropped: string
}
SuiteRunPipelinePlacement
Whether a finished run's exit code belongs to a stage after the suite runner.
interface SuiteRunPipelinePlacement {
/**
* True when a pipe this tool must not drop still follows the suite runner: the code in the
* result is that stage's, not the run's.
*/
piped: boolean
/**
* True when the suite (or a stage of its pipeline) sits inside a nested `sh -c '<command>'`
* string, so the parse cannot place it in the command's own text. The caller then says so
* plainly instead of implying a stage it can point at — and keeps the command's own code when
* no pipe follows the runner, because on that command the pipeline's last stage IS the run.
*/
unplaced: boolean
}
RunningLogRead
A bounded, contiguous read of a running task's own log.
interface RunningLogRead {
/** The log's last `RUNNING_LOG_READ_BYTES` bytes, contiguous, as one string. */
text: string
/** How many bytes the WHOLE log holds, or null when the read did not answer its size. */
bytes: number | null
}
FailedTest
One failed test, as a running suite's log names it.
interface FailedTest {
/** The location the log writes (`specs/e2e/articles.spec.ts:32`), or '' when it writes none. */
where: string
/** The test's own title — the last segment of its title path. */
title: string
/** How long it ran before failing, in seconds, or null when the log does not say. */
seconds: number | null
}
RepeatingFailure
A cause repeating among a running suite's failures.
interface RepeatingFailure {
/**
* How many DISTINCT tests share the signature — a test printed twice (two reporters in the
* log) or failed twice (a retry) is one test.
*/
count: number
/** The shared error line, when the log carries the failures' bodies (`line` reporter). */
message: string | null
/** The shared duration in seconds, when the failures line up by how long they ran. */
seconds: number | null
/** The distinct tests that share it, in log order. */
tests: FailedTest[]
}
UniversalCause
A repeating cause that is failing the WHOLE run — see universalCause.
interface UniversalCause {
/** How many distinct tests share it. */
count: number
/** The distinct spec files they live in, in the order the log named them. */
files: string[]
/**
* The cause is that the page rendered NOTHING: every failure so far is a wait for an element
* the page never painted, whatever the selector asked for (`emptyPageCause`). One cause
* is failing every test even though no two failures share an error signature, so the note says
* so in the page's terms instead of naming one locator as the signature.
*/
pageRendersNothing?: true
/** The page's own uncaught error, when the run printed one. */
pageError?: string
/**
* The distinct failures this cause covers, in log order — the rows a note lists for
* `pageRendersNothing`. Absent for a signature cause, whose rows are the repeating
* failure's own tests.
*/
tests?: FailedTest[]
}
FailureCause
One cause of failure in a run, and the tests it hit.
interface FailureCause {
/** The error line its tests all reported, or null when only the duration ties them together. */
message: string | null
/** The duration they shared in seconds, or null when the error line is the signature. */
seconds: number | null
/** The distinct tests it hit, in the order the log named them. */
tests: FailedTest[]
/**
* The FIRST failure's two most useful body lines — the values that differ, or the locator from
* its `Call log` (`failureEvidence`) — so a fix round needs no re-read of the log. Empty
* for a duration group, whose blocks carried no bodies.
*/
evidence: string[]
/**
* The suite's own per-test budget in ms, when the cause is the test-budget kill
* (`Test timeout of 15000ms exceeded`). The signature normalizes the number away
* (`normalizedSignature`) so equal causes group, and that number is the one fact that
* predicts a test spending its budget on a repeated action.
*/
budgetMs?: number
/**
* The layer the failure came from (`classifyRunFailure`). A `connection` cause never
* reached the app, so it is NOT a cause the app's code can fix: the note says to re-run it
* once and read the app's log on a repeat, instead of sending a fix at a handler
* (a CORS middleware was rewritten for a 20 s connection timeout).
*/
kind: RunFailureKind
/**
* What the page itself showed at the moment of the failure, when the caller read it from
* Playwright's `error-context.md` (the alert / error list). The failure's own error line names
* the symptom — `waitForURL` timed out — and never what the page was saying: eight
* `waitForURL` timeouts were grouped under one line while the page snapshots named
* the cause (`email can't be blank`, `username can't be blank` — the settings form submitted
* before its values had loaded). Attached to the cause so the fix needs no `cat` of the file.
*/
pageShowed?: string[]
/**
* An adjacent awaited click in this failure's source frame, before its positive state wait.
* This proves the browser action returned, not that the app accepted it or a request settled.
*/
precedingClick?: { call: string; where?: string }
}
CausePageErrors
One failing test's page errors, as read from its error-context.md.
interface CausePageErrors {
/** The test's location as the log prints it (`settings.spec.ts:107`). */
where: string
/** The alert / error items the page showed at the moment it failed. */
items: readonly string[]
/**
* The landmark roles the test's page snapshot printed (`navigation`, `banner`), read from the
* YAML block of its own `error-context.md`. Present ONLY when the caller has that test's
* snapshot; an empty array means the snapshot was read and showed no landmark, while an absent
* field means nothing was read and no claim may be made (`missingHeaderNote`).
*/
landmarks?: readonly string[]
/**
* Whether the test's snapshot showed populated page content (headings, paragraphs, links,
* list items, buttons), the other half of the missing-header reading: a page that painted its
* main content but no navigation.
*/
populated?: boolean
}
Types
CommandRunState
What a command's result records: a run that ended, or one a budget stopped.
type CommandRunState = 'ran' | typeof CUT_AT_BUDGET
CutBy
What stopped a run.
type CutBy =
/** This tool's own budget (the backend's `timeout`, just past it). */
| 'tool-budget'
/** The `timeout <N>` the command itself carried. */
| 'command-timeout'
/**
* Something outside the run: the runner's summary does not account for the total it announced,
* and neither of the two bounds above had fired — the process was killed by something this
* platform does not own (the sandbox's own process supervisor, the box going away, a signal).
*/
| 'process-stop'
RunFailureKind
The layer a failure came from: the transport (no answer at all), the response's status, or an assertion over a response that arrived.
type RunFailureKind = 'connection' | 'status' | 'assertion'
ConnectionFailureKind
What the transport did when a request never got an answer.
type ConnectionFailureKind = 'timeout' | 'refused' | 'reset' | 'dns' | 'tls' | 'empty'
PlaywrightReportStatus
How much of a report this module could account for.
complete— the runner's stats and its suite tree both parsed: every test entry is present.partial— a report was written but is not a whole run (Playwright's ownerrorsare present, the suite tree is missing, or the file is pastMAX_REPORT_PARSE_CHARS). What is listed is real; what is missing must be read atPlaywrightRunReport.path.malformed— the file exists but is not a Playwright JSON report (truncated, wrong shape). Nothing in it may be treated as runner data.missing— the run left no report (killed beforeonEnd, not a run this wrapper rewrote, or the file was removed). Nothing may be inferred from its absence.
type PlaywrightReportStatus = 'complete' | 'partial' | 'malformed' | 'missing'
DiscoveredSkill (deprecated)
Deprecated: Use SkillEntry from types.js instead.
Re-export SkillEntry as DiscoveredSkill for backwards compatibility.
type DiscoveredSkill = SkillEntry
InstalledPackageProbe
Looks at the filesystem for InstalledPackageFacts.
The guard cannot stat the path itself: the tools act through a backend (a
sandbox over the network for the fleet), so the caller — which holds that
backend — supplies the look. shellInstalledPackageProbe builds one
from any shell runner.
type InstalledPackageProbe = (path: string) => Promise<InstalledPackageFacts>
RequiredLandmark
A landmark role a failed selector requires: <nav>/role=navigation, <header>/role=banner.
type RequiredLandmark = 'navigation' | 'banner'
Classes
ToolInputError
A tool call the handler refuses with a message meant for the model as is —
thrown from deep inside a handler (a path check), returned by the guard as the
call's error without the generic "check your parameters" wrapping.
class ToolInputError extends Error {}
Functions
createLocalBackend(projectRoot)
Create an ExecutionBackend that operates on the local filesystem.
function createLocalBackend(projectRoot: string): ExecutionBackend
projectRoot— Absolute path to the project root directory
Returns: A backend wired to fs/promises and guarded subprocess calls.
createSandboxBackend(sandbox, projectRoot)
Create an ExecutionBackend that delegates to an isolated sandbox instance. The sandbox.exec method runs inside the provider's isolated environment.
function createSandboxBackend(sandbox: SandboxLike, projectRoot?: string): ExecutionBackend
sandbox— A running Sandbox instance from@molecule/api-code-sandboxprojectRoot— Root directory inside the sandbox (default: '/workspace')
Returns: A backend that proxies all filesystem calls into the sandbox.
standaloneBrowserLeak(source)
The browser variable a standalone script launches and never closes, when that can be proven from the source alone.
The proof is a closed world: one plain TOP-LEVEL launch binding whose engine is genuinely Playwright's, every reference to it a known non-closing method call, and no cleanup, escape or persistent-process path anywhere in the source. A source with two launches is read one binding at a time — a proven leak in either one is enough, because that handle alone keeps Node alive.
function standaloneBrowserLeak(source: string): BrowserProbeLeak | null
source— The script's source, as read from disk.
Returns: The leaking binding, or null when the script is clean or ambiguous.
browserProbeRefusal(probe, budgetSeconds, piped)
The refusal for a foreground command that would run a leaking browser probe: it never returns, and the one move that makes it return is closing the browser (or letting the Playwright runner own it), never moving the leak to the background.
function browserProbeRefusal(
probe: ForegroundBrowserProbe,
budgetSeconds: number,
piped?: boolean,
): string
probe— The leaked probe, fromforegroundBrowserProbe.budgetSeconds— The tool's budget, which the probe would consume whole.piped— Whether the command pipes throughtail/head, which withholds the probe's output.
Returns: The refusal sentence.
browserProbeOverBudgetAdvice(probe)
The over-budget advice for a leak discovered at cut time (the preflight could not read the script before the run — e.g. the same command wrote it). It names the lifecycle fix and says explicitly that the background is not one: a leaked handle hangs there too.
function browserProbeOverBudgetAdvice(probe: ForegroundBrowserProbe): string
probe— The leaked probe.
Returns: The sentence the cut result carries.
createCommandPlan(steps)
Give already-prepared logical commands unique log boundaries.
function createCommandPlan(steps: { id: string; command: string }[]): CommandPlan
steps— Commands in execution order.
Returns: Metadata for the wrapper and the launcher that executes its steps.
commandWithPlan(command, plan)
Preserve a wrapper's typed logical plan in its durable shell script, including across restarts. Shell comments keep this independent of the wrapper's executable, arguments and payload format.
function commandWithPlan(command: string, plan: CommandPlan): string
command— Executed wrapper.plan— Commands the launcher will actually execute and delimit.
Returns: A shell command with a passive metadata header.
commandPlan(command)
Read the shared descriptor, never a launcher's private wrapper format.
function commandPlan(command: string): CommandPlan | null
command— Command or recovered task script.
Returns: A valid logical plan, or null for an ordinary command.
logicalCommandText(command)
Commands a wrapper will run, for static classification; live diagnostics use commandStepView.
function logicalCommandText(command: string): string
command— Executed command.
Returns: Logical commands in order, or the direct command unchanged.
commandStepView(command, output)
Select only the step that owns the latest log boundary. Completed steps cannot supply a live failure, target, retry policy, file selection or rerun. Before the first boundary and between steps the live command is unknown; no diagnostic is permitted.
function commandStepView(
command: string,
output: string,
): {
command: string
output: string
complete: boolean
/** Unique execution step, including when adjacent steps run identical commands. */
stepKey?: string
}
command— Wrapper or direct command.output— Whole log, or the boundary-preserving bounded read.
Returns: Active command and its output, plus whether the entire step's output is available.
commandPlanLogRead(plan, limit)
AWK program for a bounded read that retains the active boundary even after a long step and discards prior steps. A truncated step cannot establish a universal failure across its history.
function commandPlanLogRead(plan: CommandPlan, limit: number): string
plan— Logical plan whose boundaries the launcher emits.limit— Maximum output characters retained for diagnosis.
Returns: An AWK program; callers shell-quote it like every other argument.
durationSeconds(word)
The seconds a duration word stands for.
function durationSeconds(word: string): number | null
word— A duration (280,20s,1m).
Returns: The seconds, or null when the word is not a duration.
endsInBackground(command)
Whether the outer shell's final statement starts a background job. Inner shell strings have their own job tables and do not count.
function endsInBackground(command: string): boolean
command— The shell command.
Returns: Whether its final statement ends with the shell's & operator.
commandSegments(command)
The segments of a command, each with its program and arguments — the answer every classifier that reads a command as "this runs the suite" is asking for.
function commandSegments(command: string): CommandSegment[]
command— The shell command.
Returns: One entry per statement or pipeline stage that runs something, in order.
commandSubstitutions(command)
The direct executable command-substitution bodies in shell text, in source order.
Uses the same quote, comment and heredoc boundaries as executedCommands.
Single-quoted and escaped text is inert. Nested substitutions stay inside their
parent's body so a caller can recurse with a separate working-directory scope
for each body; a cd inside one must not affect its sibling or the outer shell.
function commandSubstitutions(command: string): string[]
command— The shell text to read, including any leading assignments.
Returns: Each direct $(…) or backtick body, without its delimiters.
executedCommands(command)
Every command a shell command actually executes, at any depth — the statements themselves, the
body of a sh -c '<command>', and the body of every command substitution ($(…), backticks).
This is the reading a policy that asks "does this command run X" needs, and it is deliberately
not a text match. The command-position parser already knows what runs and what is only quoted
data (commandSegments), so a pattern never reads a | inside a quoted grep alternation
as a pipeline: grep -E "USER CALLS|ENV|BUTTON" app.log prints log lines, and the ENV in
its pattern starts nothing — a text match would block exactly that call as an environment
dump. What the shell DOES run stays visible through the same walk: a bare
launcher (ls | env), a shell string (bash -c 'env'), a substitution
(echo "$(printenv)") and a nested one (sh -c 'x; env') are all commands here.
commandSegments answers what a pipeline stage runs for a caller matching a runner; this
answers with the launcher left standing when it runs alone, since that is what the shell
executes then.
function executedCommands(command: string): ExecutedCommand[]
command— The shell command.
Returns: Each command the shell executes, in the order the shell reaches them.
locatedCommandSegments(command)
Every statement of a command, with its own assignments and where it sits — assignment-only statements included, because the variables those persist are exactly what a later statement of the same command reads.
function locatedCommandSegments(command: string): LocatedCommandSegment[]
command— The shell command.
Returns: One entry per statement or pipeline stage, in order.
statementArgumentEnd(command, start, end)
Where an option of a statement's program belongs: one past the statement's last ARGUMENT.
A flag written "at the end of the command" is not the runner's: a statement can end on a
redirection (… 2>&1), and a statement can sit inside a group whose closer belongs to the
shell, not to the words (( … ), { …; }). Appending after that closer is a different shell
word that the group has already closed — … --config=x 2>&1) --reporter=list is
sh: Syntax error: word unexpected, which kills a backgrounded walk at once and pushes the
model off the platform's runner shape. Write the option where
the program's own arguments end and the rest of the statement still parses:
… --config=x --reporter=list 2>&1).
The statement must be one locatedCommandSegments placed in THIS command: a statement
inside a nested sh -c '<command>' string has no offsets here (its positions are positions in
that string), so null is returned rather than a splice into the outer text.
function statementArgumentEnd(
command: string,
start: number | null,
end: number | null,
): number | null
command— The shell command.start— The statement's first character (LocatedCommandSegment.start).end— One past the statement's last character (LocatedCommandSegment.end).
Returns: The offset to write the option at, or null when the statement cannot be placed here.
statementBoundary(command, start, end)
Where a statement's own text ends, and whether it leaves a group open.
A statement can be written inside a subshell or a brace group, and the tokenizer attaches an
adjacent closer to its last word because no separator comes between them: ( … | tail -25)
parses its last stage as tail with the argument -25). LocatedCommandSegment.end
therefore says one past the ), and a caller cutting that stage out of the command takes the
group's closer with it — the rewritten command is then ( … 2>&1, which no shell parses
(a heredoc config plus a parenthesized Playwright pipeline came back as end of file unexpected from the background runner).
The parse's own group depths answer which closers belong to an enclosing group: the depth a
statement was written at is its first character's depth (an opener is recorded at the depth
BEFORE it opens), and every character of that statement's own words is at that depth or deeper.
A closer at a LOWER depth closes a group opened before the statement, so it is not the
statement's text. A character inside a quote (-1) is literal text and stops the walk: grep 'a)b' ends on its own quote, not on a closer.
The same depths answer the other dangerous cut: a stage that OPENS a group it does not close
(| { cat when the } follows a ;) has its closer outside the stage, so dropping the stage
alone leaves that closer dangling.
function statementBoundary(
command: string,
start: number | null,
end: number | null,
): { textEnd: number; leavesGroupOpen: boolean } | null
command— The shell command.start— The statement's first character (LocatedCommandSegment.start).end— One past the statement's last character (LocatedCommandSegment.end).
Returns: The offset of the first character that is not the statement's own text, and whether the statement leaves a group it opened still open; null when it cannot be placed in this command.
commandTimeoutSeconds(command)
The bound a command puts on its own run: the largest timeout <N> any of its segments runs
under (timeout 280 hurl --test … → 280), or null when it carries none.
This is the bound man timeout enforces by KILLING the command — so a run that used it did not
finish, whatever the pipeline's own exit status says. It is read here, from the same parse every
other command reader uses, rather than matched as text: timeout in an argument
(grep -n 'timeout 280' notes.md) bounds nothing, and -k 5 is the grace before the kill, not
the bound (WRAPPER_VALUE_FLAGS). A timeout on a statement in a loop bounds each pass, not
the command (CommandSegment.repeated): three timeout 25 curl … passes can run 77 s and end
in an inner 124 that no bound of the command's fired.
function commandTimeoutSeconds(command: string): number | null
command— The shell command.
Returns: The seconds the command allows itself, or null.
withoutTimeoutWrapper(command, which)
The command with the timeout <N> wrapper lifted off the statements which selects, and the
largest bound that was lifted.
The platform moves a run to the background precisely because its own bound cannot fit this
tool's ceiling, and a background task has no ceiling — its wait is bounded by wait_for_task
and the turn's deadline. The timeout N an executor wrote to fit the ceiling therefore keeps
killing the run at N in the background, where nothing needed it: an executor wrote
timeout 280 for a 31-test walk, the tool backgrounded it, and the prefix stopped the walk
with no tally — then the cut sentence told the executor to "run it in the background",
which is where it already was.
The wrapper is found by the same parse every other command reader uses (commandStart):
timeout in an argument bounds nothing, and the wrapper's own flags (-k/--kill-after,
-s/--signal) are stepped over, so timeout -k 5 280 … is 280.
function withoutTimeoutWrapper(
command: string,
which: (segment: CommandSegment) => boolean,
): { command: string; seconds: number | null }
command— The shell command.which— The statements to lift the wrapper from (a suite run, for the background path).
Returns: The rewritten command, and the largest lifted bound (null when nothing was lifted).
runsInCommandPosition(command, pattern)
Whether any segment of the command runs a program whose command-position text matches
pattern — the one question a runner-kind table asks.
The pattern is matched against program and its arguments as one line, so it must be
anchored at ^; it must not carry the g flag (a pattern shared between calls would then
carry its own match position from one segment to the next).
function runsInCommandPosition(command: string, pattern: RegExp): boolean
command— The shell command.pattern— An anchored pattern for the runner's invocation.
Returns: True when a segment in command position matches.
commandRunState(result)
The state a command's result records — THE reader every verdict about a run goes through.
A result that carries no state is a run that ended: the state is written where the run is
stopped (commandCutRun), so a result without it was never stopped by a budget this
platform set or can see. Results produced before this state existed read the same way, which is
what keeps a past turn's tally readable.
function commandRunState(result: unknown): CommandRunState
result— The exec_command / wait_for_task result.
Returns: The state the result records.
suiteSummary(text)
What the runner's closing summary accounts for, or null when it printed none.
Three runners' summaries are read, each by its own wording: Playwright's per-status lines
(reconciled against its Running N tests announcement), Vitest's single Tests … line (its own
parenthesised total), and Hurl's Executed files: block (which it prints only at the end, and
which announces no total — so it is a finish by construction).
function suiteSummary(text: string): SuiteSummary | null
text— The run's stdout and stderr, RAW (a truncated copy can lose the announcement).
Returns: The summary, or null when the text carries none.
suiteTally(text)
Whether text carries a runner's closing summary.
A summary is NOT a finish on its own — a stopped Playwright run prints one too. Use
suiteSummary and its finished for that.
function suiteTally(text: string): boolean
text— The run's stdout and stderr.
Returns: True when the runner's own end-of-run summary is there.
suiteRunExitCode(exitCode, output, piped)
The exit code a finished suite run may report.
The code in a background result is the code of the command's LAST pipeline stage. When a stage
after the suite runner still consumes its output (| tee run.log, or a filter the platform could
not prove output-only), that stage produced the code, not the run — and … | grep … | tail -20
can exit 0 for a run with a failure in it. No code is reported
then: the log's own tally decides.
The same reading covers a code of 0 beside a tally that names a failure: whatever ended the pipeline, a run whose log counts a failure did not pass.
function suiteRunExitCode(exitCode: number | null, output: string, piped: boolean): number | null
exitCode— The code the pipeline reported (null when it has none).output— The run's full log.piped— Whether a pipeline stage after the suite runner still consumes its output.
Returns: The code the run may report, or null when the code is the filter's or contradicts the tally.
commandCutRun(command, result, elapsedMs, budgetSeconds, rawOutput)
The run a command's result records as stopped by a budget, or null when the result is a run that ended (or says nothing about a run).
Evidence, in order — never a guess:
- the runner's own summary, when it printed one: it is a finish only if it accounts for the total
the runner announced. A summary that accounts for fewer is a walk a process stopped early, and
falls through to the branches below with its own counts (
suiteSummary). - exit code 124 together with the measured clock reaching the tool's bound, or the command's own smaller bound when that elapsed first. An early 124 without either clock is preserved as the command's own exit; it does not establish a tool-budget cut.
- the command carried its own
timeout <N>, N is inside this tool's budget (a larger one never fires — the tool's does), the run used N, and no runner printed a closing summary: the run was killed at its own bound. Its exit code, when the pipeline handed one back, is the filter's. - the run used this tool's whole budget behind a filter that withheld its output, and printed no closing summary: the budget stopped it, and no code in the result is the run's.
- a summary that does not account for its announced total, with neither bound fired: something
outside this platform stopped the process (
CutByprocess-stop).
function commandCutRun(
command: string,
result: unknown,
elapsedMs: number,
budgetSeconds?: number,
rawOutput?: string,
): CutRun | null
command— The command the executor sent.result— Its result.elapsedMs— How long the command ran, in ms.budgetSeconds— This tool's foreground budget, in seconds (0 when it has none).rawOutput— The run's output BEFORE truncation, when the caller has it: the announcement a summary is reconciled against is the first line a long run prints, which is exactly what a size cap drops. Detection reads this; the sentence's last line still comes fromresult.
Returns: The stopped run, or null.
cutRunFacts(result)
The facts a result records about the run a budget stopped it in — what a reader needs to say how far the run got WITHOUT re-reading its log or re-deriving the counts.
The numbers are read from the runner's own output where it printed them (Hurl's per-file lines,
Playwright's [n/K]), so a caller that can also see the suite itself — the file count of the
*.hurl directory the run walked — fills in the total this could not know, and both then say
the same sentence (cutRunSentence).
function cutRunFacts(result: unknown): CutRun | null
result— The exec_command / wait_for_task result.
Returns: The facts the result carries, or null when it records no stopped run.
cutRunSentence(run)
The first line of a stopped run's result: how far it got, what stopped it, the last thing it printed, and what the reader must do next.
Written to be quotable by the model in one sentence and to leave no room for "nearly passing":
the counts come from the runner's own output (runProgress), and a total the caller
read elsewhere (the suite's own file count) fills in the "of N" it can then state. The sentence
says how many tests the stop left unrun — a number a reader cannot round up to "the suite
passed" — and hands over the one move that survives a long run: run it in the background. An
inline program that only touches local files is the exception (CutRun.inlineScript): it
is not slow, it is stuck, and the background is the one place it must not be sent.
function cutRunSentence(run: CutRun): string
run— The stopped run.
Returns: The sentence.
classifyRunFailure(text)
Classify ONE failure's text — a Hurl error: block, or a Playwright failure message/body.
The transport is read first: a block that carries a connection error AND an assertion is a request whose assertion never ran, so it is a connection failure. Only a block that carries no failure signature at all answers null — unknown is never a connection failure, because a misread transport hides a real app failure behind "just re-run it".
function classifyRunFailure(text: string): RunFailureClass | null
text— One failure's text, as the runner printed it.
Returns: The classification, or null when the text carries no failure this reads.
allConnectionFailures(failures)
Whether every one of the classified failures is a connection failure — the only shape in which no response the app produced was measured.
function allConnectionFailures(
failures: ReadonlyArray<RunFailureClass | null>,
): failures is ReadonlyArray<RunFailureClass & { kind: 'connection' }>
failures— The run's classifications, in printed order.
Returns: True when there is at least one and none of them is the app's.
inlineLocalScriptCommand(command)
The interpreter of an INLINE program that only reads and writes local files — the shape that gets
INLINE_SCRIPT_BUDGET_MS instead of the tool's command budget.
EVERY statement of the command must be proven local, not just one of them: each is either an
inline interpreter program or a plain file utility (LOCAL_UTILITY). A statement that runs
a script FILE (node smoke.mjs, python3 x.py, bash x.sh) or names a program this module does
not know can do anything at all, so the command keeps the full budget.
An inline program with any external effect keeps the full budget too: no network, install, test
runner, build or server verb may appear anywhere in the command (EXTERNAL_EFFECT), and
the command must not be a suite run or a foreground server (the platform's own classifiers).
function inlineLocalScriptCommand(command: string): string | null
command— The command as the executor sent it.
Returns: The interpreter's name (python3, node, …), or null when this is not the shape.
inlineScriptRunawaySentence(interpreter, seconds)
What a cut inline program's result says instead of the background advice: the work never was slow, it is stuck, and re-running it — here or in the background — cannot help.
function inlineScriptRunawaySentence(interpreter: string, seconds: number): string
interpreter— The interpreter the program ran under (python3,node, …).seconds— The short budget it was stopped at, in seconds.
Returns: The sentence the result carries.
normalizeToolInput(schema, raw)
Move known aliases onto the declared parameter names and report what is still missing. Unknown keys are left in place — handlers ignore them, and dropping them would hide a model's intent from anything reading the call log.
function normalizeToolInput(schema: NormalizableSchema, raw: unknown): NormalizedInput
schema— The tool's declared schema.raw— Whatever the model sent as the tool input.
Returns: The normalized input plus the missing-required and aliased lists.
missingParamError(schema, input, missing)
The error a tool returns when a required parameter is still absent after aliasing. Model-facing, so it names the right parameter, what was actually sent, and the shape of a correct call — everything needed to fix it in one turn instead of concluding the tool is broken.
function missingParamError(
schema: NormalizableSchema,
input: Record<string, unknown>,
missing: string[],
): string
schema— The tool's declared schema.input— The normalized input (used to list the keys that were sent).missing— The required parameters still absent.
Returns: A single-sentence-per-clause error string.
guardToolExecute(schema, impl)
Wrap a tool handler so every call is normalized first and a handler that THROWS returns something the model can act on.
The guard deliberately does NOT pre-empt the handler when a required
parameter looks absent: several handlers accept a documented older shape
(edit_file's top-level old_string/new_string) or answer a missing
parameter with far better guidance than a generic message could (edit_file
telling the model to re-read the file). It steps in only where the handler
would otherwise crash — and when it does, a still-missing required parameter
is the accurate diagnosis for that crash, so it is reported as one.
function guardToolExecute(
schema: NormalizableSchema,
impl: (input: Record<string, unknown>, ...rest: never[]) => Promise<unknown>,
options?: GuardOptions,
): (input: unknown, ...rest: never[]) => Promise<unknown>
schema— The tool's declared schema.impl— The raw handler.
Returns: A handler with the same signature, guarded.
guardAITool(tool)
Apply guardToolExecute to a ready-made tool object (the
@molecule/api-ai AITool shape: { name, description, parameters, execute }), returning a copy whose execute is guarded.
Use it at the point a consumer hands its full tool list to the model, so tools built outside this package get the same treatment as the ones built inside it.
function guardAITool<
T extends {
name: string
parameters?: unknown
execute: (input: unknown, ...rest: never[]) => Promise<unknown>
},
>(tool: T, options?: GuardOptions): T
tool— The tool to guard.
Returns: A copy with a guarded execute.
diffLineCount(oldLines, newLines)
Count truly added/removed lines between two line arrays using LCS.
Bounded by construction, so a whole-file edit cannot allocate a quadratic
table here: the longest common prefix and suffix are trimmed first (exact —
those lines belong to every optimal diff, and on the usual small edit they
shrink the table to the edited span), and what is left is capped (see
lcsLength).
function diffLineCount(
oldLines: readonly string[],
newLines: readonly string[],
): { added: number; removed: number }
oldLines— The original lines array.newLines— The modified lines array.
Returns: An object with the number of added and removed lines.
commandRunsNoTests(command)
Whether a shell command invokes a test runner and EVERY such invocation only prints — so the command runs no test at all.
A runner counts only where a shell would RUN it (commandSegments): the word in command
position of a segment, after its wrapper prefixes. A runner named in an argument is not an
invocation — head -30 run-api-tests-hurl.sh and grep -n playwright e2e/README.md name a
file to read, and a --list written inside a file the command writes is not a flag anyone runs
with.
A command that invokes no runner is NOT one of these (false): "the command runs no test" is
then true for ls, which is not the question any caller is asking. The question is whether
the runner invocation each caller read as a run is one.
A command that also runs tests is false however it is spelled: npx playwright install && npx playwright test installs and runs, so a caller that sees playwright test in it is
reading a real run. So is a command carrying a segment this reader cannot place (a script it
does not know, which may start a suite): only the runners and the NO_TEST_PROGRAMS
table can be accounted for, and "only prints" is a claim about the WHOLE command.
function commandRunsNoTests(command: string): boolean
command— The shell command as the executor sent it.
Returns: True when the command invokes a runner only to print.
outputFilterAfterRunner(command, runs, occurrence)
The output filter that follows the runner in command, or null when there is none.
Only stages of the runner's OWN pipeline count (their separator is |), and they are read as
one trailing CHAIN: | grep … | head -40 is two cuts, and removing only the first would leave
the run piped into the second. Every stage after the runner must be a cutting filter and the
chain must run to the pipeline's end — a pipeline that continues into wc -l is not answered
here, because removing the cutting stages alone would still leave the failure hidden. A filter
before the runner (cat run.log | tail -20 && hurl …) reads something else's output and is not
this.
function outputFilterAfterRunner(
command: string,
runs: (segment: CommandSegment) => boolean,
occurrence?: number,
): RunnerOutputFilter | null
command— The command as the executor sent it.runs— Whether a segment is the runner this run is about (the caller knows its own kind:CommandSegment.programis the program, once wrapper words liketimeout 280andnpxare taken away).occurrence— Which runner invocation the output belongs to, 1-based. A command can run the same runner more than once (the suite bare, then withHOST=…), and each invocation carries its OWN pipe; a reader judging the second walk must name the second walk's cut, never the first's.
Returns: The filter and the unfiltered command, or null.
pipelineExitCodeNote(command, exitCode, output)
The sentence an exec_command result carries beside exitCode when the code belongs to a
pipeline's last stage rather than to the check that printed the output.
Two shapes, both from a hand-run check with an unguarded pipe:
- the code says 0 and the output carries failures (
tsc | headreportshead's 0); - the code is non-zero and the checker printed no failures (
tsc | head && tail missing.logreportstail's 1, and the checker was clean).
A command with no pipe, a pipe guarded by pipefail, a pipeline where no checker runs, or a
code and an output that agree all return null.
function pipelineExitCodeNote(command: string, exitCode: number, output: string): string | null
command— The command as the executor sent it.exitCode— The code the shell reported (the pipeline's last stage's).output— The command's raw stdout and stderr, for the checker's own text.
Returns: One sentence naming the stage the code came from, or null.
playwrightAttemptTimings(result)
Preserve native action clocks without turning on browser tracing.
Call only for a failed attempt, from a reporter's onTestEnd. Playwright already holds these
steps even with tracing off; this function starts no recorder, reads no browser and changes no
runner setting. The result identifies slow actions by source location. It cannot distinguish
server, network and browser scheduling inside an action. Titles, arguments and error messages
are excluded because they can contain credentials or form values.
Unfinished steps use the native After Hooks start as their cutoff when present,
otherwise the attempt's end. Inconsistent clocks remain null, never a fabricated zero.
Self-contained so execution tools can emit its source into a sandbox reporter.
function playwrightAttemptTimings(result: {
startTime: Date
duration: number
steps: PlaywrightTimingStep[]
}): PlaywrightAttemptTimings
result— The native attempt's existing clocks and step tree.
Returns: At most 2,000 steps in native tree order, with an explicit omitted count.
selectFeedbackSpecs(project, changed)
Keep the caller's test inventory order and attach the paths that triggered this run. Background passes filter this inventory to known failures and re-run their failed tests; an explicit checkpoint can still run the whole inventory, with failures first. Source syntax, route names and spec prose never decide which test runs or what it should report.
function selectFeedbackSpecs(
project: FeedbackProject,
changed: readonly string[],
): Array<{ spec: FeedbackSpec; sourceFiles: string[] }>
project— The caller's runnable test inventory.changed— Source paths observed by the caller, not an inferred failure location.
Returns: Every known spec, with the same triggering paths.
isPlaywrightFeedbackSource(path)
Whether a source change can alter markup, copy, styling or local runner configuration.
function isPlaywrightFeedbackSource(path: string): boolean
path— The path reported by the host's file-change subscription.
Returns: True for app source and data formats; never a correctness judgment.
createPlaywrightFeedback(options)
Track source writes and answer explicit checkpoints with the project's native Playwright runs.
Nothing runs on a write: a write only advances the source revision. Browser work runs inside
PlaywrightFeedback.check, which the host calls before an action that needs current
results (a deploy). A run the host made itself is handed over with
PlaywrightFeedback.record, so a checkpoint reuses its passes and re-runs only its
recorded failures.
function createPlaywrightFeedback(options: PlaywrightFeedbackOptions): PlaywrightFeedback
options— Source loader and native runner.
Returns: Write tracking, recorded outcomes and an explicit current-revision checkpoint.
readFeedbackSources(backend, sourceRoots, suiteFiles)
Read explicit source roots and supplied helper/spec paths in one backend round trip. The standard filesystem and TypeScript parser own traversal/syntax; this is transport batching.
function readFeedbackSources(
backend: ExecutionBackend,
sourceRoots: readonly string[],
suiteFiles: readonly string[],
): Promise<FeedbackSource[]>
backend— Local or sandbox execution backend.sourceRoots— App source directories, absolute.suiteFiles— Supplied spec/helper paths, absolute.
Returns: Existing, bounded text sources. Missing/unsupported files are ignored.
runPlaywrightFeedback(backend, spec, sourceFiles, revision, options)
Run ONE spec's native command. Callers supply the correctly configured local command and append these runner flags at composition time (rather than modifying shell text here). Native failures are diagnosis, never proof that a complete supplied suite passed.
function runPlaywrightFeedback(
backend: ExecutionBackend,
spec: FeedbackSpec,
sourceFiles: string[],
revision: number,
options: {
command: (flags: string[]) => string
scratchRoot?: string
timeoutMs?: number
emit?: (result: PlaywrightFeedbackResult) => void
pollMs?: number
signal?: AbortSignal
/** Explicit verification keeps the process slot instead of yielding to its own caller. */
foreground?: boolean
/**
* An earlier failed run's record (`PlaywrightFeedbackResult.lastRun`): run only the
* tests it names, with Playwright's own `--last-failed`.
*/
lastFailed?: string
},
): Promise<PlaywrightFeedbackResult>
backend— Existing execution backend.spec— The project spec and its normal per-file command.sourceFiles— Triggering component files, known to the write/index.revision— Source revision the scheduler will validate before delivery.options— Output location, command composition and a bounded backend budget.
Returns: The actual native outcome and actionable failures only.
reportCarriesIdentities(status)
The report statuses for which the report's own per-test identities and attachments may be used.
partial is included because a partial report's suite tree, where it parsed, is still the
runner's own record of which test owns which attachment; malformed and missing are not,
because nothing about them is runner data.
function reportCarriesIdentities(status: PlaywrightReportStatus): boolean
status— One record'sPlaywrightReportStatus.
Returns: True when the record's tests and attachments are the runner's own.
reportTestAttachmentPaths(test)
The attachment paths a stored test record carries, trace first.
function reportTestAttachmentPaths(test: PlaywrightReportTest): string[]
test— One entry ofPlaywrightRunReport.failures, as stored.
Returns: Every saved path the record can prove, in its own order.
reportTestArtifactDir(test)
The directory a test result's own artifacts were saved in, or null when the report names none.
Playwright writes one directory per test attempt under the run's outputDir, and every artifact
of that attempt — trace.zip included — sits in it. The directory is therefore the exact
ownership mark for a trace: two tests' traces are never in one another's directory. A damaged
record whose attachment entries carry no path answers null, so nothing is claimed from it.
function reportTestArtifactDir(test: PlaywrightReportTest): string | null
test— One entry ofPlaywrightRunReport.failures, as stored.
Returns: The posix-normalized directory, or null.
summarizePlaywrightReport(text, options)
Summarize one Playwright json report into the bounded record a tool result carries.
Pure text in, record out: the caller reads the file (and decides whether it may), so this is testable against genuine reports and against malformed controls alike.
function summarizePlaywrightReport(
text: string,
options: { path: string; sanitize?: (text: string) => string },
): PlaywrightRunReport
text— The report file's text, exactly as written.options— Where the file is, and the consumer's redactor for error text.options.path— The report file's path, carried on the record for full evidence.options.sanitize— Redactor applied to error text (defaults to the identity).
Returns: The bounded record; never a verdict.
commandWritesReportTo(command, expectedPath)
The report path a command was launched with, when it is the one this platform sets.
Read back from the launched script (and from a completed task's own command) so a record written
before an API restart is still found: the path is the task's own id derived by
playwrightReportPathFor, never a path parsed out of the executor's command.
function commandWritesReportTo(command: string, expectedPath: string): boolean
command— The command as it was launched.expectedPath— The one path this task's report may be at.
Returns: True when the command sets PLAYWRIGHT_REPORT_ENV to that exact path.
playwrightReportPathFor(taskId)
The report file a background task's own scratch files live beside.
Derived from the task id, never from the command: the id is unique per launch, so two runs can never read one another's report, and the path survives a process restart the same way the task's log and exit file do.
function playwrightReportPathFor(taskId: string): string
taskId— Themol-bg-…handle the launch returned.
Returns: The report file's absolute path.
startsServerProgram(command)
Whether a command, read from its TEXT alone, starts a server that stays up in the foreground.
The over-budget reader's shape: at that point the command has already run, and only its text is left to say whether "run a smaller unit" was ever the right advice. Inline/stdin programs remain unclassified and use the normal bounded command runner.
function startsServerProgram(command: string): boolean
command— The command as the executor sent it.
Returns: True when a foreground statement of the command starts a server.
foregroundServerCommand(command, readScript)
A FOREGROUND command that starts a server, including one that only names a script whose SOURCE
imports the app's server and calls its create()/listen(). Inline/stdin programs
(node -e …, python3 -c …) use normal bounded execution: interpreting arbitrary
program text is outside this filename/script preflight's contract.
The script read is best-effort: a path the backend will not answer for is a command this reading cannot classify, never a refusal. A backgrounded launch, a test runner and a test file are all left alone.
function foregroundServerCommand(
command: string,
readScript: (path: string) => Promise<string>,
): Promise<ForegroundServer | null>
command— The command as the executor sent it.readScript— Reads a script file the command names (backend.readFile).
Returns: The serving program, or null when the command starts no server in the foreground.
foregroundBrowserProbe(command, readScript)
A FOREGROUND command that directly runs a standalone script which launches a browser and never
closes it — the same never-returns lifecycle class as foregroundServerCommand, read from
the script's SOURCE by standaloneBrowserLeak.
The boundaries are the server preflight's, so the two readers cannot disagree about what they are allowed to touch: a backgrounded launch, a test runner and a test file are left alone, and a script the backend will not answer for is a command this reading cannot classify, never a refusal. A Playwright suite is owned by its runner's browser fixture and is never read here.
function foregroundBrowserProbe(
command: string,
readScript: (path: string) => Promise<string>,
): Promise<ForegroundBrowserProbe | null>
command— The command as the executor sent it.readScript— Reads a script file the command names (backend.readFile).
Returns: The leaked probe's variable and script path, or null when the command is not one.
serverCommandRefusal(server, budgetSeconds)
The refusal for a foreground command that starts a server: why it would never return, and the two shapes that do work — a background launch, or a probe of the API already running.
function serverCommandRefusal(server: ForegroundServer, budgetSeconds: number): string
server— The serving program, fromforegroundServerCommand.budgetSeconds— The tool's budget, which a foreground server would consume whole.
Returns: The refusal sentence.
leadingSleepPeek(command)
The leading sleep of a command, when the first statement is one and it asks for at least
MIN_PEEK_SLEEP_SECONDS.
The statement is read by locatedCommandSegments — the same parse every other command
classifier uses — so only a sleep in command position of the FIRST statement counts. The end
of that statement is then found by walking forward from its own start: the statement is
sleep <duration>, whose words carry no quotes and open no substitution, so the first unquoted
;, newline or & ends it. A | is refused: dropping the left side of a pipeline would hand
the right side its stdin instead, and a || fallback would run on a success that never did.
function leadingSleepPeek(command: string): LeadingSleep | null
command— The shell command the executor sent.
Returns: The seconds and the remaining command, or null when the command does not open with a long sleep.
withoutHeredocs(command)
A command with its heredoc bodies removed: the runs, kills and hosts it names in a file it WRITES are not what the command itself does.
The header is kept (cat > run.sh <<'EOF' …EOF leaves cat > run.sh), which is what the
readers here want: everything before the body is still readable as the command's own words.
function withoutHeredocs(command: string): string
command— The shell command.
Returns: The command without its heredoc bodies.
suiteCommandTarget(command)
The server a suite command points at, as a comparable key: the host it names (HOST=,
BASE_URL=, PLAYWRIGHT_BASE_URL=, --variable host=, or a bare URL), or local for a run
that names none — a suite run in the sandbox goes to the sandbox's own app unless the command
says otherwise. Every localhost spelling collapses to local (one sandbox, one app, one
database).
function suiteCommandTarget(command: string): string
command— The suite command.
Returns: The target key.
playwrightCommandTarget(command, last)
The target of the actual Playwright step, including inherited exports. URLs and option names in another program or a quoted title cannot decide whether this step is deployed.
function playwrightCommandTarget(command: string, last?: boolean): string
command— The shell command.last— Read the last Playwright invocation, for the background launch rewrite.
Returns: The comparable target key, or local when no target setting is present.
namesSuiteConfig(command)
Whether a Playwright statement names its own config — the reading withSuiteConfig and
scopedRerunCommand share, so neither adds a second --config to a command that has one.
function namesSuiteConfig(command: string): boolean
command— A command, or the Playwright statement inside it.
Returns: True when the statement loads a config of its own.
withSuiteConfig(command, config)
The command with a --config added to the Playwright invocation it starts — or unchanged when
it already names one, or starts no Playwright run.
The flag rides the same statement the runner does: a cd, an env prefix and a timeout before
it are left exactly as they were, and so is everything chained after the run (| tail -50).
A fix-round re-run dropped the
--config playwright.conduit.config.ts both earlier runs had carried, so Playwright started with
NO base URL and all 10 failures were page.goto: Cannot navigate to invalid URL — a failure list
that says nothing about the app. The platform composes commands back to the executor too (the
narrowed re-run of a finished run's failures), and a command it hands back has to carry the
config the run was measured under, never the shape that caused that finding.
function withSuiteConfig(command: string, config: string | null | undefined): string
command— The command as the executor sent it.config— The config the run loads, when the caller knows it.
Returns: The command with the flag, or the command unchanged.
scopedRerunCommand(command, locations, excluded, config, cwd, env, options)
The whole-suite command made scoped to the tests it should re-run instead: the same
invocation — same launcher, same settings — with the named file:lines in place of every
positional selection the run carried (a spec file, a suite directory or a regex filter),
--last-failed dropped (it re-runs the tests that never ran too) and
--retries=0 set (a re-run of a known failure does not need to pay for retries) — except the
re-run of a run against a DEPLOYED URL, which keeps the suite's own retries and tracing
(options.suiteSettings).
The re-run keeps the run's > <file> redirect only in the sense of keeping its OUTPUT there:
the target is rewritten to a fresh sibling (redirectRunnerOutputsToFreshFiles), so a
re-run never overwrites the log the run itself is the evidence for —
and the setup around the run keeps its own file writes untouched. A
tail/head/cat/grep chained after the run that reads that exact log is shown the fresh
sibling instead, so the re-run displays the run it performed.
config is the config the run was measured under (withSuiteConfig): the narrowed re-run
carries it whenever the command itself does not, so a run that dropped --config cannot be
handed back a command with the same defect (every failing test was
Cannot navigate to invalid URL because the re-run loaded no base URL).
function scopedRerunCommand(
command: string,
locations: readonly string[],
excluded?: readonly string[],
config?: string | null,
cwd?: string | null,
env?: readonly RunEnvSetting[],
options?: { suiteSettings?: boolean },
): string
command— The whole-suite run's command.locations— The failingfile:lines to re-run, as the run's own log printed them. A location the reporter printed relative to the runner's own directory (../../fixtures/…, which no absolute path contains) is resolved here (playwrightLocations), so the command this returns is one Playwright can match.excluded— The test titles the request carves out. They are inverted out (--grep-invert) so a re-run of the failing locations cannot report one of them again — a re-run of the whole 139-test suite spends ~4 minutes to be told about a test the request had already said does not count.config— The config the run loaded, when the caller knows it; added when the command does not name one.cwd— The directoryexec_commandwas given, when it was; the base a location is resolved against when the command does notcdanywhere.env— The settings the REQUEST requires of the suite and this run left out (withRunEnv): the re-run carries them, so a re-run of a run measured in the wrong mode is not measured in that mode again.options—suiteSettingsfor the re-run of a run against a DEPLOYED URL: it keeps the suite's own retries and tracing instead of the diagnosis ones. The graded measurement is the suite's own settings, and a retry is what leaves a failing test's trace there; the platform's--retries=0and its--trace=retain-on-failureare both a stricter measurement than the one that was graded, and the recording alone turned three budget-bound deployed tests into timeouts.
Returns: The scoped command, or the command unchanged when it runs no Playwright suite.
withRunEnv(command, settings)
The command with the request's required settings put in front of its RUN statement — the ONE place every composed re-run gets them.
The settings are written at the statement's own assignment offset, never in front of the whole
command: a shell binds an assignment there to the statement's program, while one in front of the
whole command is the environment of its FIRST statement alone (APP_BASE=… cd app && npx playwright test sets the variable for cd). A name the command
gives a different value is replaced, and one it already gives the required value is left as
written. When the parse cannot place the statement (a run inside a nested sh -c '…'), the
settings become exports, which no statement boundary can swallow.
function withRunEnv(command: string, settings?: readonly RunEnvSetting[]): string
command— The command to carry them.settings— TheNAME/valuepairs the request requires.
Returns: The command, or the command unchanged when it already carries every setting.
suiteRunDirectory(command, cwd)
The absolute directory the Playwright statement in a command runs in, or null when the command does not say.
The reporter prints a failing test's file relative to the process directory the runner started
in (../fixtures/… from a run whose suite lives outside its own tree), so the directory has to
come from the command itself: exec_command's cwd when it was given, then each cd before
the runner. Only a literal cd is followed — a target holding a variable, a glob or ~
resolves nowhere useful, and a guessed absolute path is worse than the relative one the
reporter printed.
function suiteRunDirectory(command: string, cwd?: string | null): string | null
command— The shell command.cwd— Thecwdthe tool was given, when it was.
Returns: The absolute directory, or null.
resolvePlaywrightSelectionPaths(command, cwd)
Resolve literal .//../ Playwright file selections against the runner's own directory.
Playwright treats every positional selection as a regular expression matched against each
collected test's ABSOLUTE path. A location copied from its reporter (../checks/smoke.spec.ts:9)
therefore collects nothing even though that path exists relative to the shell. Resolving a
literal path also escapes its regex metacharacters and shell-quotes the result: + and .
must match themselves, and the shell must pass the whole filter as one argument. Option values,
redirects, regex selections, absolute paths, and commands whose directory cannot be known stay
byte-for-byte unchanged.
function resolvePlaywrightSelectionPaths(command: string, cwd?: string | null): string
command— The command that invokes Playwright.cwd— The tool's working directory, used when the command has no absolutecd.
Returns: The command with only its literal dot-relative positional selections resolved.
suiteRunInTheWay(candidate, inFlight)
The run in flight that makes a second run a hazard, or null when nothing is in the way.
This is the ONE rule the mid-run note and the suite-overlap hold both answer with: a suite run may start only when this returns null, because two suites against one app and database share its rows — the failures one causes the other cannot be told from real ones. A run that invokes no suite is never in the way, and neither is one the candidate command stops first.
function suiteRunInTheWay<T extends SuiteRunInFlight>(
candidate: { target: string },
inFlight: readonly T[],
): T | null
candidate— The run about to start, by the app and database it would measure (suiteCommandTarget).inFlight— The suite runs already going, in the order the caller found them.
Returns: The first run in the way, or null.
isPlatformProofLaunch(input)
Whether an exec_command input object carries the host's PLATFORM_PROOF mark.
function isPlatformProofLaunch(input: unknown): boolean
input— The tool input as the handler received it.
Returns: True only for a launch host code marked; false for anything a model sent.
isDiagnosisRun(command, context)
Whether a command walks a PART of a suite instead of all of it: a cap that stops it at a failure
count, the failures the last run printed (--last-failed, --only-changed), a title filter, or
named files/lines.
THE one reading of that question, in one place. Two sites act on the answer and must never disagree:
- the command rewriter that adds
--retries=0to a background Playwright run (./utilities.jsstreamingBackgroundCommand) — a diagnosis walks each failure once, while the run the suite is judged by keeps the suite's own retries; and - the platform's own notes (molecule-dev's
suite-cli-override.ts), which must not tell the executor to drop the--retries=0the platform itself has just added — a contradiction filed three times.
Until then they were a regex and a predicate that only LOOKED alike, and the
gap was exactly the run the platform had asked for: its testRunNote says "run the whole suite
once with --max-failures=0", and the rewriter read that cap flag as a capped diagnosis and
stripped the suite's retries from the uncapped proof run that follows a deploy — the one run the
graded run is compared against (+25:03, +31:39, +36:40 and +49:57, the last two against the
deployed URL, where a network blip is likeliest and the retries it dropped are the ones that
absorb it).
--max-failures=0 is Playwright's own "no cap" (boundsFailures), so it is not a
diagnosis. A command that starts no Playwright run is not one either (false): the question is
about a run already read as a Playwright suite.
A --grep-invert is only a narrowing when it excludes MORE than the request already excludes.
When the caller passes those approved titles (DiagnosisRunContext) and the inverted
pattern names one of them — the request's own "except …" scope written as the flag, which
molecule-dev's invertDecision reads the same way — the run still walks the whole proof scope,
and it is not a diagnosis. The deployed proof carried exactly
that exclusion, the rewriter added --retries=0 to it, and the run lost the suite's retries on
the one walk where a network blip is likeliest.
A command the PLATFORM composed and launched AS the graded proof keeps the suite's retries for
the SELECTION it composed — the failures a redeploy re-runs, named as files and file:line
(DiagnosisRunContext platformProof). Only that selection is excused: a cap, a title
filter, a last-failed set and a local targeted selection stay diagnoses, so the mark cannot turn a walk of
part of the suite into the graded measurement. Which targets are local is
suiteCommandTarget's answer, and the launch rewrite asks it on the same reading
(./utilities.js streamingBackgroundCommand).
function isDiagnosisRun(command: string, context?: DiagnosisRunContext): boolean
command— The command as the executor sent it.context— The request's approved exclusions and whether this command IS the graded proof, when the caller knows them. A whole local walk still covers the whole suite; the launcher's separate local-target policy disables its retries. This predicate classifies narrowed selections and their proof purpose.
Returns: True when the run is a diagnosis or a re-run, not the whole suite or a deployed proof selection.
discoverSkills(backend)
Discover skills from a project directory.
Scans .agents/skills/ and .claude/skills/ for SKILL.md files.
Reads the YAML frontmatter of each to extract name: and description: fields.
function discoverSkills(backend: ExecutionBackend): Promise<SkillEntry[]>
backend— Execution backend to use for filesystem access
Returns: Array of discovered skills with name, description, and path
buildAgentPrompt(ctx)
Build a coding-focused system prompt from composable sections.
Returns a string that includes:
- Agent identity
- Available tools listing
- Coding best practices
- Tool argument formatting guidance
- Project docs (if provided)
- Discovered skills listing (if provided)
- Inline skills (if provided)
- Custom sections (if provided)
function buildAgentPrompt(ctx: PromptContext): string
ctx— Prompt construction inputs (tools, docs, skills, etc.).
Returns: Fully assembled system prompt text for the coding agent.
createDeferredToolCatalog(options)
Offer common tools and let the model load other schemas by exact name.
This is ordinary allowlist selection, not semantic routing or authorization. Pass tools already filtered by the current mode and permissions. Loading never executes a tool; the caller must keep its normal execution-time guards. Loaded schemas append in request order and stay available, avoiding an LRU that changes the schema prefix on every request. Only names need persistence across turns.
function createDeferredToolCatalog(options: DeferredToolCatalogOptions): DeferredToolCatalog
options— Allowed tools, initial selection and optional durable load state.
Returns: A loader tool and the current provider-facing selection.
readPlaywrightRunReport(backend, path, sanitize)
One report file's bounded facts and retained native attachments, or honest omissions.
A report that is not there is NOT "the run failed nothing": summarizePlaywrightReport answers
missing, and every reader treats that as no machine data rather than as a clean run.
function readPlaywrightRunReport(
backend: Pick<ExecutionBackend, 'readFile' | 'run'>,
path: string,
sanitize: (text: string) => string,
): Promise<PlaywrightRunReport>
backend— The project's execution backend.path— The report file's absolute path (/tmp/…).sanitize— The consumer's redactor for the error text the record carries.
Returns: The bounded record with per-call attachment copies; never a verdict.
taskStopFile(taskId)
Where a background task's stop script lives, beside its .sh, .log, .pid and .exit.
function taskStopFile(taskId: string): string
taskId— The task'smol-bg-…handle.
Returns: The script's path.
taskStopScript(taskId)
The script that stops a background task and every process under it, as they are when it RUNS.
A pid list taken when a note is written goes stale: a test runner replaces a worker after a
failure, and the new worker is in no list. Killing only the pid file's shell leaves the runner
orphaned, still holding the sandbox's one Playwright slot, so the next walk is refused.
So the walk happens here, at stop time: the kernel's own child lists
(/proc/<pid>/task/<tid>/children) or pgrep -P where those are absent. Every process gets
TERM, any still running a second later gets KILL, and a task that recorded no exit code is
given 143 (the TERM status), so wait_for_task reports it stopped at once instead of waiting
for a process test to notice.
The executor runs it as sh <file>: a file name, so no kill pattern of its own matches the
shell running it (molecule-dev/api/src/ai/pattern-kill-guard.ts).
function taskStopScript(taskId: string): string
taskId— The task'smol-bg-…handle.
Returns: The script's text.
taskStopCommand(backend, taskId)
The command that stops a running background task, read from the sandbox's own files.
THE one builder for it, so every note that hands the executor a way to stop a run hands over the
same pid-only form: a pkill -f <something> matches the shell running it (its argv IS the
command), and molecule-dev/api/src/ai/pattern-kill-guard.ts holds exactly that — a stuck note
that suggested kill $(cat /tmp/<id>.pid) 2>/dev/null; pkill -f <id>.sh was refused by the
platform's own guard, and the same shape costs a refused call every time. The pid tree is the
whole of what the pattern was for: the detached shell and every process under it.
function taskStopCommand(backend: ExecutionBackend, taskId: string): Promise<string>
backend— The execution backend.taskId— The task'smol-bg-…handle.
Returns: sh /tmp/<id>.stop for a task this tool launched with its stop script (taskStopScript); for an older task, kill <pids> from a walk made now, falling back to the task's own pid file when the walk comes back empty (a sandbox without pgrep, or a pid file already gone, in which case the pid-file form is still the one the platform's guard names).
moleculeDistReadNote(path)
The steer attached to a SUCCESSFUL read of a package's built output. The ENOENT
redirect below fires only when the read FAILS, so a model that knows the hoisted
layout reads node_modules/@molecule/<pkg>/dist/*.js happily and never learns the
documented API is one call away (24 such reads in 57 s, with no note on any of
them). Carried as distNote rather than merged into note so a host that
has read_molecule_doc (molecule-dev's cadence note, which also names the functions)
can supersede it without string-matching.
function moleculeDistReadNote(path: string): string | null
path— The resolved path that was read.
Returns: The note, or null when the path is not inside a package's dist.
registeredTaskLogCommand(taskId)
The command that reads a REGISTERED background task's own log as one bounded contiguous window
(runningLogReadCommand), with the file its launch redirects to when the launch recorded
one.
The task id is the ownership: it is the handle wait_for_task returned, /tmp/${taskId}.log is
the log this platform's launcher writes for it, and the redirect target is the file this
process's own launch registered for that id — never a path parsed out of a command by the
caller. A diagnosis that reads a running walk must not build a /tmp path of its own
(a wait's DISPLAY gets diagnosed as if it were the log).
function registeredTaskLogCommand(taskId: string): string | null
taskId— Themol-bg-…handle the wait returned.
Returns: The read command, or null when the handle is not a task id this platform minted.
shellInstalledPackageProbe(run)
Build an InstalledPackageProbe from a shell runner (a backend's
run, or a sandbox's exec): one command reports whether the entry is a
link and whether a package.json resolves under it.
function shellInstalledPackageProbe(
run: (command: string) => Promise<{ stdout?: string } | null | undefined>,
): InstalledPackageProbe
run— Runs a command where the path lives.
Returns: The probe.
installedPackageWriteRefusal(path, probe)
The refusal for a write whose target is inside an INSTALLED package, or null
when the path is not under node_modules or nothing is installed there.
node_modules is not the project's code: nothing written there survives the
next install, no deploy carries it, and a sandbox whose dependency tree is
shared (the pre-installed superset) breaks every other run through it. A
write_file on
node_modules/@molecule/api-resource-comment/dist/numbers.d.ts, made while
reading the package's declarations, clobbered its runtime module a call later
(module.exports = {} over the ESM handler its own code imports) — the write
answered ok: true, and 18 s went to noticing, npm pack-ing the package and
putting the file back. Reading these files stays allowed (that is how the
declarations above are read at all).
What is protected is the INSTALL, not the spelling: the decision comes from
InstalledPackageFacts, never from the path alone (see the symlink case above). Three
things are the run's own to remove or replace —
- a
node_modulesthat is a SYMLINK:rm/unlinkremoves the link, never the tree it points at, so a link the run made cannot clobber anything; - anything under the run's own
.mol-scratch/directory; - a
node_moduleswith nopackage.jsonunder it (nothing was ever installed).
A path INSIDE the link is still decided by what resolves there: a link into a real tree is refused, because removing or writing through it reaches the install.
The restore route is named because the model that has ALREADY clobbered a file
(this refusal is too late for it) is the one who needs it, and because the
obvious repair — npm install <pkg> — is itself refused in the pre-installed
sandbox. npm pack + a tar extraction over the package directory is the
repair both guards leave alone.
function installedPackageWriteRefusal(
path: string,
probe?: InstalledPackageProbe,
): Promise<string | null>
path— An absolute path a tool is about to write.probe— Looks at the filesystem where the path lives.
Returns: The one-line refusal naming the package, or null when nothing is installed there.
buildTools(backend, config)
Build a complete set of AI agent tools bound to an execution backend.
function buildTools(backend: ExecutionBackend, config?: ToolBuildConfig): AITool[]
backend— The execution environment (sandbox or local filesystem)config— Optional configuration for security, callbacks, and tool selection
Returns: Array of AITool objects ready to pass to an AI provider
traceArtifactsScript()
The Node program the sandbox runs to read a failed run's traces: node <script> <dir> prints one
TRACE <json> line per trace.zip under <dir> (newest first, MAX_TRACE_ARTIFACTS of
them), each with the test it belongs to, the requests its page made and its console lines.
It is a standalone program, not an import, for the reason @molecule/api-code-sandbox runs it:
Playwright's own zip reader is not reachable from a project's node_modules, and a dependency
on unzip would make the read fail on every sandbox that has none. The zip is read with the
central directory and zlib.inflateRawSync — about forty lines, and the only thing that has to
be true of a trace.zip is that it IS one.
A request is kept over a static asset when it failed — a status >= 400, or no response at all
together with Playwright's own error text (-1 plus _failureText, a refused connection) — and
over anything else when it is the page talking to the app (fetch/xhr/document): a failing
test's trace holds the whole page load. A request with no response and NO error text was aborted
or still in flight when the test ended; it is kept too, but as what it is, not as a failure.
A trace.zip holds ONE trace member per browser context the test used (beside the runner's own
test.trace), and the archive's member order is not the test's chronology. Each member is read
as its own context: actions and requests keep their context id, requests and frame snapshots
keep the pageId Playwright records, and the failing assertion's page — the page its own step id
ran on — decides which actions, snapshots and requests become the test's row. What the test's
other browser contexts recorded is reported apart, as otherContexts.
A request answered 4xx by the app's OWN API also keeps what the page SENT and the first of what
came back: Playwright stores either inline (text) or in a resource entry (_file), and both
are read. That is where a wrapped body shows: a helper passed
{ data: body } as app-http's second argument, so every POST/PUT was {"data":{…}} and the API
validated {}. Status alone said only "422".
function traceArtifactsScript(): string
Returns: The program's source, to write to a file and run.
parseTraceArtifacts(stdout)
The traces traceArtifactsScript printed, parsed.
A line that is not a complete TRACE <json> (a truncated read, a program that died mid-write) is
dropped: a partial trace is not evidence about the test it came from.
function parseTraceArtifacts(stdout: string): TraceArtifact[]
stdout— The program's output.
Returns: One entry per trace it printed.
isStaticAssetRequest(request)
Whether a request is one of the page shell's, not the test's (STATIC_ASSET_PATH).
The document itself is never incidental — a page that never loaded IS the failure — and a
request whose type is the app's own API (fetch/xhr) is judged by its path alone.
function isStaticAssetRequest(request: TraceRequest): boolean
request— One request a trace recorded.
Returns: True when the request is incidental to the step under test.
failedRequest(request)
Whether a trace recorded a failed response or a request error other than cancellation.
A 404 on a static asset is excepted: /sw.js and /fonts/* 404 on an app that never shipped
them, and naming one as a failure sent a run into writing the caching worker it had asked about.
A 5xx on an asset, or a network error, still counts. A request error alone does not locate
the cause in the server: the browser or network may have rejected the request.
function failedRequest(request: TraceRequest): boolean
request— One request a trace recorded.
Returns: True when the request failed in a way the note should name.
unansweredRequest(request)
Whether a trace recorded no response and no error other than cancellation. The request may have been pending or cancelled when recording ended; the trace does not establish whether the endpoint stalled. A shell request is not evidence about the step.
function unansweredRequest(request: TraceRequest): boolean
request— One request a trace recorded.
Returns: True when the request's missing response is inconclusive and worth naming.
stalledDocumentSubresource(request)
Whether a trace recorded a DOCUMENT SUBRESOURCE that never finished: a stylesheet, script or other asset the page itself loads, with no response and no error text — still in flight when the navigation timed out.
The page shell's own incidental requests (/sw.js, the manifest, a favicon, a font) are
excepted for the reason isStaticAssetRequest documents: an aborted /sw.js once sent a
run to write a caching service worker. A pending /assets/*.css is different — the navigation
blocks on it, so it is the reason page.goto ran out of time rather than one of the app's API
calls (three deployed page.goto timeouts on tests that pass locally, one 88 KB stylesheet
fetch measured at 27 s, and the failing tests' traces each holding the never-answered CSS while
the note said "the cause is in the page").
function stalledDocumentSubresource(request: TraceRequest): boolean
request— One request a trace recorded.
Returns: True when the request is a document subresource that never finished.
isCredentialExchangePath(path, authEndpoints)
Whether a request PATH asks the app to mint a credential — a login, a registration, a token endpoint — as opposed to a protected resource that presents one.
This is the path half of isCredentialExchange, exported so a caller holding only a
METHOD path reads the same classification: a Hurl failing entry says
POST /api/users/login and nothing about the body, and the whole-suite note must not explain
a wrong-password login that answered 200 as a cookie-jar effect.
function isCredentialExchangePath(path: string, authEndpoints?: readonly string[]): boolean
path— The request path (/api/users/login); a query or fragment is ignored.authEndpoints— The endpoints the app's auth config names (/users/login).
Returns: True when the path names a credential exchange.
hiddenBoxNote(items)
The sentence a "hidden" visibility failure earns when the trace proved WHY the box is empty.
Playwright calls an element with a zero-size box hidden even when it is painted, so the answer
is in the element's children. An a.navbar-brand was 0×4 px because its
only child was <img src="/conduit-logo.svg" height="26">: an SVG with a viewBox and no
width/height has no intrinsic size, and the height attribute loses to Tailwind's preflight
(img { max-width: 100%; height: auto }), which the scaffold's own index.css imports. The
note said only "the cause is in the page", and the run spent over four minutes rasterising an
SVG to PNG. Only what the snapshot shows is claimed (TraceHiddenBox).
function hiddenBoxNote(items: readonly TraceArtifact[]): string | null
items— The tracesparseTraceArtifactsread.
Returns: The sentence, or null when no failure carries a hidden-box reading.
countMismatchSentence(mismatch)
The row's sentence for a failing count assertion: the locator, both numbers, and the elements the failure snapshot held.
A comments.spec.ts:86 row printed only Expected: 3 / Received: 4. The
helper counted .card:not(.comment-form) .card-block, and the app's comment form was a
.comment-form wrapper around a plain .card, so the form's own .card-block was the fourth
match. The trace held the selector and the four elements; the note held neither.
function countMismatchSentence(mismatch: TraceCountMismatch): string
mismatch— The trace's count reading (TraceCountMismatch).
Returns: The sentence.
countMismatchNote(items)
The sentence a count assertion earns when every traced failure is one — the next read before the API or the request is changed.
function countMismatchNote(items: readonly TraceArtifact[]): string | null
items— The tracesparseTraceArtifactsread.
Returns: The sentence, or null when not every traced failure is a count mismatch.
failureTraceNote(items, target, earlierFailures, apiPrefixes, report)
The note a failed suite run's result carries: what each failing test's page actually sent, and what came back.
This is the answer to the question a swallowed error hides — a click that changed nothing is
usually a request that failed — so the note leads with the failing requests and says what to do
with them: read the handler the route reaches, not the selector. It is BOUNDED to
MAX_TRACE_NOTE_TESTS tests with MAX_TRACE_NOTE_REQUESTS requests each, because it
rides in a result the model pays for.
The three kinds are kept apart, because they mean different things. A FAILED request (4xx/5xx, or
a network error with Playwright's own text) is a cause. A request with NO RESPONSE RECORDED —
Playwright's -1, no error text — was still in flight when the test ended (the page closed under
it); listing it as a failure sent a run hunting an API that never answered anything wrong
The rest are the page's last answered requests.
A 4xx request carries what the page SENT beside its status, so a wrapped body is visible in one
line rather than inferred from the status; when one of those bodies is an object whose only key
is data, the note names the call shape that produces it.
Every row opens with the test's LAST user action before the failing assertion and the requests
that action caused (TraceArtifact.lastAction) — started after it, before the assertion,
the app's own API calls first, each with its status and the first 200 characters of its response,
then where the page went next. The trace's action clock and each request's _monotonicTime are
the same clock, so "caused" is the trace's own fact rather than a guess from recording order.
A run failed 13 then 12 tests on one unnamed cause while every row led with
GET /api/tags → 200 — the Home page's own fetch after the redirect — and filled its answered
slots with the PWA's /workbox-*.js and its /icons/*.svg; the register POST /api/users
(answered 201, the page still rendering signed-out) never appeared. With no action clock, the
row falls back to TraceArtifact.lead: the page's last answered fetch/xhr.
The action, the URL and the requests are the FAILING ASSERTION'S PAGE's (TraceArtifact.lastAction), never the archive's last context: a test that creates its data in a
second browser context writes that context's click and /editor snapshot into the same zip, and
reading the concatenation made them the failing page. The other
contexts' requests are named separately as set-up work. When the trace holds more than one used
context and the assertion's page cannot be identified, the note lists the requests and makes NO
causal claim — no "the test's last action", no "the page stayed at …" — instead of merging them.
A field the test filled and the page submitted EMPTY (formResetOf) leads the note: the
trace holds both facts — the value typed into textarea[name="bio"] and the PUT /api/user
whose body carried "bio": "" — so the form's state was reset between the typing and the
submit. The note names the effect that re-seeds a form from data whose identity changed and the
fix at the source (seed the form once). A deploy-and-walk cycle is lost to this on the
deployed URL only, where the background session verification lands later than it does locally.
A write whose response said a boolean field is true and a LATER GET of the same resource that
said it is false leads the note first (readContradictionSentence): the read route never
saw the viewer, so the fix is on that route's middleware, not in the page. Rewriting the
profile component over exactly that pair costs ~8 minutes — the write answered
{"following":true} and the next profile GET answered false.
WHICH rows it spends is evidence, not artifact order: a row
needs a recorded response, a real failure or a console line (traceRowEvidence), rows are
deduplicated by the test's location, and they are ordered real failure → repeated from an
(description truncated — read the full text in node_modules/@molecule/api-ai-tools/dist/trace-artifacts.d.ts.)
function failureTraceNote(
items: readonly TraceArtifact[],
target: string,
earlierFailures?: readonly string[],
apiPrefixes?: readonly string[],
report?: TraceRunReport,
): string | null
items— The tracesparseTraceArtifactsread.target— Where the run went — the deployed host, as the note names it.earlierFailures— The failingfile:lines earlier walks of this suite left, so a repeat is ranked above a one-off. Empty when the caller knows of no earlier walk.apiPrefixes— The API path prefixes the app's client config names (['/api']), read from the app by the caller. Empty when the caller could not read one; the traces' own requests may still supply it. Never a hard-coded literal.report— The runner's own report for this run (TraceRunReport): each failing test's declared location, the operation its failure names and the deadline it names, plus whether the same result'stestRunNotealready points at a production build. A pending asset is called the cause only when the runner says the failing operation for THAT test is the navigation it was loading; without the report nothing is called a navigation stall.
Returns: The note, or null when no trace held a recorded response, a real failure or a console error.
suiteRecordsTraces(configText)
Whether a Playwright config records traces for the tests that fail.
Only on and retain-on-failure keep a trace.zip for a failure whatever the retries do: the
two retry modes need a retry to happen at all, and a diagnosis run is given --retries=0
(streamingBackgroundCommand), so a run's own
trace: 'on-first-retry' recorded nothing — which is what left the failing tests' network log
unreadable. A config that sets no trace: at all records nothing either (Playwright's default
is off); so does one that cannot be read.
function suiteRecordsTraces(configText: string): boolean
configText— The config's source, or '' when none could be read.
Returns: True when the config records traces for failures.
namesNoRetries(command)
Whether the run itself pins --retries=0 (either spelling): a run that cannot retry records no
retry trace, so it still needs one recorded for it. A running wait reads the same proof to know
a first failure's body is already final (wait_for_task's diagnostic yield).
function namesNoRetries(command: string): boolean
command— The shell command.
Returns: True when the run allows no retry.
diagnosisTraceCommand(args)
The command a Playwright run needs to leave a readable trace behind, when the suite's config would record none — except a run that can serve as proof, whose own settings are left alone.
The failing tests' requests are only readable if the run wrote them down (see the module doc),
and the config is where the decision about that lives — the platform does not edit the suite's
config, so it passes the flag instead, on a Playwright run that starts tests, does not already
decide its own --trace, and whose config keeps no trace for its failures.
A run that can serve as PROOF is the exception: the graded measurement is the suite's own
settings, so it keeps its own tracing and retries. That was measured, not assumed — on one
sandbox the same build ran a three-test deployed
subset 3/3 timed out under this flag (17.6–17.9 s against a 15 s per-test budget) and the whole
file passed 14/14 without it (10.9–12.1 s). retain-on-failure RETAINS only a failing test's
trace (Playwright's _shouldAbandonTrace unlinks a passing test's), but it RECORDS every
action of every test, and for a test near its per-test budget that recording is the difference
between passing and timing out. This flag was added for exactly that failure: its
deployed proof run left only an error-context.md because the suite traces
on-first-retry and the run had no retries. That need is met without the flag — the graded
deployed run keeps the suite's own retries, so a failing test leaves its retry's trace — and
the platform's re-run note carries --trace=on for a run that did leave none.
Which runs are proof-capable is suiteCommandTarget's answer: a run against a deployed
URL. A LOCAL run that narrows the suite is not left to its config, because the launcher gives
every local run --retries=0 (@molecule/api-ai-tools streamingBackgroundCommand), so its
retry trace would never happen. A deployed run that pins --retries=0 itself is in the same
position.
A proof-capable run is left alone WHATEVER its config traces. --trace is a per-run override of
the suite's own use.trace (Playwright merges the CLI's use into every project's), and a test
record carries the project settings it ran under: a run with the flag is not the suite's own
measurement, so it can never count as deployed proof. Added to a deployed walk, the flag made the
walk unprovable, and the platform's own answer — "run the current selection" — was a command this
same rewrite then flagged again: X1 P140–P173 had 22 deployed walks the executor started, and
not one moved the native proof counts (xr-molecule-flash-l1255 walked 73/73 green twice, at
+18.2 and +22.9, and neither counted). A failure in a suite that keeps no trace at all is still
readable: the platform's re-run note carries --trace=on for a run that left none.
A LOCAL walk of the WHOLE suite keeps the suite's own trace setting too, and only a run that
narrows the suite records one: the rule is "a local run of the whole suite runs with the suite's
own trace setting; a run that names files or tests, filters titles, re-runs the last failures or
caps failures records a trace for each failure", and its one input is the command's own
arguments (isDiagnosisRun, the reading the launcher's --retries=0 rule already uses).
The recording is paid on every action of every test, and on a 2-vCPU sandbox a whole walk
already fills both cores: X1 P373–P385 local whole walks ran a median 4.36 s a passed test with
the flag (22 walks) and 3.06 s without it (3 walks the executor ran with --trace=off), about a
minute a walk on a 73-test suite. A failure is diagnosed in the narrowed re-run the platform
hands back, which names the failing tests and so gets the flag.
function diagnosisTraceCommand(args: {
command: string
cwd: string
readFile: (path: string) => Promise<string>
readDir?: ReadConfigDirectory
approvedExclusions?: readonly string[]
}): Promise<DiagnosisTraceRewrite>
args— The command, the directory it starts in, the backend's file read, and the titles the request excludes by name (an inversion of exactly those still walks the whole suite).
Returns: The command to run and the sentence to report, or the command unchanged.
shellQuote(s)
Shell-safe quoting using single quotes. Unlike JSON.stringify (double quotes), single-quoted strings prevent command substitution ($(), backticks) and variable expansion.
function shellQuote(s: string): string
s— Raw string to wrap for POSIX shell single-quoted context.
Returns: A single-quoted shell literal representing s.
stripControlChars(s)
Strip C0 control chars (except tab, newline, CR) that break PostgreSQL JSONB and can cause rendering issues.
function stripControlChars(s: string): string
s— Arbitrary text that may contain disallowed control characters.
Returns: A copy of s with unsafe control characters removed.
redactSecrets(s)
Redact values of common secret/credential patterns in text output.
ENV-DUMP GRADE — includes the JSON KEY: 'value' passes, which key off the
NAME beside the value and therefore cannot tell a credential from ordinary
code that happens to use a keyword-ish identifier. Use this for .env reads
and command output (where an env dump is the actual threat); use
redactSecretsInCode for source-file content.
function redactSecrets(s: string): string
s— Log or command output that may contain.env-style secrets.
Returns: A redacted copy safe to surface to end users or models.
redactSecretsInCode(s)
CODE-SAFE redaction — the env-assignment pass of redactSecrets WITHOUT
the JSON KEY: 'value' passes.
Those passes match on the NAME next to a quoted value, so over source code they
replace legitimate content at enormous scale: forgotPasswordEndpoint: '/users/forgot-password', apiKeys: 'API keys', and every localized "Show
password" string all became '[REDACTED]'. Because the agent writes back the
content it reads, that token then lands in the user's project — measured at
10,952 of 27,919 flagship template files before this split.
No value heuristic can fix that: a legitimate password = 'TestPass123!' in a
test helper is indistinguishable from a real credential by shape. So the
name-keyed passes simply do not run over code. Credentials in source are still
caught by the env-assignment pass here, and consumers layer VALUE-SHAPE
detection (vendor prefixes, PEM blocks, credentials in a URL authority) on top —
which is what actually catches a secret sitting under an innocuous name.
function redactSecretsInCode(s: string): string
s— Source-file content or other code-shaped text.
Returns: A redacted copy that preserves ordinary code verbatim.
addedRedactionMask(next, previous)
The redaction mask next adds over previous, or null when it adds none.
previous is the file's previous content for write_file, and the replacement's own
old_string for edit_file — an edit that carries an existing mask through (a file that
already had one, read back and rewritten) adds no occurrence. A new occurrence may
be copied output or intentional source; the caller declares the latter explicitly.
function addedRedactionMask(next: string, previous: string): string | null
next— The content about to be written (or the replacement'snew_string).previous— The content it replaces, already on disk (or theold_string).
Returns: The added mask as written ('[REDACTED]', "[REDACTED]", =[REDACTED]), or null.
printsOnlySource(command)
Whether a shell command only PRINTS source files (cat a.tsx, sed -n '1,40p' x.ts,
head -50 b.hurl): its output is file content and gets the code-safe redaction, like
read_file. This preserves fixture values, type literals and other ordinary source text.
Literal echo/printf headings between reads do not change that grade.
Expansions, other commands, env files and labels without a source read keep the full grade.
function printsOnlySource(command: string): boolean
command— The shell command.
Returns: True when the command prints source files, with only literal headings and filters.
isReadOnlyInspection(command)
Whether a shell command only INSPECTS the workspace WITHOUT printing a file's contents:
it prints source files (a pure literal read, printsOnlySource), lists names
(ls, find), or counts lines (wc) — joined by ;, && or |, with literal
echo/printf headings and cd.
Its output is code or names, not an env dump, so it gets the code-safe redaction
(redactSecretsInCode) instead of the name-keyed env-dump passes. Without this,
ordinary code values such as tokenKey: 'jwtToken' in a mixed source read and
ls | head command would be masked by the environment-dump rules.
A RECURSIVE SEARCH IS NOT INSPECTION (grep -rn x ., rg x src/): its output is the
content of whichever files matched, including .env files and JSON secret dumps, so it
keeps the full grade. A path with no extension is not evidence that it is a directory —
/dev/stdin and an ordinary secrets file read the same way.
Env dumps keep the full grade: .env anywhere in the command, env/printenv, a
non-literal or redirecting form, and an interpreter one-liner (node -e, python -c)
all return false.
function isReadOnlyInspection(command: string): boolean
command— The shell command.
Returns: True when the command only reads or lists workspace content.
isEnvFilePath(path)
Whether a path is an env file, for which redactSecrets' full env-dump
treatment is appropriate rather than redactSecretsInCode. Matches
.env, .env.<suffix>, and <name>.env.
function isEnvFilePath(path: string): boolean
path— A workspace-relative or absolute file path.
Returns: true when the file is an env file.
declaredBudgetSeconds(command, timeoutParam)
The time budget a COMMAND declares for itself — a timeout <seconds> prefix
anywhere in it, or the tool call's own timeout (ms) parameter, whichever is
larger. Zero when it declares none.
function declaredBudgetSeconds(command: string, timeoutParam: unknown): number
command— The shell command.timeoutParam— The tool call'stimeoutinput, in milliseconds.
Returns: The declared budget in seconds, or 0.
outputIsWithheldUntilExit(command)
Whether a command's output reaches the tool only when the whole pipeline
ends — a pipe into tail, grep, sort, wc and friends, which
block-buffer when stdout is not a terminal.
It matters only in combination with an overrun: a command stopped at the tool's ceiling normally hands back everything it printed, but behind one of these it printed nothing, so the whole budget is spent for no information. Measured across six real agent runs: ten such commands, every one of them piped, 49 minutes returning a few hundred bytes each.
function outputIsWithheldUntilExit(command: string): boolean
command— The shell command.
Returns: True when a kill would return no useful output.
outputRedirectTarget(command)
The file a command sends its own output to, when it redirects it (> out.txt,
>> log, &> run.log, | tee [-a] file), or null. A background command that does
this leaves its task log empty, so the log is the wrong place to look and an empty
log proves nothing.
Which redirect counts is decided by the command's own shell structure, from the same
parse every other command reader uses: a redirect written in a BACKGROUNDED statement
(… &) or inside a ( … ) / { … } group writes that process's or group's output, not
the command's. The platform's own preview launch is exactly that — the preview server is
started with >/tmp/mol-preview-4173.log 2>&1 & inside the build/serve prelude, and the
suite's foreground command follows it — so a reader that took the last > in the whole
text tells a run its output went to the PREVIEW's log.
The target comes back without its shell quotes: > '/tmp/x.log' is /tmp/x.log, and
the callers resolve a relative one against the command's cwd.
function outputRedirectTarget(command: string): string | null
command— The shell command.
Returns: The target, or null (/dev/null and &1/&2 are not files).
streamingBackgroundCommand(command, context, reportPath)
Rewrite a command about to run in the background so its log grows while it
runs. Two shapes left the log empty until exit, and an empty log is what
wait_for_task reads as "stuck", so working suites were reported stuck and
killed (one run lost 20 of its 60 minutes this way):
- a trailing
| tail -N, which holds everything back until the command ends. It is dropped:wait_for_taskalready returns the end of the log. - any output-only filter piped after a SUITE runner (
| grep … | tail -20), which hides the failing test's own error and leaves the pipeline's exit status — the filter's — as the run's. Every such stage is dropped from EVERY suite run in the command, not only the last (stripTrailingSuiteFilters);wait_for_taskalready returns the end of the full log, and a run whose tally shows a failure must never report 0. playwright testwith no--reporter, which runs the config's reporter — oftenhtml, which prints nothing per test.--reporter=listis added when the playwright run is the command's last step, piped or not: it writes each result as it finishes, and it is the shape the platform reads a background suite back in. Every EARLIER Playwright invocation gets the same reporter, so its log is readable while it walks; the machinejsonreport stays on the last invocation.
The run ends up with exactly ONE reporter that prints each failure — list. A run that names
any other printing reporter has it REPLACED, never joined: two of them write every test result
into the log twice, which made a --reporter=list,line run (its
line added by this function one run earlier) report two distinct failures as "4 of this run's
tests have already failed the same way", and the executor stopped a 139-test walk at test 21
with a single cause in hand. line alone is no use either: it writes [n/N] <title> with no
✓/✘ mark and no duration, so an 8.3-minute walk of one suite could never trip
the fail-fast note. A reporter set that writes a machine format to a file (json, html,
junit) is the
executor's own and is left exactly as it is — so is any reporter this build does not know.
Every background command that is not a no-test invocation is also given
PLAYWRIGHT_FAILURES_INLINE_ENV (inert except for Playwright's list reporter), so each
failure's own error is in the log as that test fails rather than only at the end: a suite that is
still walking is exactly when the executor reads the log, and without it a running log carries
✘ rows and nothing else (~90 s went to greps of one, then to fixing what was
guessed; a wrapper-launched run lost 6.5 minutes to the same shape).
Only the step that runs the suite is touched, and only its reporter, and only when that step
runs something: npx playwright test --list takes two seconds and writes nothing per test, so
no reporter is added to it (isPlaywrightRunCommand). A trailing
status step (; echo EXIT $?, && true) is not the run and is skipped when the run step is
found (isStatusOnlyStep); a run whose output is redirected to a file is still readable
through that file, which the launch records as the task's own output.
Explicit repetitions and configured runner settings (retries, timeouts, workers and scope) are preserved. Each requested execution remains in the command.
function streamingBackgroundCommand(
command: string,
context?: DiagnosisRunContext,
reportPath?: string,
): {
command: string
changes: string[]
reportPath?: string
error?: string
}
command— The command as the executor sent it.context— What the caller knows beyond the command: the tests the person's request excludes by name, and whether this command IS the platform's graded proof (DiagnosisRunContext). A--grep-invertof exactly those exclusions is the request's own scope, not a diagnosis. Missing literal title exclusions are applied before launch while preserving existing exclusions and the runner's configured settings.reportPath— Where this run should write Playwright's standardjsonreport, when the caller keeps one (./playwright-report.js). The reporter is added to the run's own reporter set, never in place of one, and its output goes to that file throughPLAYWRIGHT_JSON_OUTPUT_FILE— so the log, the executors' own reporters and every verdict stay exactly as they are. Omitted, or a run whose reporter set is not this function's to place (already namesjson, sets the variable itself, or whose runner cannot be located), leaves the command untouched and the result'sreportPathunset.
Returns: The command to run, one sentence per change made (empty when none), and the report path when one was actually wired.
withPlaywrightRunReport(command, reportPath)
Put Playwright's standard json report on a FOREGROUND run that already names its own reporters.
A background run is rewritten onto the platform's reporter anyway (streamingBackgroundCommand), so adding the machine report there costs nothing. A foreground run
is not: its reporters are either the command's own flags or the suite's config, and replacing a
config reporter would stop writing the artifact the executor configured. So this only ever
APPENDS json to a --reporter set the command already wrote — the log keeps every printing
reporter it had, the executor's file reporters keep their place, and the standard report goes to
PLAYWRIGHT_REPORT_ENV's file.
A command that names no reporter at all is left exactly as written: its reporters are the suite
config's, and this tool does not rewrite those. A command that already names json, or sets
PLAYWRIGHT_JSON_OUTPUT_FILE itself, already has a report of its own — a path the executor chose
is never overwritten.
function withPlaywrightRunReport(
command: string,
reportPath: string,
): { command: string; reportPath: string | null }
command— The command the executor sent, after every other rewrite.reportPath— The file this run's machine report should be written to.
Returns: The command to run and the report path when one was wired; reportPath is null when the run was left untouched and no report may be expected.
suiteRunStatements(command)
Every statement of a command that starts a whole test suite, in command order.
This is the ONE count of suite runs in a command: isSuiteRunCommand asks it,
repeatedSuiteRunError refuses only simple identical invocations, and a re-run
composed from a command (./suite-overlap.js scopedRerunCommand) keeps only the first.
A statement that invokes a runner only to print is not one of these
(commandRunsNoTests): npx playwright test --list prints the tests it would run and
exits, and npx playwright install, vitest list and hurl --help start no test either.
function suiteRunStatements(command: string): string[]
command— The shell command.
Returns: One entry per suite-running statement, as the parser read it (empty when none).
isSuiteRunCommand(command)
Whether a command runs a whole test suite — a Playwright, Vitest or Hurl run — rather than a build, an install or a one-off script.
function isSuiteRunCommand(command: string): boolean
command— The shell command.
Returns: True when the command starts one of those runners.
repeatedSuiteRunError(command)
Refuse only a command made entirely of identical suite invocations.
Mixed shell commands execute as written. Rebuilding their prefix or suffix can lose writes, break heredoc delimiters or turn an && guard into unconditional work. Different args or environments may select different suites or targets; they are not known duplicates either. This is an optimization, so uncertainty always allows the original command.
function repeatedSuiteRunError(command: string): string | null
command— The shell command as the executor sent it.
Returns: The duplicate-only refusal, or null when the original command should run.
suiteRunBudgetCommand(command, flags)
A command with the supplied suite's own settings written back onto its runner as Playwright flags, and the flags that could not be placed.
The grader walks the suite under its OWN budget, so a run whose runner config sets a different
timeout or worker count measures a run the grader never sees (a 60 s wrapper config produced
a green local proof the official 15 s grader then failed). Playwright
lets a command-line flag win over every config file, so the suite's values are put on the
runner's own arguments — written where statementArgumentEnd places them, never after a
pipe, redirect or group closer. Only the command's LAST suite step is touched: that is the run
every launch site measures.
A flag the command already carries is REWRITTEN in place (last occurrence wins, as it does for Playwright); a flag it does not carry is inserted at the end of the runner's arguments. A command whose runner cannot be placed is returned exactly as written, with every flag reported as unplaced, so the caller states the fact instead of claiming a pin it did not make.
function suiteRunBudgetCommand(
command: string,
flags: readonly string[],
): { command: string; placed: string[]; unplaced: string[] }
command— The shell command about to run.flags— The flags to put on it, each as--name=value.
Returns: The command to run, the flags placed on it, and the ones it could not carry.
suiteRunConfigCommand(command, config)
A command with the derived config put on the LAST suite runner's own arguments, replacing the config the run names or added when it names none.
Some of the suite's settings have no Playwright flag (expect.timeout, use.actionTimeout,
use.navigationTimeout), so a config the executor wrote cannot be corrected from the command
line. The consumer writes a derived config OUTSIDE the supplied suite that re-imports the one
the run selected and pins those settings (SuiteBudgetPin.config); pointing the runner at
it is the one way to carry them, and it belongs on the runner itself for the same reasons
suiteRunBudgetCommand's flags do (last suite step, before a pipe or group closer).
A command whose runner cannot be placed is returned exactly as written with placed: false, so
the caller never claims a config it did not point the run at.
function suiteRunConfigCommand(
command: string,
config: string,
): { command: string; placed: boolean }
command— The shell command about to run.config— The config to run, as the runner takes it (--config <path>).
Returns: The command to run and whether the config was placed.
withoutSuiteTimeout(command)
The command with the timeout <N> wrapper lifted off the statement that runs the suite, and the
bound that was lifted.
Used where the platform moves a run to the background: the executor wrote the bound to fit this
tool's foreground ceiling, and in the background that ceiling no longer applies — the task is
bounded by wait_for_task and the turn's deadline — so the prefix only kills the walk
(withoutTimeoutWrapper).
function withoutSuiteTimeout(command: string): {
command: string
seconds: number | null
}
command— The shell command.
Returns: The rewritten command, and the largest lifted bound (null when nothing was lifted).
isPlaywrightRunCommand(command)
Whether a command starts a Playwright run — a playwright test in command position, in a form
that runs something.
npx playwright test --list matched every \bplaywright\s+test\b test in the platform and was
then treated as a run: held (a config check), backgrounded for a run that outlasts
the tool's ceiling, and rewritten with --reporter. A list takes two seconds, prints its lines
and exits, so it is none of those; commandRunsNoTests is what decides.
A playwright test named as an argument is not a run either (head -30 run-tests.sh,
grep -n "playwright test" e2e/README.md): the command that runs is the reader.
function isPlaywrightRunCommand(command: string): boolean
command— The shell command.
Returns: True when the command starts a Playwright run.
stripTrailingSuiteFilters(command)
Drop the output-only filters piped after the command's suite runners
(suiteFilterDrops).
function stripTrailingSuiteFilters(command: string): SuiteFilterStrip
command— The shell command.
Returns: The rewritten command, and the stages dropped in command order ('' when none were).
suiteRunPipelinePlacement(command)
Where the suite runner's exit code comes from: the runner itself, or a stage piped after it.
suiteRunPipedAfterRunner's one question, with the honest third answer kept apart. The
code a finished run reports is its LAST pipeline stage's, so a stage after the runner makes the
code the stage's — but only when such a stage EXISTS. The platform used to report "piped" for
any run whose statements it could not place in the text, which one heredoc body was enough to
cause: a config written in the same exec_command made the run come back with no exit code
at all, and the note under it claimed a stage after the
runner that was not there. The parse now places every statement (locatedCommandSegments), so
"unplaced" is the rare, named case rather than a guess dressed as an answer.
function suiteRunPipelinePlacement(command: string): SuiteRunPipelinePlacement
command— The shell command, after the streaming rewrite when one was applied.
Returns: Whether a stage follows the runner, and whether the run could be placed at all.
suiteRunPipedAfterRunner(command)
Whether the command's last step runs a suite whose output still passes through a stage after
the runner — one stripTrailingSuiteFilters could not prove is output-only (| tee log,
| xargs …). The pipeline's exit status is that stage's, not the run's.
function suiteRunPipedAfterRunner(command: string): boolean
command— The shell command, after the streaming rewrite when one was applied.
Returns: True when a pipe this tool must not drop still follows the suite runner.
suiteRunPriorityLaunch(command, launch)
Start a background suite run at lower CPU and IO priority, so the sandbox it shares with everything else stays responsive to what the executor does next.
A whole-suite Playwright run saturates the one container the app's Vite server, its API process and every other command also live in: a backgrounded 139-test run has left the two-word shell command sent next — tick its plan file — returning nothing for 2 min 40 s, measured on the chat payload and on the live-stream follower independently. The backgrounding note is right that the executor should go do other work; what it cannot promise is that the sandbox will let it.
nice -n 10 lowers the run's CPU share and ionice -c3 its IO class. Both
are PROBED in the sandbox by RUNNING them, not with command -v: a syscall a
container's seccomp policy refuses leaves -v passing while the real run
fails. Each is applied only if its probe passed, so a sandbox with neither,
or with only one, runs the suite exactly as it did before. Playwright's own
workers are children of this shell and inherit both (niceness and IO class
are inherited across fork/exec).
Only a command the caller has already detached reaches this: foreground commands are never touched.
function suiteRunPriorityLaunch(command: string, launch: string): { launch: string; note: string }
command— The command as the executor sent it; the suite detection reads this.launch— The shell line that would start it, with no prefix of its own.
Returns: The line to run, and one sentence for the tool note ('' when unchanged).
checkBlockedCommand(command)
Check if a command is blocked for security reasons. Returns error message or null if allowed.
The first check reads the commands the shell actually RUNS — the statements, a sh -c
string's body, and every command substitution (executedCommands) — so a | inside a
quoted grep alternation is data, not a pipeline: grep -E "USER CALLS|ENV|BUTTON|passed|failed" app.log prints log lines, and the ENV in its pattern starts nothing — a text
match would block exactly that call as an environment dump, twice over. What the
shell DOES run stays visible through the same walk: ls | env, bash -c 'env',
echo "$(printenv)" and a nested sh -c 'x; env' are all commands, and so is env itself
when nothing follows it.
function checkBlockedCommand(command: string): string | null
command— Shell command string proposed for execution.
Returns: A human-readable block reason, or null when the command is allowed.
resolvePath(path, projectRoot)
Normalize the project root and resolve a path absolutely within it. Empty string and '/' both resolve to projectRoot. Rejects paths that escape via traversal or absolute paths outside root.
function resolvePath(path: string, projectRoot: string): string
path— Relative or absolute path inside the workspace.projectRoot— Absolute filesystem root for the active project.
Returns: A normalized absolute path confined to projectRoot.
isOutsideRoot(path, projectRoot)
Whether a tool path points outside the normalized project root (an
absolute path elsewhere, or a .. that climbs out). resolvePath
clamps such a path to the root; a file tool must refuse it instead of
answering about the root — a list_files /tmp/x used to return the
workspace listing as if it were /tmp/x.
function isOutsideRoot(path: string, projectRoot: string): boolean
path— The path the tool was given.projectRoot— The project root.
Returns: True when the path leaves the root.
commandStartsWithCdInto(command, directory, projectRoot)
Whether a command's FIRST statement already changes into directory.
exec_command refuses a cwd outside the workspace, and that refusal tells
the caller to drop cwd and start the command with cd <path> && . When the
command ALREADY starts that way the advice describes what was just sent, so
the command runs as written with the backend's working directory at the root
instead ({cwd: "/tmp", command: "cd /tmp && …"} was refused with "start the command with
cd /tmp && "; the same command resent with cwd: "/workspace" then passes).
Only the leading statement counts, only when the shell's own parse puts it in
the caller's shell — a ( cd … ) group or a sh -c '…' runs in its own
directory and moves nothing — and only when it ends the way a following
command needs (&&, ;, a newline, or nothing after it). cd … | cat is a
pipeline, so its cd runs in a subshell, and & backgrounds it: neither
leaves the caller's directory changed.
function commandStartsWithCdInto(command: string, directory: string, projectRoot: string): boolean
command— The shell command as the tool received it.directory— Thecwdthe caller asked for.projectRoot— The project root a relative path is resolved against.
Returns: True when the command's first statement cds into directory.
isValidGlob(pattern)
Validate that a glob/include pattern is safe (no shell metacharacters that could
inject). Allows alphanumeric, * ? . _ - / and the bracket/paren glob chars [] ().
The brackets/parens matter for real frameworks: Next.js App Router names route
directories [id], [...slug], (group), [[...optional]], so without them the
executor cannot find_files/search_files its own routes on any Next.js project — a
hard block observed on live imports. They are injection-safe here because every caller
passes the pattern through shellQuote before it reaches find -name/grep --include,
where inside single quotes []() are literal (a subshell (...) only starts UNquoted);
to the glob engine [abc] is a normal character class. The genuinely dangerous
metacharacters (; | & $ \ > < \n` space) remain disallowed.
function isValidGlob(pattern: string): boolean
pattern— User-supplied glob fragment for search/list operations.
Returns: true when the pattern contains only allowed characters.
expandBraceGlob(pattern)
Expand ONE level of brace alternatives in a glob pattern, validating every expanded pattern.
Neither search tool expands braces itself: grep --include and find take
the pattern as a single shell-quoted argument, so no shell ever sees it.
find_files {pattern:"*.{ts,tsx}"} and search_files {include:"*.{ts,tsx}"}
were both refused outright, costing a round trip and pushing the agent to a narrower
search. The group is expanded here
instead — search_files passes one --include per alternative and
find_files ORs one -name/-path predicate per alternative.
Bounded on purpose: one level of braces, alternatives split on ,, at most
MAX_BRACE_GLOB_ALTERNATIVES, none empty, and each EXPANDED pattern
must still pass isValidGlob — so a shell metacharacter in any
alternative (*.{ts,$(rm)}) is refused exactly as a bare one is.
function expandBraceGlob(pattern: string): string[] | null
pattern— The user-supplied glob.
Returns: Every pattern the value expands to, or null when it is not accepted (the caller reports its tool's glob error).
findPatternArgs(pattern)
The find predicate for a find_files pattern.
find -name compares a pattern against a file's BASENAME, so a pattern
containing a slash (helpers/*, e2e/*.spec.ts, src + ** + /App.tsx)
can never match and the tool answers [] (twice in one run). Such a pattern is matched
with -path instead: an fnmatch
glob over the whole printed path, whose * crosses / — the rule
.gitignore uses, and the reason a bare helpers/* means "a helpers/
directory anywhere below the root". The pattern is anchored with a leading
* then / ("any parent") so the search root — an absolute
/workspace/<app> in a sandbox — need not be spelled out.
A doubled-star directory segment keeps its usual meaning of ZERO or more
directories; -path alone would demand at least one, so the pattern is also
emitted with each such segment removed.
function findPatternArgs(pattern: string): string
pattern— A pattern already accepted byisValidGlob.
Returns: A find predicate: -name '…' for a bare name, else one or more -path '…' alternatives, ORed inside parens when there is more than one.
findPathArgs(pattern)
The -path alternatives of findPatternArgs, for a pattern whose
directory the caller has already rooted the search at.
find_files narrows the search root itself when the pattern spells its own
directory out (see literalDirPrefix) — node_modules plus
@molecule/api-resource-user/dist/*.d.ts searched that one directory. The
remainder (*.d.ts) must then keep the -path form rather than collapsing to
-name: * crosses / in an fnmatch glob, so the -path form still finds a
declaration file in a dist/utilities/ subdirectory, which -name '*.d.ts'
would drop (a silent partial answer, which is worse than the timeout it
replaced).
function findPathArgs(pattern: string): string
pattern— The pattern's remainder, with a/in it or not.
Returns: One or more -path '…' alternatives, ORed inside parens when there is more than one.
literalDirPrefix(pattern, root)
The directory a GLOB pattern spells out, when it spells one out: everything
before the pattern's first glob character, trimmed back to the last /.
A pattern is matched against the whole path with a leading "any parent"
anchor (findPatternArgs), so find visits every entry below the
search root. Handed /workspace/node_modules and
@molecule/api-resource-user/dist/*.d.ts — a directory named outright —
find walked the sandbox's entire dependency tree and hit the tool's 10 s
deadline without printing a result (the one directory the model meant answered a list_files
in 0 s). The literal prefix is that
directory, and rooting the search at it is what keeps the call instant.
A BARE first segment (helpers/*, bonds/*, e2e/*.spec.ts) is NOT one:
helpers/* means "a helpers/ directory anywhere below the root", which the
tool documents and a live run relied on (a path pattern is not anchored to one depth).
Rooting those at
<root>/helpers would answer with a SUBSET, silently: the nested
api/src/helpers/ matches would disappear, and a missing file reads as
"no such file". So a prefix is returned only when it names a path of two or
more segments (@molecule/api-resource-user/dist), which is the shape that
is a directory rather than a directory name.
An npm SCOPE as the first segment, under a node_modules root, is the one
exception that parameter root enables: npm installs a scope only directly
inside a node_modules directory, and the walk already prunes every nested
node_modules (see findPruneArgs), so the whole-tree form can only ever
match <root>/@molecule/… — the scope directory IS the directory the pattern
names. Left un-narrowed, a scoped-package pattern walked the sandbox's entire
dependency tree and hit the 10 s deadline with no result at all. A bare NAME stays a
directory name at any depth:
helpers/* is unchanged even under a node_modules root.
function literalDirPrefix(pattern: string, root?: string): string | null
pattern— A pattern already accepted byisValidGlob.root— The resolved search root, when one is already known; a scope-first prefix is returned only when this ends in anode_modulessegment (and the pattern has more path after the scope).
Returns: The literal directory prefix, without a trailing slash, or null when the pattern has no glob character, no /, or only a bare name before one.
isCommandTimeout(error)
Whether a backend error is the sandbox's own command deadline.
The E2B SDK answers a timed-out exec with its generic text —
[deadline_exceeded] the operation timed out: … It can be modified by passing 'timeoutMs' when making the request. Use '0' to disable the timeout. — which
names an option the executor cannot set and says nothing about the search
that died. Handing that sentence to the model is what a run
read after find_files spent 10 s walking node_modules; the tool answers
the deadline in its own words instead (see searchTimeoutError).
function isCommandTimeout(error: unknown): boolean
error— The error the backend threw.
Returns: True when the error reads as a timeout or a deadline.
searchTimeoutError(tool, searched, pattern, seconds, hint)
The answer a search tool gives when the backend's deadline fires: what was
searched, for what, how long the tool allowed, and the two ways to get an
answer — a narrower path, or a listing. Never the vendor's timeoutMs
sentence (see isCommandTimeout).
function searchTimeoutError(
tool: string,
searched: string,
pattern: string,
seconds: number,
hint: string,
): string
tool— The tool that timed out (find_files,search_files).searched— The directory the search actually covered.pattern— The pattern it was searching for.seconds— The tool's own limit, in seconds.hint— What to do differently — the narrower target or the listing tool.
Returns: The message's text.
pathArgError(path, tool)
Validate a file tool's path argument is a non-empty string. A weak model
sometimes omits it or passes a non-string, which would otherwise crash
resolvePath (path.replace on undefined) with the cryptic, unactionable
"Cannot read properties of undefined (reading 'replace')" — wasting executor
turns. Returns an actionable message, or null when the path is usable.
function pathArgError(path: unknown, tool: string): string | null
path— The rawpathargument from the tool input.tool— The tool name, for the error message (e.g. 'read_file').
Returns: An actionable error string, or null when path is a non-empty string.
emptyCallError(input, tool)
The error for a file tool called with NO arguments at all — edit_file {}, the
shape a truncated provider stream leaves behind.
The path message is the wrong reading of it: "requires a non-empty path
argument" says the call was understood and the path was left out, so the model
retries the call it just made instead of sending the whole call again (edit_file {} loses
one round). An empty object and a
missing path are different failures and deserve different sentences.
function emptyCallError(input: unknown, tool: string): string | null
input— The raw tool input.tool— The tool name, for the message.
Returns: The truncation message, or null when the call carried any argument.
directoryReadHint(message, path)
Detect a "read/edit targeted a directory, not a file" failure from a backend
error message (local fs EISDIR or the sandbox's cat: X: Is a directory),
and return an actionable message steering the model to list_files. Returns
null when the error is not a directory error.
function directoryReadHint(message: string, path: string): string | null
message— The backend error message.path— The resolved path that was targeted.
Returns: An actionable directory-error string, or null.
sliceLines(content, window)
Return a line window of content, or null when no window was asked for.
read_file returned whole files only, so an executor that wanted part of one
shelled out: across six real agent runs, 260 of 377 shell-inspection commands
(69%) were head/tail/sed -n windowing a file the tool could have
windowed itself. offset is 1-based, matching the line numbers every other
tool reports and what grep -n prints.
function sliceLines(
content: string,
window?: { offset?: unknown; limit?: unknown },
): { text: string; offset: number; lines: number; totalLines: number; truncated: boolean } | null
content— The file's full text.window— The requestedoffset(1-based) andlimit(line count).
Returns: The window plus its position, or null when neither was given.
serializedChars(text)
A file's text as the request counts it: the length of its JSON string.
JSON escaping (\n → \\n, " → \") costs characters, and the request
side counts the SERIALIZED tool result. A window of 59,000 characters of
source — 1,200 lines — arrives as ~60,200 characters of JSON, over the
ceiling it was sized for, so a window is measured with this rather than by
its raw text length.
function serializedChars(text: string): number
text— The text.
Returns: Its serialized length, without the surrounding quotes.
linesWithinSerialized(content, chars)
How many leading lines of a file fit inside a budget of SERIALIZED chars,
the way read_file sizes a window (see serializedChars).
function linesWithinSerialized(content: string, chars: number): number
content— The file's full text.chars— The budget in serialized chars.
Returns: The line count, at least one.
looksLikeHtml(text)
Whether text is an HTML document (a doctype or an <html root tag).
function looksLikeHtml(text: string): boolean
htmlOutline(text, label)
An OUTLINE of an HTML document: its head's tags and the tags that open each body section, one per line, with line numbers.
Line-based on purpose — a parser would be a dependency and an attack surface
for a read that only has to be navigable. A line is shown when it starts with
< after trimming, which is what keeps the inside of a <style> block, a
<script> body or a prerendered text section out of the outline while keeping
every tag the document is built from. Long lines (a minified tag, a data URI)
are cut, and the whole outline is capped, so a pathological document cannot
turn one read into another wall of text.
function htmlOutline(text: string, label?: string): string | null
text— The document's full text.label— What to call the document in the outline's header (its path).
Returns: The outline — or null when text is not an HTML document.
truncate(s, maxLength)
Truncate a string to a max length with a truncation notice.
function truncate(s: string, maxLength: number): string
s— Arbitrary text to bound in size.maxLength— Maximum number of characters to retain before truncating.
Returns: Either the original string or a shortened copy with a trailing notice.
truncateMiddle(s, maxLength)
Truncate keeping BOTH the head and the tail, eliding the middle — for command
output (build / test / migration / install logs). Plain head truncation
(truncate) drops the TAIL, which is exactly where a failing command puts
the reason: the npm ERR! line, the test-failure summary (1 failed, 240 passed), the migration stack trace. When that is cut, the executor sees only
passing progress and can't tell WHY the command failed — a self-inflicted error
then survives every fix round. The head still shows what ran and the first
errors; the split is weighted toward the tail since the summary lives there.
No-op when s already fits.
function truncateMiddle(s: string, maxLength: number): string
s— Arbitrary text (typically stdout/stderr) to bound in size.maxLength— Maximum characters to retain (excluding the elision notice). Failure identities always survive the cut; detail bodies are capped at 1,500 characters each and by the remaining total budget. An identity inventory larger than the budget is retained whole, with omitted details counted. Fitting logs and logs without failures pay no summary cost.
Returns: The original string, or bounded progress and failure details with every failure named.
failureBlocks(s)
The numbered failure blocks of a Playwright report ( 1) [chromium] › file:line › title
up to the next block or the tally).
function failureBlocks(s: string): string[]
s— Test-runner output.
Returns: Each block, in order (empty when there are none).
runningOutputSliceCommand(log, own, command)
The shell command whose stdout is the interesting part of a log that is still being written:
the failure lines so far (capped at RUNNING_FAILURE_LINES), then the end of the log.
A Playwright list run prints one line per test as it finishes, so the LAST bytes of a running
log are its least informative part — the last 3 000 bytes of a 139-test walk are the skip
list, and all 61 failures were above them, which costs the run the grep it has to make anyway. A background run also carries each failure's own error as it fails
(PLAYWRIGHT_FAILURES_INLINE_ENV), and RUNNING_FAILURE_LINE_RE already matches
those blocks' headers and their Error: lines, so this slice shows the causes too.
function runningOutputSliceCommand(log: string, own?: string): string
log— The task log path.own— A file the command redirects its own output to, if any.command— Executed command, whose logical plan supplies live step boundaries if present.
Returns: The shell command, safe to hand to the execution backend as-is.
runningCauseCommand(log, own)
The shell command whose stdout is enough of a running log to tell whether one cause is
repeating: its tail, REPEATING_CAUSE_TAIL_BYTES of it.
runningOutputSliceCommand is the wrong read for this: it keeps only the FIRST 40
failure lines plus 1 000 bytes, so on a run whose failures print a body each — which is what
a line reporter does, and the only form that names the cause as an error message rather than
a duration — three bodies do not fit, and the repeat is invisible. This read is not shown to
anyone; it is parsed.
function runningCauseCommand(log: string, own?: string, command?: string): string
log— The task log path.own— A file the command redirects its own output to, if any.
Returns: The shell command, safe to hand to the execution backend as-is.
runningLogReadCommand(log, own)
The shell command whose stdout is a bounded CONTIGUOUS read of a running task's own log: the
log's byte size, then its last RUNNING_LOG_READ_BYTES bytes.
runningOutputSliceCommand is the wrong read for a diagnosis: it
stitches the first 40 grep-selected failure lines to the last 1 000 bytes with a blank line
between, so the tail is DISJOINT from the headers above it. Read as one log, the last numbered
header absorbs whatever the tail starts with — a clipped skipped-test title becomes the cause
of a genuine failure. A contiguous window can only ever hold real
neighbouring lines of one log.
The size rides along so a caller can say when the window is only the log's end
(parseRunningLogRead); without it a tail reads as the whole run.
function runningLogReadCommand(log: string, own?: string): string
log— The task log path.own— A file the command redirects its own output to, if any.
Returns: The shell command, safe to hand to the execution backend as-is.
parseRunningLogRead(stdout)
The two parts of runningLogReadCommand's answer.
function parseRunningLogRead(stdout: string): RunningLogRead | null
stdout— The command's stdout.
Returns: The window and the whole log's byte size, or null when the size line is absent (the read did not run, so nothing may be said about the log).
repeatingFailure(log)
The cause repeating among a running suite's failures, or null.
Playwright's list reporter prints one line per test as it finishes — its mark, its title
path and how long it ran — and, on a run the platform started in the background, each failure's
own error with it (PLAYWRIGHT_FAILURES_INLINE_ENV); a list run with no error bodies in
its log (an older Playwright, a log the bodies have been cut from) carries only the duration as
a signature. Where the log carries the failure bodies (either inline, or in a finished run's
summary) the signature is the
error itself — failureMessage: the error class plus the locator or the values that
differ — which is stronger (it needs no assumption about how long a failure should take), so
the message is looked for first and the duration is then left with the tests whose bodies the
log does NOT carry.
Either way the point is the same: a suite whose failures repeat one cause spends its whole
runtime proving that one cause, and the executor watching it can be told so at the third
failure instead of at the last. Fifteen tests walked in 4.0 minutes where 15.6 s
each was the test timeout and one missing navigate('/') was the cause of all of them.
The quorum is of DISTINCT tests — REPEATING_FAILURE_MIN of them — because a log that
prints each failure twice (a second reporter, a retry) has told a run that four of its
tests failed the same way when two had, so the executor stopped a 139-test walk at test 21
with one cause in hand.
function repeatingFailure(log: string): RepeatingFailure | null
log— The log so far.
Returns: The repeating cause, or null when no signature has REPEATING_FAILURE_MIN distinct tests behind it.
logShowsInlineFailureBodies(log, excluded, options)
Whether the log read so far carries a failure's own body under a ✘ row — the evidence that a
run prints each failure's error as that test fails (PLAYWRIGHT_FAILURES_INLINE_ENV).
wait_for_task promises the executor that each failure's report sits right under its ✘ line
only when the log proves it. The command's shape cannot answer: the launch sets the switch on
every background command (the executor's wrapper script inherits it), so a wrapper this reader
cannot place is exactly as covered as npx playwright test (streamingBackgroundCommand).
The log is the evidence — a 1) [project] › spec › title ─── block whose test the log also
printed with ✘ (failureBlocks).
A block alone is not enough: a FINISHED run's end-of-run summary carries the same blocks, and a
running wait must not be told "as it fails" about a log whose bodies only appear at the end.
During a wait the run has not ended (the exit file is read first), so a block beside a ✘ row
is one the reporter printed inline.
A body for a test the request EXCLUDES is not that evidence: its failure does not count for
this request (matchingExcludedTitles), so a wait that handed it over as the diagnostic
spent a model round trip and 8 k of partial log on a test the same result says to ignore —
which a run has done twice while the platform's proof was still walking.
With finalOnly, only a failure the run has FINISHED with counts; a pending retry waits.
function logShowsInlineFailureBodies(
log: string,
excluded?: readonly string[],
options?: {
finalOnly?: boolean
noRetries?: boolean
excludeTestBudget?: boolean
onCause?: (cause: string) => void
},
): boolean
log— A log, or the slice of one a wait reads.excluded— The test titles the request carves out, if the caller knows them.options—finalOnlyreads only a failure the run has finished with;noRetriessays the command proves the run cannot retry (--retries=0), so its first failure is final.excludeTestBudgetskips whole-test deadline errors when collecting repair cues.onCausereceives each distinct normalized native error from the matching bodies.
Returns: True when a ✘ row's own test, outside the request's exclusions, has a failure body under it — and, with finalOnly, that failure is final in the log read so far.
specFilesSelected(command)
How many test FILES a Playwright run's own command narrows it to, or null when it selects the whole suite (or its selection cannot be read).
universalCause's file threshold is written for a whole-suite run, which a narrowed run
can never reach. A run that re-ran ONE spec file against a hand-started vite preview the
browser could not reach had every test in it fail page.goto: Timeout —
but one file is below UNIVERSAL_CAUSE_FILES, so the wait sat out its entire 280 s
budget on a run that had already measured all it could.
The command is read through commandSegments, so a playwright test named as an
argument is not a run. A PLAYWRIGHT_VALUE_FLAGS flag written without = takes the next
word as its value, so a --config app/e2e-suite.config.ts is never counted as a spec file; a
directory or a bare substring filter names files the command does not list, which answers null
(the whole-suite threshold) rather than a count of the wrong files.
function specFilesSelected(command: string): number | null
command— The run's command.
Returns: The number of distinct test files it names, or null when it names none (the whole suite) or the selection cannot be told.
universalCause(log, found, command)
Whether a repeating cause is failing the whole run — the one case where stopping it is the right call.
The test is: the cause accounts for every failure the log names, it has hit the spec-file
threshold, and nothing has passed since its first failure. The threshold is
UNIVERSAL_CAUSE_FILES for a whole-suite run but the number of files the command
SELECTED for a narrowed one (specFilesSelected): a one-file run can never span three,
and a run can wait out its whole budget on exactly that shape. An app
that is not up, a 5xx on every request, or a selector that is missing on every page all look
like that, and every remaining test will fail the same way — so the run's remaining minutes
measure nothing. A CONNECTION-class cause (CONNECTION_CAUSE) needs no file span at all:
three tests that could not reach the app, with nothing passing since, is the app-unreachable
case however few files the run walks.
Anything less is NOT this: a cause that stops at one file of a multi-file run, or that leaves other tests passing, or that shares the run with failures of another shape, leaves the run with something to say, and the run is the only thing that will say it. Stopping runs at their first repeating cause has burned eight local runs over 14.5 minutes without finishing one; three of its deploys each fixed a single cause that a finished run would have listed alongside the others.
function universalCause(
log: string,
found: RepeatingFailure | null,
command?: string | null,
): UniversalCause | null
log— The log so far.found— The repeating causerepeatingFailurefound in it, or null when no two failures share a signature (a page that renders nothing fails each spec at its own first locator —emptyPageCausestill reads that run).command— How the run was started, when the caller knows it: its spec-file selection scales the file threshold (specFilesSelected).
Returns: The cause's count and files, or null when the run is not failing whole.
earlyReturnCause(found, universal)
The ONE finding that ends a wait early, and the only one a note may hand a stop command over for: a PROVEN cause that is failing the whole run.
Both halves are load-bearing, each of them learned from a run that lost minutes to the other.
- Failing the WHOLE run is
universalCause: every failure the log names, across the spec-file threshold —UNIVERSAL_CAUSE_FILES, or the files a narrowed run's own command selects, orCONNECTION_CAUSE_TESTStests of an app that never answered — with nothing passing since the first. That is the dont-stop-runs rule. Stopping runs at their first repeating cause has burned eight local runs in 14.5 minutes without finishing one, and a run that still has other causes left to name is the only thing that will name them. - A PROVEN cause is an error repeated VERBATIM. A shared DURATION is a LEAD, never a cause:
a suite whose config sets a timeout spends that timeout on every failure that waits for
anything, so three unrelated tests timing out together look exactly like one broken run
(
~7 sis a property of the CONFIG, not of the cause —normalizedSignature). A run toldstatus: 'repeating_failure'twice on that shape — threeurl-navigation.spec.tstests at ~16.2 s, onetimeout: 15_000plus teardown — read the early return as "stop waiting, edit now", and voided a run that was still walking; the second cost a 224 s wait that ended with no result at all.
Neither half alone is enough, and repeatingFailure finding a signature is not either:
that answers "is a cause repeating among this run's failures", which is worth telling the
executor mid-run as a NOTE while the wait goes on. This answers the narrower question the wait
needs — is the run over as a measuring instrument — and it is THE one predicate behind both
that decision and the note's wording, so the two cannot come to different verdicts.
function earlyReturnCause(
found: RepeatingFailure | null,
universal: UniversalCause | null | undefined,
): UniversalCause | null
found— WhatrepeatingFailurefound mid-run, or null when no signature repeats.universal— WhatuniversalCausefound for it, if anything.
Returns: The cause to stop the run over, or null — in which case nothing may be stopped, the wait keeps going, and the finding rides the run's result as a note.
matchingExcludedTitles(heading, excluded)
The titles a request excludes that a test's heading names — the ONE matcher for "is this failure one the request does not count?".
The request quotes a test's own title (… except "should require login to post comment",
extracted by molecule-dev's excludedTestTitles) while a run's heading carries more of it
(comments.spec.ts › Comments › should require login to post comment), so containment is the
comparison. Whitespace is normalised and case is ignored: a brief may wrap the title across a
line, and the reporter's own casing never has to match the brief's.
Two readers used to answer this separately — the causes note (which therefore asked the executor to fix a test the same result said not to) and molecule-dev's exclusion notes — and a run paid for the gap (a turn and an edit spent on the excluded test).
function matchingExcludedTitles(heading: string, excluded: readonly string[]): string[]
heading— The text to match against: a test's title, its wholefile › describe › titlepath, or (for a note that only has the run's output) the run's text.excluded— The titles the request carves out, if the caller knows them.
Returns: The excluded titles this heading names, in the request's order.
failuresByCause(log, excluded)
Every failure a run names, grouped by the cause behind it — one group per cause, with the tests it hit.
The point is that ONE run yields EVERY cause. A Playwright report prints its failures one after another with no statement of which of them share a cause, so a run of 19 failures is 19 bodies to read; three deploys (6.7 minutes) each fixed a single cause, two of them found by runs stopped before they walked the rest.
The signature is the cause itself where the log carries the failures' bodies (a finished run, a
background list run — whose failures print as they fail — or a line reporter) —
failureMessage: the error class plus the locator or the values that differ — and how long
they took where it does not, which is why a duration group is labelled as a duration and not as a
proven cause. A test the log printed twice, or failed twice, is one test.
A test the request EXCLUDES by name is not a cause to fix: its failure does not count for
this request (matchingExcludedTitles), so it is dropped here rather than handed to the
executor as work — a result that names it beside "it does not count" is the contradiction
a run filed (the model spent a turn and an edit on the excluded test, on a page that was
passing).
function failuresByCause(log: string, excluded?: readonly string[]): FailureCause[]
log— The log of a finished or running run.excluded— The test titles the request carves out, if the caller knows them.
Returns: The causes, the one with the most tests first.
requiredLandmark(selector)
The landmark a selector requires as an ANCESTOR (or names as its own role), or null when it
names no landmark at all (h1, .article-preview, a[href="/profile/x"]).
function requiredLandmark(selector: string): RequiredLandmark | null
selector— One CSS selector orgetByRolerole from a failure's call log.
Returns: The landmark, or null.
missingHeaderNote(log, pageErrors)
The sentence for a run whose navigational elements are all missing from pages that otherwise painted — the missing shared header the executor must check BEFORE rewriting auth.
A run had four failures on / — a[href="/profile/…"],
a.navbar-brand, nav a[href="/"], nav .user-pic — while every error-context.md snapshot
showed the feed, sidebar and footer with no navigation at all. Home.tsx imported and
re-exported Navbar but never rendered it, and App.tsx mounted <Home /> in a bare route.
The cause list named four unrelated symptoms, so the run rewrote Navbar's auth logic and then
the HTTP bond across two whole walks (~6 minutes) instead of mounting the header.
The reading is per FAILURE and per SNAPSHOT: each failure's own selector must require the
landmark, its own snapshot must have been read AND show populated page content, and that
snapshot must not contain the landmark. Two or more such failures on ONE route (the route a
selector names, e.g. nav a[href="/"] → /; failures whose selector names none ride along)
are the group. A page that shows the navigation and merely misses a signed-in link is not this
shape — its snapshots contain the landmark, so nothing is said.
This never stops the run and never claims the page is blank: it is one sentence prepended to
the causes note (failureCausesNote).
function missingHeaderNote(log: string, pageErrors?: readonly CausePageErrors[]): string | null
log— The run's output.pageErrors— The page snapshot facts the caller read per failing test.
Returns: The sentence, or null when the failures do not share a missing landmark.
failureCausesNote(log, excluded, run, pageErrors, regressedSpecs, displayedLog)
The one-line-per-cause summary of a run's failures, or null when the run named none, or named one in a short log returned whole to the reader.
This is what makes a run worth finishing: every cause the run found, in the result the executor reads, so one round of fixes covers all of them rather than the one cause a run stopped early happened to reach.
A test the request excludes is not one of the causes — it is dropped and named once, at the
end, so a result never asks to fix a test it also says to ignore. A test the runner itself
declared flaky (it failed once and passed on its config retry) is not a cause either: it is
named apart from them, once, as what the tally called it (flakyTestsDeclared). Where
the caller knows how the run was started, the note also hands over the narrowed re-run of
exactly those tests (rerunOfRunningSuite) instead of leaving the executor to re-run the
whole suite.
A run whose failures are ALL NO_BASE_URL_ERROR is not a set of causes at all: it is one
navigation configuration failure, said in one line (invalidNavigationConfigNote) rather than a list that
reads as ten defects in the app.
function failureCausesNote(
log: string,
excluded?: readonly string[],
run?: {
command: string
cwd?: string
log?: string
config?: string | null
env?: readonly RunEnvSetting[]
},
pageErrors?: readonly CausePageErrors[],
regressedSpecs?: readonly string[],
displayedLog?: string,
): string | null
log— The diagnostic log, which may be a running or explicitly clipped read.excluded— The test titles the request carves out, if the caller knows them.run— How the run was started, when the caller knows it: the narrowed re-run is built fromcommand/cwd/config/env, andlog(the path the output was written to) is what the "left out" sentence greps when more causes exist than the result has room for.pageErrors— Page evidence for the tests whose failures are being summarized.regressedSpecs— Specs whose selector contracts were broken by subsequent edits.displayedLog— The log text returned to the reader, when different from the diagnostic log (for example a running task's failure headings and tail). A short diagnostic read does not prove that this separate display delivered its error, so it also gets a single recap.
Returns: The note, or null.
rerunOfRunningSuite(run, locations, excluded)
The command that re-runs the tests at locations the way the run IN FLIGHT ran them: the same
invocation, in the same directory, narrowed to those tests — or null when the running command
is not a Playwright run this can narrow.
A run against a DEPLOYED URL keeps the suite's own retries and tracing in its re-run
(scopedRerunCommand suiteSettings): the deployed measurement is the one the deploy is
graded on, and neither the platform's --retries=0 nor its recording --trace belongs on it.
The locations are the paths the run's own log printed, which are relative to the directory
that run started in, so the composer resolves them there (scopedRerunCommand): the
command names that directory unless it already changes into one of its own, because the
executor's next command starts wherever it starts. The returned command is for AFTER the run
ends — it is a second run against the same app and database, and that is exactly what is
refused while the run walks (suiteRunInTheWay).
function rerunOfRunningSuite(
run: { command: string; cwd?: string; config?: string | null; env?: readonly RunEnvSetting[] },
locations: readonly string[],
excluded?: readonly string[],
): string | null
run— The run in flight: the command it was started with, as it was run, the directory that command ran in, the config it loaded when the caller knows it, and the settings the request required and the run left out (env) — the re-run carries them, so it never reproduces the configuration the run was measured under by mistake.locations— The failingfile:lines to re-run, as the run's log printed them.excluded— The test titles the request carves out: the re-run inverts them out (--grep-invert) so it cannot report them again.
Returns: The re-run command, or null when there is no suite to narrow.
repeatingFailureNote(found, o)
The sentence that names a cause repeating among a running suite's failures, mid-run.
Kept here, beside repeatingFailure, so the two stay in step: every word below is about
what that function could actually see in the log — including the count, which is of DISTINCT
tests, so the note never names one or two tests as a cause.
The note names the cause early so the executor can START FIXING while the run keeps walking,
and it hands a stop command over only when earlyReturnCause says so — the SAME
predicate the wait uses to decide whether to return early, so a finding the wait keeps waiting
on is a finding this note never asks to stop for. One run spent 4.0 minutes
walking 15 tests whose one cause was certain at the third, 47 s in, and the note answers
exactly that; another stopped eight runs at their first repeating cause in 14.5
minutes and never finished one, so the note must not say to stop when the run still has other
causes to name. The third shape: a shared duration is
not a cause at all, so a lead reaches the executor as a note on a result it is still waiting
for — never as a verdict with a stop command in it.
The run is STILL WALKING while this note is written — both callers produce it mid-run — so a
re-run of one of its tests is a second run against the same app and database, and the platform
refuses that (suiteRunInTheWay, the same rule its overlap hold answers with):
an executor read "Start on them now, while the run keeps walking.
null-fields.spec.ts:53 alone reproduces the first one." and sent exactly that re-run 23 s
later, where the hold answered "A playwright suite is already running against this app and
database … Wait for it." The note therefore hands over the read-and-fix to do NOW and the
re-run for after the run ends — the exact command where the caller knows how the run was
started (rerunOfRunningSuite), the timing alone where it does not.
function repeatingFailureNote(
found: RepeatingFailure,
o: {
taskId: string
log: string
stop: string
universal?: UniversalCause | null
run?: { command: string; cwd?: string; env?: readonly RunEnvSetting[] }
editsInvalidateRun?: boolean
},
): string
found— WhatrepeatingFailurefound.o— The run's facts: itstaskId, itslogpath,stop— the shell command that stops it, printed only for anearlyReturnCause—universal, whatuniversalCausefound (absent means the run is not failing whole),run, how the run was started (rerunOfRunningSuite) when the caller knows it, andeditsInvalidateRun, true when the run measures the sandbox's own app (a local run, where an edit now changes what the suite is testing and its result stops counting).
Returns: The note.
whitespaceTolerantReplace(content, oldString, newString)
Attempt a whitespace-tolerant replacement when an exact old_string match
failed. Finds a contiguous run of lines in content whose per-line
whitespace-normalized form (runs of whitespace collapsed to one space, then
trimmed) equals the normalized oldString lines, and replaces that run with
newString verbatim. Applies ONLY when exactly one such run exists —
uniqueness keeps it safe; an ambiguous (or zero) match is refused (returns
null) so the caller falls back to its existing error path.
This rescues the most common edit_file failure: a (weak) executor reproduces the target text correctly but with different indentation or trailing whitespace, which would otherwise bounce it into a re-read/retry loop — the single biggest source of wasted edit turns.
function whitespaceTolerantReplace(
content: string,
oldString: string,
newString: string,
): string | null
content— Current file content.oldString— The search text (an exact match has already failed).newString— The replacement text, applied verbatim.
Returns: The new content if a unique fuzzy run matched, else null.
sameModuleNote(path, stdout)
What the write's result says when another file in its folder answers the same import, or null.
auth.ts and auth.tsx side by side both answer ./auth.js. TypeScript and Vite both try
.ts before .tsx, so the .tsx never runs, yet it is still type-checked and shipped, and a
change elsewhere can break the build through it. A .js or .jsx sibling can make the
type-checker and the bundler load different files, so that case names no winner.
function sameModuleNote(path: string, stdout: string): string | null
path— The written file's path.stdout— The parse check's standard output.
Returns: The note, or null when no sibling answers the same import.
parseCheckCommand(path)
The shell command that parses one file and exits non-zero with the error
when it does not parse: node --check for JavaScript, JSON.parse for
ordinary JSON, TypeScript's config parser for tsconfig/jsconfig files
(which are JSONC), esbuild's transform (present wherever Vite is) for
TypeScript.
function parseCheckCommand(path: string): string | null
path— The file's absolute path.
Returns: The command, or null when the file type has no cheap parser.
parseCheckProblem(result)
What a failed parse check says to the executor, or null when the check passed or could not run (no parser available is not a syntax error).
function parseCheckProblem(result: {
stdout: string
stderr: string
exitCode: number
}): string | null
result— The check command's result.
Returns: The message for the tool result, or null.
fusedLine(content, newString)
The line a replacement fused when it dropped the newline its old_string
ended with: new_string's text is followed on the same line by what used to
be the next line. Read off the file as it now is, so the line shown is the
line the parser is actually complaining about.
function fusedLine(content: string, newString: string): { line: number; text: string } | null
content— The file's content after the edit.newString— A replacement'snew_string, whoseold_stringended with a newline.
Returns: The fused line's 1-based number and its text, or null when the replacement's text is not followed by more of the same line (it ends the file, the following newline survived, or another replacement rewrote it).
Constants
CUT_AT_BUDGET
The state a result carries when a budget stopped its command: a run that did not finish is not a run that passed, and no reader may treat it as one.
const CUT_AT_BUDGET: 'cut_at_budget'
INLINE_SCRIPT_BUDGET_MS
How long an inline interpreter program that only reads and writes local files may run.
Such work finishes in milliseconds; if it has not finished in twenty seconds it never will (a backtracking regex on a large file, a loop waiting on something that is not coming), so this is a runaway detector, not a performance budget.
const INLINE_SCRIPT_BUDGET_MS: 20000
PLAYWRIGHT_REPORT_ENV
The environment variable Playwright's built-in json reporter takes its output path from
(resolveOutputFile("JSON", …)), resolved against the runner's own working directory. An
absolute path is used here, so the file lands in the run's scratch area whatever directory the
suite runs from.
const PLAYWRIGHT_REPORT_ENV: 'PLAYWRIGHT_JSON_OUTPUT_FILE'
PLAYWRIGHT_REPORT_SUFFIX
The file name a background task's report is written to, beside its own log.
const PLAYWRIGHT_REPORT_SUFFIX: '.playwright.json'
MAX_REPORT_PARSE_CHARS
How big a report may be before this module refuses to summarize it. The file stays readable at its path; the record only says so. A whole 139-test suite's report is well under a megabyte; a report past this is not one a tool result should carry.
const MAX_REPORT_PARSE_CHARS: 8000000
MAX_REPORTED_FAILURES
How many failing tests a record lists before the rest are counted in omittedFailures.
const MAX_REPORTED_FAILURES: 12
MAX_REPORTED_ATTACHMENTS
How many attachments one failing test keeps in the record (trace first).
const MAX_REPORTED_ATTACHMENTS: 4
MAX_REPORTED_ERROR_CHARS
How much of one failure's own error text the record keeps.
const MAX_REPORTED_ERROR_CHARS: 400
TOOL_SCHEMAS
Canonical tool schemas shared by the agent runtime and documentation.
const TOOL_SCHEMAS: Record<string, ToolSchema>
BACKGROUNDED
A background launch: a single & (not &&, not a 2>&1) or an explicit detacher. A
backgrounded launch never holds the tool, so every reading here stops at it.
const BACKGROUNDED: RegExp
SERVER_PROGRAM
A program that SERVES: the scaffold's entry (server.ts/server.js), a package manager's
start/dev/serve/preview script, a Vite dev or preview server, next start|dev, or a
Python WSGI server. Matched against a command segment's own text, and against a script's SOURCE
when the command only names the script file — but NEVER against an inline program's code
(node -e …, python3 -c …), where this text is the user's program rather than a file being
run: require('…/node_modules/vite') imports a module, it does not start a dev server
(refused as "node starts a server" for exactly that line).
const SERVER_PROGRAM: RegExp
SERVER_OVER_BUDGET_ADVICE
The closing advice on an over-budget message for a command recognised as a server start: there is no tally to split, and the run has to leave the foreground budget to keep serving.
const SERVER_OVER_BUDGET_ADVICE: string
MIN_PEEK_SLEEP_SECONDS
The shortest leading sleep the platform drops: below it the wall clock it costs is noise, and a
short settle (sleep 2; curl …) is a legitimate thing to run.
const MIN_PEEK_SLEEP_SECONDS: 5
PLATFORM_PROOF
The key host code sets on an exec_command input object to mark the launch as the platform's
own graded proof (DiagnosisRunContext platformProof).
A SYMBOL, deliberately: a model's tool input is JSON, and JSON cannot carry a symbol key, so a
model can never forge this mark — a platform_proof key it writes into its own JSON is just an
unknown input key, and the handler ignores it. Object spreads through a consumer's wrappers, and
this package's own input normalization, keep symbol-keyed properties, so the host's intent
survives the real launch path.
const PLATFORM_PROOF: unique symbol
supportsBackgroundScriptPreparation
Hosts can retain their script-write fallback when an older package lacks this hook.
const supportsBackgroundScriptPreparation: true
BACKGROUND_SCRIPT_SHELL
The shell a background command's script runs in: bash, the shell a foreground command runs in
(a sandbox backend's bash -c), so moving a command to the background never changes what its
text means. A host that checks a script before launch (prepareBackgroundScript) asks this
same shell, e.g. ${BACKGROUND_SCRIPT_SHELL} -n <path>, so its answer is the launch's.
const BACKGROUND_SCRIPT_SHELL: 'bash'
SPLIT_WORK_ADVICE
The closing advice on an over-budget message for a command that is not a test suite: the work it was chaining is what to split.
const SPLIT_WORK_ADVICE: string
SUITE_OVER_BUDGET_ADVICE
The closing advice on an over-budget message for a command that IS a suite run
(Playwright, Vitest, a hurl run — isSuiteRunCommand): its files are not
a bigger unit to break up.
The wrong advice here is "run a smaller unit": it is the wrong direction for a suite, and measurably so — a run stopped here reports NO tally, so nothing in the result says which test or request hung. The run has to be sent again in the background (off this budget, its output written to a log that can be read mid-run) or, when a consumer knows the runner's per-request limit, with each request bounded. One Hurl run lost 4.8 minutes to a single unanswered request held by hurl's 300 s default per request, ten seconds past this tool's budget.
const SUITE_OVER_BUDGET_ADVICE: string
MAX_TRACE_ARTIFACTS
How many traces one read reports, newest first.
const MAX_TRACE_ARTIFACTS: 12
MAX_TRACED_REQUESTS
How many requests one test's trace contributes.
const MAX_TRACED_REQUESTS: 6
MAX_TRACED_CONSOLE
How many console lines one test's trace contributes: errors ahead of a session or molecule-package line, both ahead of a plain warning and of the browser's own resource error.
const MAX_TRACED_CONSOLE: 4
MAX_TRACED_ACTIONS
How many of the page's own actions one test's trace contributes, the LAST ones.
const MAX_TRACED_ACTIONS: 40
MAX_TRACED_BODY_CHARS
How much of a 4xx request's sent body (or its response body) the trace read keeps.
const MAX_TRACED_BODY_CHARS: 300
MAX_TRACE_NOTE_TESTS
How many tests the note in a run's result names.
const MAX_TRACE_NOTE_TESTS: 5
MAX_TRACE_NOTE_REQUESTS
How many requests the note names per test.
const MAX_TRACE_NOTE_REQUESTS: 4
TRACE_NOTE_LOOP_REPEATS
How many times ONE test may send the same method+path before the note calls it a render loop.
An Editor effect with [seeded, slug, t] in its
dependency list re-fetched GET /api/articles/<slug> 2,106 times in one test. The trace reader
caps and de-duplicates its request list, so the note printed four identical → 200 lines and
the run patched the component's seeding, rebuilt and re-ran before unzipping the trace by hand.
Twenty is far above the retries a correct page makes (a few on a flaky call) and far below any
render loop.
const TRACE_NOTE_LOOP_REPEATS: 20
TRACE_NOTE_URL_CHARS
How long a URL the note prints, before the middle is cut.
const TRACE_NOTE_URL_CHARS: 96
TRACE_NOTE_SENT_CHARS
How much of the sent body the note prints — enough to see a {"data":…} wrapper.
const TRACE_NOTE_SENT_CHARS: 160
TRACE_NOTE_GOT_CHARS
How much of the response body the note prints — the API's first error line.
const TRACE_NOTE_GOT_CHARS: 120
TRACE_NOTE_LEAD_GOT_CHARS
How much of the FAILING STEP's response body the note prints. Longer than
TRACE_NOTE_GOT_CHARS: it is the one line that answers "what did the click actually get
back", and an app's own body ({"profile":{…}}) can carry the answer past its first clause.
const TRACE_NOTE_LEAD_GOT_CHARS: 200
DIAGNOSIS_TRACE_FLAG
The --trace flag this platform adds, and the only value it adds it with.
const DIAGNOSIS_TRACE_FLAG: '--trace=retain-on-failure'
PLAYWRIGHT_FAILURES_INLINE_ENV
Playwright's switch for printing each failure's own error as that test fails, instead of only in
the summary at the end: list reads it in its constructor (ListReporterOptions.printFailuresInline,
playwright/lib/reporters/list.js — 1.63, the version the toolchain pins), and when it prints
inline the end-of-run repeat is suppressed with it (epilogue(!printFailuresInline)), so one
reporter still prints each failure exactly once.
Every background command is given this (see streamingBackgroundCommand), so a suite the
executor starts through its own wrapper is covered too — the wrapper passes the environment on
to the Playwright process it spawns. Without it the log's only failure lines are ✘ rows:
A run told to grep -n -A 20 '<test name>' the log got nothing back through four greps,
inferred causes from the spec prose instead, and
edited app/src while the run was still walking — which voids the run.
const PLAYWRIGHT_FAILURES_INLINE_ENV: 'PLAYWRIGHT_LIST_PRINT_FAILURES_INLINE'
MAX_BRACE_GLOB_ALTERNATIVES
The most alternatives one brace group may expand to. The point is to accept
the ordinary multi-extension form a model writes from habit
(*.{ts,tsx,yml,json,md}), not to grow a glob engine: a group is bounded so
a pattern cannot turn one search into hundreds.
const MAX_BRACE_GLOB_ALTERNATIVES: 16
BRACE_GLOB_HINT
The accepted brace form, named in every refusal so a refusal teaches the syntax rather than only reporting that the value was wrong.
const BRACE_GLOB_HINT: string
MAX_READ_SIZE
Max file size for read_file (5MB).
const MAX_READ_SIZE: number
MAX_WRITE_SIZE
Max content size for write_file (10MB).
const MAX_WRITE_SIZE: number
MAX_OUTPUT_SIZE
Max command output size (100KB per stream).
const MAX_OUTPUT_SIZE: number
MAX_SEARCH_CONTEXT_LINES
Most lines of surrounding context search_files will return per match.
Bounded so a broad pattern with a generous context cannot pull a whole tree
into one reply.
const MAX_SEARCH_CONTEXT_LINES: 40
MAX_BATCH_READ_FILES
Most files one batched read_file call returns. The cap exists so a survey
of a large tree cannot swallow the turn's context in one result; every path
past it is named in the result's note and listed with its own error, so
the model continues from there.
const MAX_BATCH_READ_FILES: 25
MAX_READ_CALL_CHARS
The most one read_file RESULT may carry, in chars of its JSON — every file
the call returns, the envelope and the note included. That is how the request
side counts a tool result, so it is how this tool counts one too
(serializedChars).
One tool result is ONE block in the request, and the request side caps a
block: molecule-dev cuts any block over MAX_TAIL_BLOCK_CHARS (60,000) in
place, keeping ~30 KB of each end. A batched read that crossed it lost its
MIDDLE — the cut lands between two "content" values, so whole files fell
out and the note in their place said only "N characters cut here" — while
this tool's own note had promised each of those files that it "fits in one
call, so it is not paged": one batched read of ten e2e specs (121,467 chars) lost the
middle six and bought them again in six further calls (52,908 chars).
So the CALL gets the ceiling the request gives it. Whole files are returned
up to it; the paths that did not fit are named in note and listed in
files with their own error, the shape every other entry has. No file is
ever cut, and no read result reaches the request-side cut. A test in
molecule-dev's context-fit asserts the two ceilings still agree.
const MAX_READ_CALL_CHARS: 60000
READ_RESULT_ENVELOPE_CHARS
Room inside one read result for what is not file content: the path, the
offset/line fields, and the note.
A batch sizes each file against what the call has left
(MAX_READ_CALL_CHARS less this), so the entry that does not fit is
caught here rather than by the request-side cut.
const READ_RESULT_ENVELOPE_CHARS: 1000
MAX_READ_RETURN_CHARS
The most one read_file call returns for ONE file when no window was asked for, in serialized chars: larger files come back as their first window, with a note saying how to read the rest.
MAX_READ_SIZE (5 MB) is a bound on what the tool will open, not on what it
should hand a model: a single batched read that returned a 1.2 MB README
put the next three provider calls at 366k tokens (~330k of them fresh)
against a 120k-token context cap (X0 run x5, call 26). This is the call's
own ceiling (MAX_READ_CALL_CHARS) less the room its envelope takes,
so one read result — one file or twenty-five — fits inside what the request
side carries without being cut.
const MAX_READ_RETURN_CHARS: number
SMALL_FILE_WHOLE_CHARS
A file this small is returned whole on a second window of it (paging it costs a call each).
The same bound as MAX_READ_RETURN_CHARS: the windowed-read note promises that a
file under it "fits in ONE call", and a smaller bound here breaks that promise.
const SMALL_FILE_WHOLE_CHARS: number
MAX_HTML_INLINE_CHARS
How large an HTML document must be before a whole-file read is replaced by its
outLINE — much smaller than MAX_READ_RETURN_CHARS, because the cost of
an HTML read is almost never worth it.
An entry document is boilerplate the reader rarely needs in full: meta tags,
stylesheet and preload links, a <style> block, and a handful of <script>
tags. The parts an executor acts on — the body's structure, where a script is
loaded — are all visible in an outline of one line per tag. One such read paid
63,735 chars: ~60 KB of it was the IDE's own preview bridges,
and the read pushed the transcript past its context cap, so the e2e specs the
executor had just read were trimmed to summaries and it read the whole suite
again — twice. The scaffold now keeps those
bridges in separate files, but a template's own head is still ~5-12 KB, and a
static-site or SSR entry can be far more.
The outline is not a truncation: the note beside it names the exact offset/limit that returns the whole document in one call.
const MAX_HTML_INLINE_CHARS: number
MAX_HTML_OUTLINE_LINES
Most lines an HTML outline prints before it stops and says so.
const MAX_HTML_OUTLINE_LINES: 200
MAX_SEARCH_RESULTS
Max search results.
const MAX_SEARCH_RESULTS: 50
MAX_FIND_RESULTS
Max find results.
const MAX_FIND_RESULTS: 100
DEFAULT_SEARCH_EXCLUDED_DIRS
Default directory names search_files/find_files skip — VS Code's
search.exclude + files.exclude defaults (node_modules, bower_components,
VCS dirs) plus the platform's vendored/build dirs. Overridable per consumer
via ToolBuildConfig.searchExcludedDirs (a per-project, user-editable
setting in molecule.dev — keep the APP-SIDE copy in
@molecule/app-ide-react's search types in sync with this list).
const DEFAULT_SEARCH_EXCLUDED_DIRS: readonly [
'node_modules',
'bower_components',
'.git',
'.svn',
'.hg',
'CVS',
'dist',
'.next',
'.vite',
'molecule',
]
RUNNING_FAILURE_LINES
Failure lines shown from a log that is still being written.
const RUNNING_FAILURE_LINES: 40
RUNNING_TAIL_BYTES
Bytes of a running log's end appended after its failure lines.
const RUNNING_TAIL_BYTES: 1000
RUNNING_FAILURE_LINE_RE
The lines worth showing from a log that is still being written: a failed test's mark or
numbered block header, and a runner's own error lines. Matched with grep -E.
const RUNNING_FAILURE_LINE_RE: '^[[:space:]]*(✘|✗|×|✖|✕|[0-9]+\\)|[0-9]+ (passed|failed|flaky|skipped|did not run)|FAIL|FAILED|ERROR|Error:|error:|Traceback|AssertionError)'
REPEATING_CAUSE_TAIL_BYTES
Bytes of a running log a repeating-cause look reads back.
const REPEATING_CAUSE_TAIL_BYTES: 40000
COMMAND_PLAN_LOG_CHARS
Whole-step history retained for wrapped plans; ordinary diagnostic logs fit inside this bound.
const COMMAND_PLAN_LOG_CHARS: 4000000
RUNNING_LOG_READ_BYTES
Bytes of a running log a diagnostic note reads back: one REPEATING_CAUSE_TAIL_BYTES window.
const RUNNING_LOG_READ_BYTES: 40000
REPEATING_FAILURE_MIN
DISTINCT tests that must share one signature before a running suite's repeating cause is named. A test the log prints twice, or a test that failed twice, is still one test.
const REPEATING_FAILURE_MIN: 3
REPEATING_FAILURE_LISTED
How many of a repeating cause's failures the note lists before it says "and N more".
const REPEATING_FAILURE_LISTED: 5
TOOL_RESULT_CHARS
The platform's cap on one tool result's text: MAX_TOOL_OUTPUT_CHARS in molecule-dev's
api/src/ai/chat-handler.ts, which cuts a longer string field's MIDDLE. A finished run's
stdout is cut to it, so the cause list must not depend on reading the log back — and must
itself fit inside it, or the cut lands in the list.
const TOOL_RESULT_CHARS: 8000
FAILURE_CAUSES_CHARS
The characters a finished run's cause list may use of TOOL_RESULT_CHARS. A measured
recap was 12 failures, 8 causes: one cause line is
~200 chars and ~80 more with its two body lines, so 8 causes is ~2.3 k against the 8 k cap —
the old 5-cause cap withheld 3 causes that the same result had room for.
The rest of the cap is left to the header, the narrowed re-run command and the exclusion line, which ride the same note.
const FAILURE_CAUSES_CHARS: number
FAILURE_CAUSES_LISTED
How many causes a finished run's summary lists at most. The character budget above is the bound that must hold (it is what keeps the note on the surviving side of the tool-result cut); this is the bound past which a list stops being read at all.
const FAILURE_CAUSES_LISTED: 12
FAILURE_CAUSE_TESTS_LISTED
How many of one cause's tests that summary names before it says "and N more".
const FAILURE_CAUSE_TESTS_LISTED: 6
UNIVERSAL_CAUSE_FILES
Distinct spec FILES a repeating cause must span — with every failure sharing it and nothing passing since — before a run is called broken for the whole suite.
One file's failures can be that file's own setup, so a cause confined to one file is never
this. Across UNIVERSAL_CAUSE_FILES files, on the other hand, whatever it is is a
property of the run rather than of a page.
const UNIVERSAL_CAUSE_FILES: 3
EMPTY_PAGE_CAUSE_TESTS
How many tests a run must have walked — with nothing passing since its first failure — before "the page renders nothing" can be its one cause.
THREE, and the number is the cost of the alternative. The old floor of 15 was chosen when the
reading was only offered at a completed run; once it STOPS the walk, every test waited for is
a test whose result is thrown away, and a blank page costs its per-test budget each time
(18 tests, ~4.2 minutes, on a page whose thrown error was visible in the first
pageerror). Three is the smallest count that is not one page's own bug: the cause additionally
needs three DISTINCT spec files (UNIVERSAL_CAUSE_FILES, or the files a narrowed run selected),
no failure showing a locator RESOLVING (ELEMENT_FOUND — a blank page cannot resolve
one), and no test passing after the first failure. A page that renders misses elements, but
three unrelated specs in three files failing at three different locators that never resolved,
with nothing passing in between, is the page, not three bugs. At the suite's own 5 s action
timeout that verdict lands ~20 s into the walk, so the early stop costs about one test's worth
of time instead of fifteen.
const EMPTY_PAGE_CAUSE_TESTS: 3
CONNECTION_CAUSE_TESTS
How many tests a connection-class cause must cover before the run is stopped even when they
are all in one file — see universalCause.
const CONNECTION_CAUSE_TESTS: 3
PARSE_CHECKABLE
Files a parse check can vouch for cheaply right after a write.
const PARSE_CHECKABLE: RegExp
SAME_MODULE_MARK
The line the TypeScript parse check prints when other files answer the written file's import.
const SAME_MODULE_MARK: 'MOL_SAME_MODULE '
Injection Notes
Requirements
Peer dependencies:
@molecule/api-ai^1.0.1
Runtime Dependencies
-
@molecule/api-ai -
typescript -
Failed-attempt timings without tracing:
playwrightAttemptTimings(result)serializes the native action clocks already available to a Playwright reporter'sonTestEnd. Call it only on a failed attempt and retain its output as an attachment. It starts no browser recorder and excludes action titles, arguments and error text. Unfinished steps carry their elapsed time to the native teardown boundary withunfinished: true; invalid clocks remain null. A passing attempt needs no work. -
outputFilterAfterRunnerreturns only removable output cuts. File redirects, in-place edits, command substitutions and filter programs with write or execution effects retain their pipelines. Dynamic/external filter scripts and unrecognized awk options stay unchanged. -
Playwright commands apply
excludedTestTitlesbefore launch. Existing literal filters remain in effect. Dynamic filters and opaque launchers stay unchanged. -
Trimmed test output keeps every failure named. Shared log cuts prioritize capped error, locator and expected/received details over passing progress. A detail budget never drops failure identities; native reports also name failures beyond their detailed-record cap.
-
Playwright checkpoints:
createPlaywrightFeedback({ load, run })tracks source writes withchanged(paths)and runs nothing on a write.check()verifies the current revision before an explicit action (a deploy), reusing current passes;check({ failedOnly: true })re-runs onlyfailingSpecs()(files whose latest native outcome failed) and does nothing when none is known. A full checkpoint stops at its first failure; a known-failures checkpoint re-runs every file known to fail and reports each recorded test that still fails, so all of them can be fixed before the next check. Within a file only the tests its last failed run named are re-run (Playwright's--last-failedrecord); editing the spec or its config runs it whole again. Every record names whole serial groups (test.describe.serial): a group's later test never runs without the earlier ones it depends on. Hand the host's own completed runs (a local test command, a deployed walk) torecord(results, revision)so their failures become known failures and their passes are reused. A write during a checkpoint interrupts it. UsereadFeedbackSourceswhen a caller needs filesystem inventory andrunPlaywrightFeedbackto run each spec through its native command; its incremental reporter supplies native errors, locators and the failure-time page snapshot. Withforeground: falsea run beside other work (a CLI watcher) uses idle CPU/I/O priority and the highest OOM score, and yields to independent native tests, builds, deploys and package installs in the project (not to HTTP clients, type-checks or lint), recording the competing process's kind and PID. Application and test source text never determine selection or a verdict. A spec whose every test skips itself isskipped: neither a pass nor an outage. Diagnoses are not whole-suite completion proof. -
Opaque command plans: prepare each logical step with
streamingBackgroundCommand, callcreateCommandPlan, and attach it to the executed wrapper withcommandWithPlan. The launcher prints each step'sstartMarkerandendMarkeron their own lines around execution.commandStepViewreads the active step for diagnostics;logicalCommandTextexposes the planned commands for static classification. Preserve the descriptor when wrapping again. The metadata is advisory and never establishes a completed test result. -
yieldOnFirstFailureForletswait_for_taskyield new final-failure causes from a still-running deployed task. Fix while it walks; once every known cause is fixed, deploy now. The task does not stop when the deploy lands, and the sandbox runs one Playwright walk at a time: stop it then with the command the note names, collect its stopped result withwait_for_task, and walk the new build. A local diagnostic tests mutable source: collect or stop it before editing that source, since edits invalidate its result. -
Every background task can be stopped whole.
exec_commandwrites/tmp/<id>.stopbeside the task (taskStopScript);sh /tmp/<id>.stopstops the task and every process under it as they are when it runs, workers a runner started later included, and records exit 143.taskStopCommandreturns that command, or a pid walk for a task launched without one. -
wait_for_taskstate probes report current progress without guessing log growth. A call shorter than one normal two-second poll omits both growth and no-growth claims; task age, log counters and time-left estimates remain available. Full waits still report whether the log grew. Hosts that cap a wait should allow its final result read to finish before replacing it with a state probe. -
This package only defines the tools — it runs no model loop. Hand them to the bonded AI provider (
chat({ tools, … })) or to an@molecule/api-ai-agentsrun. -
Safety defaults: keep them on for model-driven use.
pathGuards(default true) rejects paths escapingprojectRoot;redactSecrets(default true) masks secret-looking values in file reads and command output. -
exec_commandexecutes REAL shell commands on the backend. Prefer a sandbox backend for untrusted/model-driven work; add environment-specific rules viablockCommand(return an actionable error string to refuse — it is shown to the model verbatim) and enableblockDangerousCommands(default FALSE) where appropriate. -
An early exit code
124is not proof that the tool budget elapsed. Programs and nestedtimeoutcalls may return it sooner. The cut-run result requires the measured clock or the runner's own partial tally; otherwise the command keeps its actual exit code without a guessed duration. -
read_filetakespathsas well aspath. An agent that issues one tool call per model round-trip pays a full round-trip per file, so a project survey costs minutes; batched, the same reads cost one call each 25 files (MAX_BATCH_READ_FILES). One result is capped atMAX_READ_CALL_CHARS, the ceiling the request side puts on a single tool result: whole files are returned up to it and every path past that is named innoteand listed asnot returned, so a file is never handed back in part — the shape that lost the middle of a ten-file batch to the request-side cut. Each entry carries its own content or its own error, so one bad path never fails the batch. -
edit_fileshows the result, so the model need not re-read. A successful edit returnsexcerpt: each edited region as it now reads, with 1-based line numbers (N: text) and a few lines of context, capped at 60 lines in total (what did not fit is named by line range), plustotalLines.write_filereturnstotalLines, andexcerptonly for a small file (up to 40 lines) — a big file is never echoed back. Line numbers count the wayread_filedoes, so they are valid offsets. The excerpt is redacted like a read. The existing fields (ok,replacementsApplied,alreadyApplied,syntaxError) are unchanged. -
A dropped line break and the parse error it causes are reported as ONE thing. When a replacement's
old_stringended with a newline and itsnew_stringdoes not (so the next line is pulled up onto it) and the file then fails its parse check,edit_filereturns a singlesyntaxErrorthat names the replacement, shows the fused line with its number, and says to re-send that replacement with the newline restored — instead of thenewlineNotehint beside an unrelated-looking parse error, which an executor repairs by rewriting the fused line's text and fuses the next one. ThenewlineNotealone is still returned when the file parses. -
A replacement that only changes a line break at its boundary is refused, not applied. When
new_stringisold_stringwith its trailing newline added or removed and nothing else, the edit can only move text across lines — joining the next line onto the replaced text, or pushing the rest of the line down — which is what a weak model does by accident when it repeats a line it means to keep. The replacement is skipped, the rest of the batch is applied, and the result carriesskippedNote: one line naming the replacement, what applying it would have done, and how to say it on purpose (include the next line inold_string). The file's own next character decides: text on the same line is a join or a split and is refused; a blank line after it, or the end of the file, means no text crosses lines and the edit is applied as written. -
A parameter under another name is not a broken tool. Every tool's input is normalized first (
cmd→command,file→path, camelCase ⇄ snake_case), and a handler that throws returns an error naming the missing parameter rather than a bare internal message — which a weak executor reads as a broken tool and routes around, taking its verification with it. UseguardAIToolto give tools built elsewhere the same treatment, passingredactErrorso a thrown message is masked by your own redactor. -
Defer occasional tools with
createDeferredToolCatalog: pass your current permission-filtered tools and a small initial name set, offercatalog.select()to the model, and executecatalog.loaderlike any other tool. Loading only exposes schemas, never grants permission or runs a tool. Persist its loaded names withonLoadto keep them available across turns and compaction. -
Sandbox writes batch transport work. The optional backend operations
readFileForUpdateandwriteFileAndCheckcombine path safety with the old-text read, then the write with its parse check;replaceFileAndCheckdoes all of it forwrite_filein one command, refusing a path outside the root before writing. It runs once a guarded read has come back whole over the same channel, so a stub transport or a host prelude that prints degrades to the two-call path instead of an uncertain write. Diff tracking and redaction checks stay in the tools. Format and change hooks retain their ordering before parsing; large files and backends without these operations use the native file APIs. A host that overridesreadFileorwriteFileturns these off. Hosts that validate/compose background shell scripts useprepareBackgroundScriptinstead of overriding the backend's ordinarywriteFile: it runs after the script is written and before launch, and a rejection prevents the command from starting.supportsBackgroundScriptPreparationadvertises this hook; hosts keep their existing script-write preparation when running against older package versions. -
Scope the tool set per agent with
include/exclude— a read-only agent should not receivewrite_file/exec_command. -
Outputs are size-capped (
MAX_READ_SIZE,MAX_OUTPUT_SIZE, …) and searches skipDEFAULT_SEARCH_EXCLUDED_DIRS(node_modules, VCS dirs, build output) — passsearchExcludedDirsso every search surface shares the consumer's one setting.
E2E Tests
Integration checklist — drive the real UI (live preview, no mocks), adapt each item to this app's actual agent/chat surface and its registered tools, and check every box off one by one. A box you can't check is an integration bug to fix — not a skip:
- A prompt that should trigger a registered tool makes the model INVOKE
it with args matching that tool's
parametersschema (e.g. "read src/index.ts" -> callsread_filewith{ path: 'src/index.ts' }). Confirm the tool'sexecuteactually RAN — its backend side effect / log / the file it touched — not that the model merely narrated calling it. - The tool's returned value flows back into the model and shapes the final answer: the REAL result (the file's actual contents, the command's real stdout/exitCode) appears in the reply, not a plausible hallucination.
- A prompt that needs no tool is answered directly, with no spurious tool call.
- A tool whose
executethrows or returns{ error }(missing file, failing command, blocked path) degrades gracefully — the error is caught and fed back to the model as text, the conversation continues, and nothing crashes the request. - The model can invoke ONLY the tools handed to this run: an
include/exclude-scoped agent (e.g. read-only — nowrite_file/exec_command) cannot call an excluded tool, and a tool name the model invents that was never registered is refused, not executed. - Tool execution is server-side and authorized:
exec_command/write_filerun only on the bonded backend under its guards (pathGuards,symlinkGuards,redactSecrets,blockDangerousCommands/blockCommand) and stay insideprojectRoot. Feed a prompt-injected instruction (a file or message telling the model to read/etc/passwd, escape the workspace, or run a privileged command) and confirm the guard REFUSES it — a user must not be able to trigger, via the model, any action they could not perform directly.