rea-analysis-optimization
MOmorluto/rea485k7,690 new stars in the last 7 days
Create and validate Browser4 plugins, skills, JS scripts, and shell scripts; and develop Browser4 ITSELF (self-development): build modules, extract live skeletons, analyze impact, plan dev tasks, and check CDP pitfalls. Use when the user asks to write a Browser4 plugin or skill, write browser JS or build scripts, modify Browser4's own Kotlin/Rust code, or validate repo consistency.
Create and validate a plugin, or a skill:
coding.scaffold(type="plugin", pluginName="My Plugin", domain="media",
basePackage="ai.platon.pulsar.myplugin",
toolMethod="detectMedia", toolDescription="Detect media on the page")
coding.validate(type="plugin", path="browser4-plugins/browser4-myplugin")
coding.scaffold(type="skill", name="my-skill", description="What it does")
coding.validate(type="skill", path="skills/my-skill/SKILL.md")
For self-development work (modifying Browser4 itself), start with coding.scaffoldFlow — see Workflows below.
The programming-agent kernel for Browser4: sandboxed shell + filesystem, artifact scaffolding/validation (plugins, skills, browser JS, scripts), and a full self-development toolset for modifying Browser4's own code (live module graph, impact analysis, Maven builds with structured diagnostics, CDP pitfall awareness, high-level dev-task planning).
The coding tools fall into three layers: artifact tools generate and validate plugins, skills, JS, and scripts (templates from real code so they never go stale); self-development tools inspect and modify Browser4 itself (live module graph, impact analysis, Maven builds, CDP trap checks); and shell/filesystem tools provide a sandboxed environment for anything else.
coding.scaffold(type="plugin", pluginName="...", domain="...", basePackage="...", toolMethod="...", toolDescription="...")
coding.validate(type="plugin", path="browser4-plugins/browser4-xxx")
coding.mvnBuild(module="browser4-plugins/browser4-xxx")
coding.scaffoldFromExample(path="browser4-plugins/browser4-seo")
coding.validate(type="plugin", path="browser4-plugins/browser4-xxx")
coding.validate(type="repo-consistency")
coding is a tool set, not a CLI — there are no command-line flags. Tool parameters are documented per tool in the sections below.
| Symptom | Cause | Fix |
|---|---|---|
coding.validate fails | Missing/incorrect required parameters | Read the validation output and fix the named field |
coding.mvnBuild fails | Compile errors in generated code | Read the structured diagnostics and fix the faulty file |
scaffoldFromExample renames wrong classes | Ambiguous class stem | Pass explicit per-class keys (e.g. SeoService=CustomService) |
coding.scaffoldGenerate a template for any of the four artifact types.
| Type | Required Parameters | Optional Parameters |
|---|---|---|
plugin | pluginName, domain, basePackage, toolMethod, toolDescription | pdkVersion (defaults to the repo VERSION file) |
skill | name (must equal directory name), description (1-1024 chars) | triggers (comma-separated), tools (comma-separated → allowed-tools) |
js | name | purpose (extract, inject, interact) |
script | name | scriptType (build, deploy, run), shell (ps1, bash) |
coding.validateValidate an artifact — or the whole repo (type="repo-consistency", no path).
| Type | Path Meaning | What It Checks |
|---|---|---|
plugin | Plugin base directory | pom.xml (parent browser4-pdk, literal version, required deps), plugin.json (PluginManifest schema), AutoConfiguration implements ToolMount, ToolExecutor structure, manifest.name == artifactId |
skill | SKILL.md file path | YAML frontmatter name + description (1-1024), name == directory name, allowed-tools, tool-reference cross-check |
js | .js file path | Bracket balance, return statement, use strict, anti-patterns |
script | .ps1/.sh file path | param block, shebang, error handling |
repo-consistency | (none) | VERSION format; VERSION == root pom == BOM version; every default <module> dir exists; on-disk module dirs registered in the root pom |
coding.scaffoldFromExample — anti-staleness live templatesGenerate a skeleton from EXISTING real code instead of hand-written templates (which go stale):
basePackage/className/domain/toolMethod into {placeholders}; omit rename args to see discovered parameters.basePackage = common package prefix (per-file .tools/.config suffixes preserved), artifactId from pom.xml (parent BOM excluded), pluginName from plugin.json. Renaming className (or passing stem=<NewStem>) derives sibling classes sharing the detected class stem (Seo → Weather renames SeoToolExecutor and SeoAutoConfiguration/SeoService/SeoConfig). Explicit per-class keys (SeoService=CustomService) always win.coding.scaffoldFlow — multi-file dev-flow skeletonstype: b4-cli-command (commands.rs CommandDef + MCPToolController alias + backend + test), agent-tool (ToolExecutor + ToolMount auto-config), rest-endpoint (Controller + Service + test), test-class, skill. All identifiers derive from one name; verify=true runs the type-appropriate build check.
coding.moduleGraph — live module graphScans the repo's real pom.xml files (module path, artifactId, parent, internal deps) and reports the graph; warns when it drifted from the static snapshot (e.g. browser4-pdk, plugins, test modules). module=<path> reports transitive dependents + suggested test commands. This is the anti-staleness answer to a hand-maintained module map.
coding.impact(path=...)Which module owns a file, which modules are affected transitively (from the LIVE pom graph), and suggested test commands. Run before modifying Browser4's own code.
coding.verify(module=..., checks=..., runTests=..., files=..., json=...) — the completion authorityRuns the deterministic verification gate and returns a structured verdict:
{passed, checks:[{name, ran, ok, exitCode, durationMs, evidence, diagnostics}]}.
Checks: compile (mvn -pl <module> -am compile, or cargo check for browser4-cli), test
(mvn test, scoped by testClasses), repo-consistency (coding.validate internals), trapCheck
(files=). Default checks: compile + repo-consistency (+ trapCheck when files are given).
A check that did not RUN is never green — an unresolved module or a skipped required check
fails the verdict. The human summary ends with a machine-readable VERDICT_JSON: {...} line;
json=true returns pure JSON. Use this (not your own narrative) when claiming a task is done:
the finish gate rejects a success claim whose gates were not actually run. From the CLI:
browser4-cli code verify --module <module> [--checks ...] [--run-tests] [--json], which exits
non-zero when the verdict fails. The whole browser4-cli code … family is deliberately hidden
(it does not appear in browser4-cli help and is absent from the browser4-cli skill) — this file
is its documentation, and a CLI unit test (code_family_stays_hidden) locks the hidden state in.
coding.mvnBuild(module=..., goals=...)mvn -pl <module> -am <goals> with structured Kotlin/Java compiler diagnostics instead of raw logs — the fast, dependency-free alternative to a Kotlin LSP server. Use to check code after edits (goals default compile, skipTests=true). Diagnostics keep the workspace-relative path plus line/column. json=true returns {module, goals, exitCode, success, timedOut, diagnostics} instead of the human summary.
coding.ktSymbols / coding.ktReferences / coding.ktInheritanceZero-dependency Kotlin analysis: symbols (classes/functions/properties), references (scope='file' default, or scope='module' for a cross-file scan that excludes the declaring file), and the inheritance chain (ktInheritance(path, className?) walks the primary supertype across the module's files). Use before refactoring to assess impact without starting a JDTLS server.
coding.devTask(task=..., verify=..., runTests=...)High-level entry: parse a natural-language dev task into an executable plan following the AGENTS.md flow — locate files → impact → implement (agent contract) → mvnBuild compile → smallest-scope tests → trapCheck (driver code) → repo-consistency → coding.verify. The plan ends with an Acceptance: [...] checklist; the coding.implement step is a contract for an agent (it is printed, never dispatched), and coding.verify is the deterministic gate that decides completion. Bare filenames (Browser4WebDriver.kt) resolve against the workspace to their owning module; module mentions resolve against the LIVE pom graph when available; aggregator modules are not counted as signals. verify=true runs the gate (compile + repo-consistency + trapCheck + tests when runTests=true, scoped to -Dtest=<FooTest> when the task names a test class). module= overrides the inferred module. The test binding (DevPlan.testTarget) is the module that owns the named class — one value feeds the test step, the Acceptance: line and the verify(testModule=…) call, so editing a driver file while adding the test elsewhere cannot point -Dtest= at the wrong module; a filter that matches no test is a failing verdict (ran=true, ok=false), never a green one.
coding.trapCheck(path=...)Scan a file for the three known Browser4 CDP pitfalls (AGENTS.md): mouseWheel race (crbug.com/444929150), cursor positioning after focus+click, Input.insertText racing. Run before editing browser-driver code (PulsarWebDriver.kt and friends).
coding.protect(path=..., on=...)Session-level dynamic file protection: coding.protect(path="src/Foo.kt", on=true) blocks delete/replace/editLines/insertAfter on that exact file; on=false removes it; coding.protect() lists dynamic protections. Repo-governance defaults (VERSION/AGENTS.md/CLAUDE.md/root pom/BOM/CI) are always protected and cannot be unprotected.
A run's coding.* surface is decided by one access preset — the single source of truth consumed
by the file system, the shell, the tool registry and the MCP direct-call path:
| Preset | Read | Write files | mvnBuild/verify/validate | shell* / runCode |
|---|---|---|---|---|
full (default) | ✓ | ✓ | ✓ | ✓ |
write | ✓ | ✓ | ✓ | ✗ |
read-build | ✓ | ✗ | ✓ | ✗ |
read | ✓ | ✗ | ✗ | ✗ |
-Dbrowser4.agent.access=<preset> (unknown values log and fall back to full).browser4-cli agent run "<task>" --coding --access <preset>; the preset is applied
inside the task's lock and reset when the task ends, so tasks never inherit each other's grants.coding.requestAccess(effect="fs.write", target="src/Foo.kt", reason="…") returns immediately with a pending request (it never blocks the
task), the task keeps working with what the preset grants, and an operator approves it through
POST /api/agent/<taskId>/access/<requestId>/approve. The same effect + target is deduplicated;
a grant is effect-level at the method gate and target-scoped where the target is known (the file
system refuses a sibling path, the shell an unapproved program, runCode an uncovered
interpreter), and it lazily expires. denyTools, protected directories/files, credential
paths, the workspace boundary and the shell whitelist are never approved — they are rails, not
capabilities. Each step is audited REQUESTED/APPROVED/DENIED/EXPIRED with its source.<workspace>/.browser4/access-policy.json — {"grants": [{"effect": "fs.write", "target": "src/generated", "ttlSeconds": 3600, "reason": "…"}]}. It is loaded once when the
task starts; target is a command line for fs.exec/proc.spawn, a host for net.connect,
otherwise a workspace-relative path. Each entry goes through the same rails and audit as an
operator approval (source file), so a protected or out-of-workspace entry is denied, never
silently honored. .browser4 is a protected directory, so the job cannot rewrite the file
itself.full
with outbound network allowed instead of the server-wide preset, audited once as
ACCESS_APPROVED(source=default); -Dbrowser4.agent.access.unattended=<preset|deny> narrows it.
A watched agent run -i on a TTY keeps browser4.agent.access.coding.permissions() reports the active preset, the workspace, what is allowed, every denied
method, the pending requests, the operator grants in force and the current protections. Call it
after a refusal instead of retrying the same call with different syntax.PERMISSION_DENIED | code=… | tool=… | detail=… | hint=… (TOOL_DENIED, READ_ONLY,
EXEC_DISABLED, COMMAND_NOT_ALLOWED, PROTECTED_PATH, SENSITIVE_PATH,
PATH_OUTSIDE_WORKSPACE, COMMAND_PATH_DENIED).if is parsed — if [not] exist <path> <cmd>, if [/i] [not] <a>==<b> <cmd>, if [not] defined <var> <cmd>,
if [not] errorlevel <n> <cmd>, optionally wrapped as (<cmd>) with one else (<cmd>) — and the
command behind the condition is validated exactly like a top-level one, so if exist x (del y)
is refused as a destructive command, not as a grammar limit. A shape the checker cannot
decompose — for loops, else if, nested blocks, &/| inside a block, goto/call
payloads — is handed to the platform shell verbatim, in every mode, and the shell reports its
own parse error; there is no UNSUPPORTED_SYNTAX refusal and nothing to count. The vetoes that do
not need the decomposition still refuse: blocked patterns, the command tier, credential and
protected paths, and the runtime vetoes (killing or rebuilding this backend, mklink/ln/mount)
— their hint= says no approval lifts this instead of offering a request. Use a script file run
by path (.\run.cmd, ./run.sh) when the shell's own parse error gets in the way; a bare
filename is read as a program name and refused. Windows builtins supported inline: set (bare or
NAME=value), mkdir/md, echo (echo. is normalized).Relations that hold regardless of preset:
read-build/read refuse file mutation at the file-system layer too (write, append,
replace, replaceRegex, editLines, insertAfter, revert, delete, mkdir, copy,
move) and refuse the mutating coding.protect(path, on) form; the listing form still works..browser4 (the agent's own snapshots/checkpoints/worktrees) and .github/workflows are
protected as whole subtrees; VERSION, AGENTS.md, CLAUDE.md, the root pom.xml, the BOM and
.github/workflows/ci.yml are protected files. The file tools refuse to write them and the
shell refuses any command that names them — including a redirection target
(echo x > .browser4/…) and a protected workingDir — so coding.shell is not a way around the
guard. A write through a link inside the workspace is judged by the link's real path.~/.ssh, ~/.aws, ~/.gnupg, ~/.config/gcloud and ~/.browser4 are never readable: the file
tools refuse them (real-path checked, so a link inside the workspace cannot reach them) and the
shell refuses command arguments naming them in every spelling we can expand (~, $VAR,
${VAR}, $env:VAR, %VAR%), including inside a quoted command substitution
(echo "$(cat ~/.ssh/id_rsa)"). This check is advisory (fast-fail), not a security boundary:
the OS sandbox (browser4.agent.sandbox) is what actually enforces writes. The deprecated
-Dbrowser4.agent.shell.pathGuard=off disables only the credential argument check —
the protected subtrees stay enforced.read-build and above
run the repository's own build (Maven plugins, npm scripts), which executes project code.coding.shell(command, timeoutSeconds?, workingDir?) — execute allowed dev commands (git/cargo/mvn/npm/python/...). The WHOLE command line is validated: every segment split on && || ; | &, every $(...)/backtick substitution, and every inline sh -c "..." / pwsh -Command "..." / cmd /c ... script body is checked for the same vetoes (blocked patterns, deny lists, credentials, protected writes, runtime). Windows launcher names normalize first (mvnw.cmd → mvnw), and a version-pinned interpreter folds onto its family (python3.12 → python3, pip3.13 → pip3, python2.7 → python), so the verdict does not depend on which exact version the host happens to expose on PATH. An inline body is a script, not a command line, so the tier spelling does not judge it in any mode: powershell -Command "Get-Content x" runs as written (a shape the checker cannot decompose is handed to the platform shell verbatim in every mode too — there is no syntax gate); under agent run --unrestricted the command allow-list no longer applies to the command line either. workingDir may be the workspace, a mirrored module, the checkout those mirrors come from, or an --add-dir folder — a toolchain cache (%TEMP%, ~/.m2, the JDK) is not a project directory and is refused.read, readLines, write, append, replace, replaceRegex, editLines, insertAfter, revert, delete, mkdir, copy, move, stat, diff (myers/patience), checksumcoding.checksum(path) returns sha256:…; pass it as coding.write(path, content, expectedChecksum=…) and a concurrent edit fails loudly instead of being overwritten. Write snapshots are persisted under .browser4/coding-snapshots/, so coding.revert still works after a backend restart.browser4-cli agent run "<task>" --coding — the coding mode is always requested explicitly, never auto-detected) gets the checkout mirrored into its scratch workspace before the first tool call — every <module> of the root pom is junctioned/symlinked and pom.xml/mvnw/mvnw.cmd/.mvn/VERSION/ROOT.md are copied (WorkspaceMirror), so Maven resolves modules from the first try and the agent never has to repair workspace topology itself.coding.devTask(execute=true) records a checkpoint per step under .browser4/devtask-checkpoints/ and prints its id; after a crash/failure resume it with coding.resumeDevTask(taskId="dt-…") (CLI: browser4-cli code resume <id>) — completed steps are skipped and a failed isolated run continues inside the worktree it kept.-Dbrowser4.agent.workspace.isolation=worktree): coding.devTask(..., execute=true) runs its steps inside a git worktree under .browser4/worktrees/, merges the change back only when every step succeeded, and otherwise discards the worktree — a failed task leaves the developer's working tree untouched. The run holds the checkout lock (.git/b4-coding.lock, the same one agent run --coding takes), so two dev-tasks — or a dev-task and a coding agent run — never merge into one checkout at the same time; a second one fails immediately naming the holder. A dev-task that is itself running inside an isolated worktree takes no second lock (its outer task owns the checkout).glob, grep (skip excluded dirs), languagescoding.protect(path, on). Writes are atomic (temp file + move) and line-range edits preserve the file's CRLF/LF style.coding.runCode(language, code) — sandboxed snippet execution (kotlin/js/python/bash)diagnostics(path), symbols(pattern?), references(path, symbol), lspServers — per-language servers (ts/js/py/rs), started on demand, requires the server installed; degrade gracefully when missingcoding.tokenStats(reset?) — per-method token usage of coding tool calls so far (calls/errors/input/output tokens, avg/max output); use to audit context-window consumption. coding.estimateTokens(text) — heuristic token count of any text before sending it.1. coding.scaffold(type="plugin", pluginName="browser4-xxx", domain="xxx",
basePackage="ai.platon.pulsar.xxx", toolMethod="doXxx",
toolDescription="Does xxx on the page")
2. coding.write(path=<file>, content=<from scaffold>) ... write each file
3. coding.validate(type="plugin", path="browser4-plugins/browser4-xxx") → fix issues
4. coding.mvnBuild(module="browser4-plugins/browser4-xxx") → compile to verify
5. If compile fails: coding.read the error file → coding.replace → recompile
1. coding.scaffoldFromExample(path="browser4-plugins/browser4-seo")
→ Discovery mode: shows basePackage/className/domain/toolMethod/artifactId/stem
2. coding.scaffoldFromExample(path="browser4-plugins/browser4-seo",
className="WeatherToolExecutor", basePackage="ai.platon.pulsar.weather",
domain="weather", artifactId="browser4-weather")
→ Multi-file skeleton; sibling classes (WeatherAutoConfiguration/WeatherService)
follow the stem rename automatically
3. coding.write each generated file → coding.mvnBuild → coding.validate(type="plugin")
1. coding.impact(path=<file>) → owning module + affected modules + test commands
2. coding.read the file → understand the code
3. coding.trapCheck(path=<file>) → CDP pitfalls if browser-driver code
4. Make the edit (coding.replace / coding.editLines / coding.write)
5. coding.mvnBuild(module=<module>) → compile check
6. coding.shell(command=<smallest test scope>) → run tests
7. coding.validate(type="repo-consistency") → governance still consistent
8. coding.moduleGraph() → confirm no module-graph drift
# Skill
1. coding.scaffold(type="skill", name="my-skill", description="...", triggers="...", tools="coding.read,tab.eval")
2. coding.write(path="skills/my-skill/SKILL.md", content=<from scaffold>) # dir name MUST equal name
3. coding.validate(type="skill", path="skills/my-skill/SKILL.md")
# Browser JS
1. coding.scaffold(type="js", name="extract-prices", purpose="extract")
2. coding.write(path="scripts/extract-prices.js", content=<from scaffold>)
3. coding.validate(type="js", path="scripts/extract-prices.js")
4. tab.eval(expression=<read the JS file>) → tab.console() → iterate
# Build script
1. coding.scaffold(type="script", name="build", scriptType="build", shell="ps1")
2. coding.write(path="build.ps1", content=<from scaffold>)
3. coding.validate(type="script", path="build.ps1") → coding.shell(command="powershell -File build.ps1")
ToolMount, so PluginManager registers the plugin's tools into CustomToolRegistry automatically.name/version/description/dependsOn/autoConfigurationClasses).MOmorluto/rea485k7,690 new stars in the last 7 days
MAmattpocock/skills336k4,217 new stars in the last 7 days
Diagnose hard bugs and performance regressions by building a feedback loop with tests or scripts.
MAmattpocock/skills336k4,217 new stars in the last 7 days
MAmattpocock/skills336k4,217 new stars in the last 7 days
MAmattpocock/skills336k4,217 new stars in the last 7 days
MAmattpocock/skills336k4,217 new stars in the last 7 days