Repository navigation
refactor(runtime): read four agents' readiness from JSON rule files through one engine - #24348
Conversation
Replays every recorded agent PTY transcript frame by frame through a real runtime pane (agent-known and agent-unknown, clocked and clockless) and a synthetic evidence matrix for all 43 TuiAgents, and compares each verdict and tui-idle wait outcome to committed run-length-encoded baselines. Refs STA-9098
A census that read TUI_IDLE_QUIESCENCE_MS would move with it; fixed 2999/3000 ms reads and a fixed 2000 ms poll step make a changed window show as changed verdicts. Refs STA-9098
…sible waits - Read each verdict through the runtime's own settle seam (evaluateTuiIdleForLeaf) instead of re-wiring evaluateTuiIdle/leafTuiIdleEvidence/buildTerminalWaitText, so the census is coupled to one runtime method, not to the module STA-9098 rewrites. - Let the runtime finish each chunk (one macrotask turn) before reading. The old read raced work chained on the paint, so 14 frames pinned a microtask-ordering artefact. - Record when a wait settles (@start vs @poll), not just its outcome. - Exit each pane's PTY after reading it so its emulator is freed. - Replace the hand-grouped families, literal fixture list and per-pane split flag with a directory-scanned catalog, one baseline per replayed pane, and size-balanced shards. - Run the synthetic matrix in one file; it takes about 2 s.
…e in the census matrix Blocked detection is position-ordered (design doc 11.5): the later of a blocker and a ready anchor wins. The matrix now paints a workspace-trust dialog after, and before, each agent's ready screen under every title, so a rule engine that loses that ordering fails per agent.
The anti-slop lint rejects Reflect.get on parsed input.
…adiness from rule files Adds agent-state-rules/: a zod-validated JSON file per agent, one priority list of screen rules per agent (idle with strength and requiresQuiet, or hold), and text anchors that feed the shared, position-ordered blocked layer every pane reads first. The three screen-ruled agents and Cursor's approval menu and prompt move to data; the Antigravity text scan stays code as a named anchor. Their old code paths are deleted. Every other agent still runs through the existing lanes, unchanged. The readiness census baselines are untouched and pass. Refs STA-9098
…rows, anchors and lanes Refs STA-9098
|
There was a problem hiding this comment.
ℹ️ No critical issues — two minor suggestions inline/body. The refactor is behavior-preserving for the four migrated agents, verified against the census and by tracing every deleted function to its replacement.
Reviewed changes
- Rule files + engine. Four agents' readiness (Antigravity, Cline, Prime Agent screen rules; Cursor text anchors) moves from per-agent TypeScript into strict-schema JSON (
agent-state-rules/*.json) compiled byagent-state-rules-engine.ts/agent-state-rule-matchers.ts. - Shared text layer. Cursor's approval menu and prompt become data anchors in
agent-state-text-anchors.ts;blocked-text-layer.tstakes the old live-window scan and prefilter. - Lane rewiring.
tui-idle-evidence.tsswapsreadScreenDecidesReadiness: booleanforreadAgentRuleVerdict: AgentStateVerdict | null, adds a weak-idle settle branch, and extractshasQuietOutput.hasScreenRulesreplacesgetScreenReadyRule. - Deletions. The old per-agent readiness files, Cursor approval detector, and inline blocked/prompt helpers are removed; no live code references them.
I independently traced each deleted predicate to its rule/engine replacement and ran two read-only specialist passes; none could produce an input where the four agents' verdicts differ, and the committed census baselines are unchanged and pass.
ℹ️ Stale evidence docs still name the deleted detectors
Two reference docs describe the removed functions as the shipped implementation, so a reader lands on symbols that no longer exist.
Technical details
# Update evidence docs to the rule-file engine
## Affected sites
- `docs/reference/cline-and-prime-agent-readiness-evidence.md:5` — names `isClineComposerReadyScreen` and `isPrimeAgentComposerReadyScreen`, both deleted; readiness now comes from `agent-state-rules/cline.json` / `prime-agent.json`.
- `docs/reference/antigravity-readiness-evidence.md:3` and `:44` — place `findAntigravityReadyPromptIndex` in `src/main/runtime/terminal-wait-detection.ts`; it is gone, and its body now lives as `findAntigravityComposerIndex` in `agent-state-rules/antigravity-text-composer.ts`, referenced by name from `antigravity.json`.
## Required outcome
- Retarget each reference to the rule file (and, for Antigravity, the named predicate) so the docs match what ships.
## Suggested approach (optional)
- Both docs already explain the tiering; only the symbol/path references need to change.
- Worth a one-line note that screen rules now live in `agent-state-rules/<agent>.json` so future agents are discoverable.
</details>
<!--
Pullfrog review metadata. These findings were written against eaa0706b99;
if commits have landed on jinwoo/agent-state-rules-engine since, treat every specific bug, file, or
line callout as POTENTIALLY STALE and re-diff before acting on it.
- Mode: Review (initial)
- Files reviewed: 31
- Commits reviewed: 2
- Base: jinwoo/readiness-census (50038b0c)
- Head: jinwoo/agent-state-rules-engine (eaa0706b)
- Reviewed commits:
- faa97a21c5 — refactor(runtime): read Antigravity, Cline, Prime Agent and Cursor readiness from rule files
- eaa0706b99 — test(runtime): cover the agent state rule engine's schema, priority, rows, anchors and lanes
- Prior pullfrog review: none
-->
<!-- PULLFROG_DIVIDER_DO_NOT_REMOVE_PLZ -->
<sup><a href="https://pullfrog.com"><picture><source media="(prefers-color-scheme: dark)" srcset="https://pullfrog.com/logos/frog-white-full-18px.png"><img src="https://pullfrog.com/logos/frog-green-full-18px.png" width="9px" height="9px" style="vertical-align: middle; " alt="Pullfrog"></picture></a> | [Fix all ➔](https://pullfrog.com/trigger/stablyai/orca/24348?action=fix&review_id=5377941346) | [Fix 👍s ➔](https://pullfrog.com/trigger/stablyai/orca/24348?action=fix-approved&review_id=5377941346) | [View workflow run](https://github.com/stablyai/orca/actions/runs/36845649333/job/110315447195) | Using `DeepSeek Flash` (free via [Pullfrog for OSS](https://pullfrog.com/for-oss)) | [𝕏](https://x.com/pullfrogai)</sup>…ting group
The load-time regex check only flagged a repeated group whose body held * + or {,
so (a?)* and (a|aa)+ passed though both backtrack exponentially. A repeated
group's body must now be fixed: no quantifier of any kind and no alternation.
The comment states the remaining polynomial gap instead of claiming linearity.
…nswer shape Every rule and text anchor is now when (a region and what it must show) plus answer, each a discriminated union, so part (b) adds title, text and status regions and working or blocked answers as new variants instead of new fields. - Cursor's prompt is two anchors answering working and idle; the one-off workingIfAfter and followedBy fields become a general after test. - Anchor literals and the probe banner must be lowercase, since they are matched against the lowercased tail. - screenProbeBanner moves under profile, the place for non-detection facts. - why is required on every rule and anchor. - A blocked anchor must name a lastOf literal, which the prefilter keys on.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Reviewed the three commits landed since the prior pullfrog review at eaa0706b99.
- Reshaped rules and anchors. Every rule and text anchor moved from a
state-discriminated object to a sharedwhen/answershape; Cursor's single prompt anchor split intoprompt_busy(answerworking) andprompt_idle(answeridle), with theliveindex spanning both andreadygated onidle. - Regex safety broadened. The load-time unsafe-pattern check now also flags a repeated group whose body varies by a quantifier or an alternation (
(a?)*,(?:a|aa)+), and the comment is narrowed to the subset actually detected (adjacent-quantifier overlaps likea*a*stay out of scope). - Evidence docs retargeted. Both readiness evidence docs now name the rule files and the named Antigravity predicate instead of the deleted per-agent detectors.
I independently traced the when/answer rewrite of the text-anchor layer and ran a read-only specialist differential over constructed tails: the blocked signal, live, and ready verdicts match the pre-refactor helpers for every input tested, not just the bundled Cursor strings. The focused unit tests (agent-state-rules-engine.test.ts, agent-state-text-anchors.test.ts) pass locally, and the prior inline note on regex safety is addressed.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
|
Navigate logical layers of code changes, visualize relationships, and explore their blast radius. No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (3)
💤 Files with no reviewable changes (1)
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review. 📝 WalkthroughWalkthroughThe change adds schema-validated agent-state rules, bundled configurations, text anchors, and shared blocked-text detection. Terminal-wait and TUI idle evaluation now use agent-rule verdicts. Probe selection and transcript tests also use the shared rules engine. The change removes several agent-specific readiness detectors and updates reference documentation. Priority: ⬇️ Low Merge Risk: ⚪ Minimal · up to No actionable merge-blocking issue remains. The readiness-rule migration is mergeable subject to normal checks. Security Architecture ReviewSecurity architecture risk: 🔵 Low · up to The checked paths retain validation, blocked-state precedence and cancellation safeguards. No new privileged access was identified, but complete behavior equivalence and exposure coverage were not established. Retained concerns Security review detailsSecurity Blast Radius
Trust Boundaries and Controls
Resilience and Maintainability Implications
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/main/runtime/agent-state-rules/agent-state-rules-schema.ts (1)
35-49: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winText-anchor
containsterms can be uppercase. They then never match.
- Text anchors run against the lowercased text tail.
- The schema rejects an uppercase
find.lastOfwithTailLiteralfor this reason. It does not apply the same check tocontainsterms insidewhen.afterandwhen.lines.test, which also read the lowercased tail.- Screen rows use the same
TextTestSchema, but screen rows are not lowercased. One check cannot cover both cases.If a rule author writes
{ "contains": "Run (once)" }in a text anchor, the file loads and the term never matches:
- In
allorany, the anchor never fires. The approval menu is then not reported as blocked.- In
none, the veto never fires. An idle anchor can then report ready when it should not.This breaks the guarantee in the file header: "a misspelled field rejects the file instead of silently dropping a condition".
Build the text-test schema from a term factory. Then use a lowercase-checked variant for anchor
afterandlines.test. A regex cannot be checked the same way, because escapes such as\Sand\Ware uppercase, so check onlycontains.♻️ Sketch
-const TextTermSchema = z.union([ - z.object({ regex: SafeRegex, ignoreCase: z.boolean().optional() }).strict(), - z.object({ contains: Literal }).strict() -]) - -const Terms = z.array(TextTermSchema).min(1).max(MAX_TERMS) - -const TextTestSchema = z.union([ - TextTermSchema, - z - .object({ all: Terms.optional(), any: Terms.optional(), none: Terms.optional() }) - .strict() - .refine((test) => Boolean(test.all ?? test.any ?? test.none), 'needs all, any or none') -]) +function textTestSchema(containsLiteral: typeof Literal) { + const term = z.union([ + z.object({ regex: SafeRegex, ignoreCase: z.boolean().optional() }).strict(), + z.object({ contains: containsLiteral }).strict() + ]) + const terms = z.array(term).min(1).max(MAX_TERMS) + return z.union([ + term, + z + .object({ all: terms.optional(), any: terms.optional(), none: terms.optional() }) + .strict() + .refine((test) => Boolean(test.all ?? test.any ?? test.none), 'needs all, any or none') + ]) +} +const TextTestSchema = textTestSchema(Literal) +// Why: anchors read the lowercased tail. +const TailTextTestSchema = textTestSchema(TailLiteral)Then use
TailTextTestSchemaforwhen.afterandwhen.lines.testinTextAnchorSchema.Also applies to: 129-151
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: a9401f57-f1c7-4bea-bddd-1552fd47782c
📒 Files selected for processing (33)
docs/reference/antigravity-readiness-evidence.mddocs/reference/cline-and-prime-agent-readiness-evidence.mdsrc/main/runtime/agent-state-rules/agent-state-rule-matchers.tssrc/main/runtime/agent-state-rules/agent-state-rule-pattern-safety.tssrc/main/runtime/agent-state-rules/agent-state-rules-catalog.tssrc/main/runtime/agent-state-rules/agent-state-rules-engine.test.tssrc/main/runtime/agent-state-rules/agent-state-rules-engine.tssrc/main/runtime/agent-state-rules/agent-state-rules-schema.tssrc/main/runtime/agent-state-rules/agent-state-text-anchors.test.tssrc/main/runtime/agent-state-rules/agent-state-text-anchors.tssrc/main/runtime/agent-state-rules/antigravity-text-composer.tssrc/main/runtime/agent-state-rules/antigravity.jsonsrc/main/runtime/agent-state-rules/blocked-text-layer.tssrc/main/runtime/agent-state-rules/cline.jsonsrc/main/runtime/agent-state-rules/cursor.jsonsrc/main/runtime/agent-state-rules/prime-agent.jsonsrc/main/runtime/antigravity-screen-readiness-transcripts.test.tssrc/main/runtime/cline-screen-readiness-transcripts.test.tssrc/main/runtime/cline-terminal-readiness.tssrc/main/runtime/codex-quiet-ready-screen.test.tssrc/main/runtime/cursor-approval-prompt-detection.tssrc/main/runtime/orca-runtime-start-tui-idle-visible-read-probe.tssrc/main/runtime/prime-agent-screen-readiness-transcripts.test.tssrc/main/runtime/prime-agent-terminal-readiness.tssrc/main/runtime/runtime-terminal-wait.tssrc/main/runtime/screen-ruled-agent-readiness.tssrc/main/runtime/screen-ruled-agent-transcript-suite.tssrc/main/runtime/terminal-tail-sentinel-index.test.tssrc/main/runtime/terminal-tail-sentinel-index.tssrc/main/runtime/terminal-wait-detection.tssrc/main/runtime/terminal-wait-tail-state.tssrc/main/runtime/tui-idle-evidence.test.tssrc/main/runtime/tui-idle-evidence.ts
💤 Files with no reviewable changes (4)
- src/main/runtime/prime-agent-terminal-readiness.ts
- src/main/runtime/cline-terminal-readiness.ts
- src/main/runtime/cursor-approval-prompt-detection.ts
- src/main/runtime/screen-ruled-agent-readiness.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.
…read the lowercased tail A text anchor's after and lines tests run on the lowercased tail, so an uppercase contains term loaded and then never matched. Build the text test schema from the literal it accepts and give anchors the lowercase one. Also drop a probe-banner early return that no bundled catalog reaches.
|
Re the review note on uppercase |
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Reviewed the one commit landed since the prior pullfrog review at a567b268e0, which closes the lowercase anchor gap CodeRabbit flagged.
- Lowercase
containsterms in text anchors.agent-state-rules-schema.tsnow builds its text-test schema from a term factory: screen rows keep the mixed-caseLiteral, while an anchor'safterandlines.testare built from the lowercase-onlyTailLiteral.find.lastOfalready usedTailLiteral, so an uppercasecontainsin a text anchor is now rejected at load instead of silently never matching.regexterms are deliberately left unchecked, since escapes like\Sare uppercase. - Dead branch removed.
showsScreenProbeBannerdrops its empty-banner early return;.someover an empty list already yieldsfalse.
I verified all bundled rule files' contains terms are already lowercase (so no file is rejected by the stricter check), ran the focused suite (44/44 pass), and pnpm tc:node is clean. The textTestSchema(...) factory typechecks because Zod 4's .refine preserves the ZodString type.
deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

Builds on the readiness census (#24336, merged), which proves this PR changes no verdict.
ELI5
Orca decides whether an agent in a terminal is "ready for input", "busy" or "waiting on a question" by reading its screen. For each agent that logic was hand-written code. This PR moves four agents' rules into small JSON files that one shared engine reads, so later agents can move the same way and the rules can be read in one place. Nothing the user sees changes.
What Changed
src/main/runtime/agent-state-rules/<agent>.jsonholds those rules, validated by a strict zod schema when the app loads (unknown fields, unknown agents, unsafe regexes are rejected). The old agent-specific functions are deleted.The mechanism:
when(a region and what it must show) plusanswer, each a closed list checked by zod. Today the only region is the trusted screen grid and the answers areidle(withstrengthstrong/weak andrequiresQuiet) andhold("the screen was readable and it is not ready, so don't fall back to weaker hints"). Later agents add the title, text and status regions and theworkingandblockedanswers as new entries in those lists, not as new kinds of field.working(spinner after the prompt) and oneidle; either proves an earlier dialog was answered, and onlyidlesettles a wait. The blocked layer (moved intoagent-state-rules/blocked-text-layer.ts) still picks the blocker painted latest, and its cheap prefilter regex is now built from the rule files' blocked anchors.antigravity-text-composer) and referenced fromantigravity.json.profile.screenProbeBannerholds the one fact that is not a detection rule: tail text that makes a wait read the visible screen once (Antigravity's banner).find.lastOfand anycontainsterm) must be lowercase or the file is rejected; screen rows keep mixed case.?, or an alternation), which is what makes backtracking exponential. Every rule and anchor carries awhy, since JSON has no comments and the rationale should travel with the pattern.evaluateTuiIdle's lane order is unchanged; the rule verdict plugs into the same three places the old screen verdict did (strong ready, quiet ready, and "screen decided, close the weak lanes"). Codex, Muse, Qoder and every other agent still run through the existing code; they can move one by one.Why
Every agent's readiness logic lived in its own code path, with ordering spread across several files. One engine with data files gives one place to read each agent's rules and makes migrating the other agents mechanical. The alternatives were to keep adding per-agent functions (more drift) or to rewrite all agents at once (no way to prove zero behaviour change). Doing four agents now, under the census, proves the engine can reproduce today's verdicts exactly before the rest move.
Linked Issue
Refs STA-9098 (part a: the engine, with no behaviour change).
Visual Proof
N/A: no UI or behaviour change. The readiness census (#24336) replays every recorded agent session and a synthetic matrix over all agents, and its committed baselines are untouched and pass.
Testing
pnpm test src/main/runtime/readiness-census: 218/218 passed, three runs, about 20 s each; no baseline file changed.Mutation check against the census (re-run after the rule shape change): Cline's
holdabove its composer rule (11 failures), Prime withoutrequiresQuiet(12), the Antigravity text anchor answeringworking(13), Cursor's idle prompt without its spinner veto (2), and countingworkinganchors as ready (2 census frames plus a unit test) all fail. Earlier: movingholdabove the composer rule (each of the three screen agents), a priority tie withholdfirst in file order, droppingrequiresQuiet(Prime), dropping Cline's spinner veto, dropping Cursor's busy spinner, and dropping the Antigravity text anchor all fail the census. Raising Cursor's choice count to 3 passes the census (no recording separates it) and is caught by a new unit test.New unit tests for the engine: schema rejections (including unsafe and safe pattern cases and uppercase anchor literals), priority and ties, hold, optional and relative rows, strength and quiet through the tui-idle ranking, text anchors, and the prefilter.
pnpm test src/main/runtime src/shared: all pass exceptomp-draft-launch-shell.test.ts(fish), which fails locally because of my own shell config and does not touch this code.pnpm tc:node, oxlint, anti-slop andpnpm run check:code-quality:changed: clean.Platforms: macOS locally; the change is platform-neutral string matching. SSH: unaffected, since detection runs on the execution host as before.
I manually tested these changes locally
Automated tests added/updated, or explained why not below
Review
Agent skill upstream boundary
docs/reference/agent-skill-sharing-upstream-boundary.mdand copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.Notes
No security, platform, SSH, mobile or wire-compatibility impact: same verdicts, same blocked reasons. Performance: rules are compiled once at load. Per evaluation, the screen is read once per agent and each anchor scan runs once, as before.
Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)