From Repeated Failures to Stable Runs: A Practical Guide to Agent Automation

    This article explains how to turn agent-assisted workflows into reliable production automation. It covers splitting interactive, data, and business layers; building a verifiable seven-stage pipeline; browser state waits and scoped locators; screenshot provenance; local vision for grid charts; executable algorithm dictionaries; engineering closed-loop fixes; local failure recovery; and a three-phase rollout.

    1. The goal of automation is not “let the model do everything”

    Logging into a business site every day, searching for specified objects, capturing hundreds of trend charts, then recognizing, computing, and aggregating them is a typical high-repetition, low-tolerance task.

    It looks like repeated clicks, but it actually has three layers:

    • Interaction: login, dismiss overlays, enter search criteria, switch pages.
    • Data: capture charts, recognize colors and symbols, recover numeric matrices.
    • Business: compute from an algorithm dictionary and produce statistics.

    If every step is left to a large model’s on-the-spot judgment, you get unstable locators, visual misreads, forgotten rules, and uncontrolled cost. A successful demo does not mean the job will run reliably every day.

    A sounder architecture is: use agents to help understand tasks and handle exceptions, use deterministic programs for repeated execution, and use checks to decide whether a result may proceed.

    Determinism here does not claim the program never fails. It means the same inputs, rules, and versions should produce reproducible results.

    2. Turn the seven-step flow into a verifiable data pipeline

    Split the business chain into seven stages:

    authentication → precise search → overview screenshots → detail screenshots → numeric matrix conversion → rule calculation → statistical aggregation

    Special screenshot names from the original business should map internally to clear types such as overview, grouped, or detail charts, so vague names do not scramble the flow.

    Each stage must define inputs, outputs, and acceptance criteria.

    Stage Main output Acceptance focus
    Authentication Session that can reach the target page Login state and access rights
    Precise search Result page matching the target Object IDs, time range
    Overview screenshots Complete chart images Chart fully loaded, unobstructed
    Detail screenshots Images for each detail object Complete count, no duplicates or gaps
    Matrix conversion Structured cell data Correct rows/columns, valid values
    Rule calculation Per-item analysis Explicit rule version, complete inputs
    Statistical aggregation Summary tables and exception lists Count checks, traceable results

    Stages should pass more than “success” or “failure”: task IDs, source image references, data versions, and error reasons. If one image fails recognition, reprocess that image instead of rerunning the whole batch from login.

    3. Browser automation: verify page state before acting

    1. Do not treat a fixed wait as “page ready”

    “Wait a few seconds then click” only barely works when response time is stable. Network delay, async chart loading, or popups can capture blank regions or click the wrong element.

    Prefer state-based waits:

    • Search box visible and editable;
    • Loading indicators gone;
    • Target object IDs present in the results area;
    • Chart container size reasonable;
    • Chart content stable across consecutive observations.

    For dynamically rendered charts, element existence is not enough. Combine pixel change in the chart region, loading flags, and business text, and set a maximum wait.

    2. Locators need semantics and boundaries

    Prefer accessible names, form labels, or stable business attributes over screen coordinates and element order.

    “Close popup” especially needs a bounded scope. Confirm the popup container first, then find the close control inside it—do not search the whole page for a vague “close.”

    Suggested order:

    1. Check for known popups.
    2. Classify type and whether auto-close is allowed.
    3. Close inside the popup.
    4. Verify the popup is gone and the target page remains.
    5. For unknown popups, save the scene and send to an exception queue.

    Automation must not treat “keep going” as the only goal. Stopping on unknown state is usually safer than blind clicks.

    3. CAPTCHA and identity checks are not solved by infinite retries

    For CAPTCHAs, step-up auth, or permission errors, use access methods the site allows, and human verification when needed. Do not treat bypassing security as an automation feature.

    Credentials should come through controlled configuration, not scripts, prompts, or ordinary logs. Session data needs restricted access and reasonable expiry and refresh.

    4. Screenshot capture: make images reliable data assets

    Screenshots are not only intermediate files; they are evidence for later recognition and audit.

    Each image should at least associate:

    • Task ID and business object ID;
    • Query conditions and data time range;
    • Actual capture time;
    • Chart region and display size;
    • Capture program version;
    • File checksums.

    Capture time and business time represented by the chart must be stored separately. A picture taken today may show yesterday’s data; mixing them distorts statistics.

    Unify viewport, page zoom, and chart size where possible to reduce layout drift. Check for blank, obstructed, or truncated images.

    Dedup has two levels: identical file content can flag duplicate captures, but it does not prove duplicate business records. Uniqueness should combine object ID, time range, and chart type.

    5. Vision: when rules are stable, prefer local processing

    1. Why general vision models may not fit bulk matrix parsing

    General models handle complex images well, but dense grids, tiny symbols, and similar colors need cell-level precision. Models may return structurally complete, confident answers that are locally wrong.

    For trend analysis, one wrong cell can skew later stats. Whether to use a vision model depends on per-cell accuracy, whole-matrix pass rate, and anomaly detection—not whether output “looks like” the right answer.

    Bulk calls also add latency, cost, and retries. Total cost includes recognition, validation, human review, and maintenance, not only per-call price.

    2. When local recognition applies

    When charts have a fixed grid, a limited color set, and stable symbols, local image processing can build a dedicated pipeline:

    locate chart region → recover grid → split cells → extract features → classify → validate matrix

    If numbers map to colors by business rules, recover data from color and position. If digits are actually drawn, you still need OCR or template matching.

    Color recognition is not number recognition. Confirm encoding rules first; do not infer unproven numeric meaning from color alone.

    3. Do not classify from a single pixel

    Anti-aliasing, scaling, and background blending mean one color maps to a band of pixel values.

    A more robust approach:

    • Remove grid lines and edge noise;
    • Extract a candidate region inside the cell;
    • Use regional color stats, not a single sample;
    • Combine color distance, area, and shape;
    • Mark ambiguous cells as “needs review.”

    Illustrative pseudocode (not a specific API):

    1. for each cell:
    2. extract inner valid region
    3. detect foreground color and symbol features
    4. compute match scores for candidate classes
    5. if best match is not enough to separate classes:
    6. mark for review
    7. else:
    8. save class, original position, and match evidence

    Match scores are internal decision metrics, not validated accuracy probabilities.

    4. Accuracy must be validated on samples

    Success on a few images is not “100% recognition.”

    The test set should cover normal, scaled, low-clarity, partially occluded, theme-changed, and layout-changed charts, and at least record:

    • Cell recognition accuracy;
    • Share of fully correct matrices;
    • Anomaly-image detection rate;
    • Human review rate;
    • Per-image processing time.

    Distinguish “wrong recognition” from “cannot recognize.” A system that refuses unreliable input is usually better for production than one that always answers.

    6. Algorithm dictionary: write business judgment as executable spec

    After visual parsing, business calculation should not keep relying on ad-hoc natural-language reasoning.

    The dictionary should at least describe rule ID, scope, input fields, steps, edge cases, outputs, and version. Spell out whether missing data may enter calculation, how empty matrices are handled, and priority when multiple conditions hold.

    Especially:

    • Do not fill missing values with zero unless agreed;
    • Row/column order must be defined uniformly;
    • Handle duplicates before calculation;
    • Do not mix unlabeled results from different rule versions in one summary;
    • When samples are insufficient, emit a clear status instead of forcing a conclusion.

    Each rule needs human-confirmed inputs and expected outputs for regression. After a rule change, validate historical samples before new tasks.

    7. Why errors repeat: knowledge never entered the system

    Telling an agent “don’t do that again” is not a stable constraint. Chat history may be truncated, task wording may change, and the runtime may update.

    Effective correction must land in maintainable engineering assets:

    1. Config: selectors, chart sizes, color classes, search strategy.
    2. Rule docs: allowed actions, exception handling, acceptance criteria.
    3. Test cases: screenshots that triggered errors and correct results.
    4. Code: fix the logic that actually caused the issue.

    One error should close a loop:

    save the scene → locate the cause → change rules or code → add a regression sample → verify the fix → release a version

    Agents can help analyze logs and suggest edits, but production config changes still need review and tests. Do not skip validation because the model “already remembered.”

    8. Exception recovery: keep local failures local

    Long-running jobs need explicit states, e.g. pending capture, captured, pending parse, pending review, calculated, aggregated.

    Persist artifacts and state after each stage. On restart, continue from the last valid state to avoid repeat downloads, computation, and writes.

    Retry by error type:

    • Transient network: limited retries with increasing wait.
    • Session expired: re-authenticate, then resume.
    • Page structure change: stop auto-retry, inspect locators.
    • Poor image quality: try recapture.
    • Ambiguous recognition: human review.
    • Incomplete business rules: pause calculation until rules are filled in.

    Writes to summaries should be idempotent. Build a result key from business object, data time range, chart type, and rule version so reruns update existing results instead of appending duplicates.

    9. Before go-live, close a small-batch loop

    Advance in three phases.

    Phase 1: Build a checkable baseline.
    Use a small sample covering main scenarios. Humans label and compute to validate capture, recognition, and rules.

    Phase 2: Run human and automation in parallel.
    Do not replace the original process yet. Compare outputs and trace differences to a specific image, cell, or rule—not only whether the final totals look close.

    Phase 3: Scale while keeping an exception path.
    Increase volume only after errors are locatable, results traceable, and failures recoverable. Keep pause, review, and human takeover even when the main path is stable.

    On limited hardware, capture serially, cap concurrent images, release image memory promptly, and avoid opening pages without bound. Stronger hardware should follow measured need, not hide process problems.

    10. Real “automated work” comes from engineering constraints

    Agents are valuable not only for clicking. They help developers structure flows, draft initial code, analyze exceptions, and improve tests.

    Stable automation depends on another set of capabilities: clear data contracts, reproducible processing rules, complete state records, verifiable quality gates, and explicit human takeover boundaries.

    For bulk trend-chart analysis, the end state is an observable pipeline:

    compliant capture → reliable screenshots → verifiable parsing → deterministic calculation → traceable aggregation

    Turning vague instructions into explicit specs, repeated debugging into regression tests, and accidental success into continuously verifiable runs is how you move from a usable agent to a reliable automation system.