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

    This guide explains how to build agent-assisted automation that delivers trustworthy results, not just page clicks. It covers layered responsibilities, web verification, evidence-based screenshots, image-to-matrix recognition, versioned rules, orchestration, reporting, and cost and security checks.

    1. The Goal of Automation Is Trustworthy Delivery, Not “Being Able to Operate”

    Daily work such as logging into a business site, searching for records, capturing trend charts, reading colors and numbers, running algorithms, and summarizing results looks like repetitive labor. In practice it includes many interdependent technical steps.

    A human operator fills in context automatically: wait if the page is not loaded, reopen a chart that looks wrong, and note missing records. An automation system must turn those implicit judgments into explicit conditions. Otherwise a single locator error can propagate and produce a report that is well formatted but factually wrong.

    Building such a system should not start with “can the agent operate the web page?” It should start with three questions:

    • Do inputs come from the correct page, object, and time range?
    • Do image recognition and rule calculations rest on clear, inspectable evidence?
    • When something fails, can the system stop error propagation and keep recovery clues?

    A more reasonable engineering goal is: complete tasks that meet preset conditions automatically, and send tasks that do not into a traceable exception path.

    “Fully automatic” does not mean no people in any situation. It means routine tasks no longer depend on step-by-step human operation, and exceptions are not silently ignored.

    2. Split Responsibilities: Agents Collaborate; Programs Execute Deterministically

    The original workflow can be organized into seven stages:

    Log in → precise search → capture base screenshots → capture grouped screenshots → convert to a numeric matrix → run rule calculations → aggregate statistics.

    Base and grouped screenshots are different types of business input. Their meaning should be defined by the business, not guessed by the agent from names.

    These seven stages should not all be left to free model planning. Split them into three layers.

    2.1 Execution layer: operations that can be specified clearly

    The execution layer handles page location, query input, screenshots, image preprocessing, matrix conversion, and rule calculation.

    Given the same inputs, these tasks should produce the same results. Implement them with fixed programs, not by regenerating steps from a model each time.

    For example, before capturing a screenshot, verify that the target chart exists, loading has finished, and the query object matches. Rule calculation should use confirmed formulas, not a model’s ad hoc reading of business terms.

    2.2 Orchestration layer: task state and recovery

    The orchestration layer tracks progress, failure reasons, retry counts, and artifact locations.

    It must know that a record has been captured but not yet recognized, and it must resume from a safe point after a process restart instead of reprocessing everything.

    An agent can help explain exceptions and suggest fixes, but critical state changes should be triggered by the program under explicit conditions.

    2.3 Analysis layer: explanation and assisted judgment

    Models are better suited to explaining structured results, summarizing exception patterns, and drafting reports.

    Quantities, ratios, and statistical metrics in the report should come directly from the calculation program. The model must not invent data for smoother prose, and must not describe unprocessed records as complete.

    This split reduces model calls and limits how far model uncertainty can affect business results.

    3. Web Automation: Verify the Page Before Acting

    Unstable web operations are often not “the model is not smart enough,” but scripts that do not check page state.

    3.1 Login success needs observable evidence

    Clicking Login is not proof of success. Confirm authentication with page elements that reflect state, such as a logged-in region, access to the target feature, or disappearance of the login prompt.

    Store session data securely and check validity before reuse. If authentication fails, re-enter the compliant login flow; do not search on an expired page.

    For CAPTCHA and other security checks, pause and request authorized human handling, or use authentication methods the site allows. Do not try to bypass verification.

    3.2 Avoid fragile coordinates for locators

    Clicks based only on screen coordinates break with window size, zoom, ads, and layout changes.

    Prefer page structure, field semantics, and stable attributes, and constrain the action region. For example, locate the query form first, then the input inside it, instead of taking the first element that looks like a search box.

    After search, check object IDs and time range in the results. Correct input that was never submitted still produces wrong screenshots later.

    3.3 Wait on business state

    Fixed sleeps only reduce some failures; they do not prove the page is ready.

    Reasonable wait conditions include:

    • loading indicators gone;
    • chart region visible;
    • result identifiers matching the current task;
    • chart size and content remaining stable across consecutive checks.

    Set timeouts. On timeout, save the scene and return an exception; do not loop forever.

    3.4 Popup handling needs a clear boundary

    Close only confirmed popups, then check that the target page still exists.

    Do not let the system click unknown dialogs at random. Prompts that confirm transactions, grant permissions, or modify data should go to a human.

    4. Screenshot Capture: Save Evidence, Not Just Images

    If the screenshot is wrong, no recognition algorithm can save the result. Capture should store the image and task metadata together.

    Record at least:

    • task ID and business object ID;
    • query conditions and time range;
    • screenshot type;
    • capture time;
    • chart region size;
    • page structure version or capture-rule version;
    • file integrity checksum.

    This helps diagnose mixed-up screenshots, stale cache, and overwritten files with the same name.

    Crop to the chart that must be analyzed, excluding menus, hints, and decorative backgrounds. Do not set crop bounds by guesswork; verify across page sizes that rows, columns, borders, and legends remain complete.

    Distinguish “the page has no data” from “data has not loaded yet.” The first may be a valid business state; the second is an execution failure. Do not save both as blank images and continue.

    5. Image to Matrix: Prefer Fixed Structure; Use Models on Hard Samples

    Sending every chart to a vision model usually means unstable results, higher cost, and weak explainability. Claiming local image processing is fully accurate in every scene is also unjustified.

    Choose the method from chart structure.

    5.1 Decide whether image recognition is required

    If the business system offers authorized structured export or data APIs, evaluate those first. Raw data is usually more reliable than inferring numbers from screenshots.

    Use screenshot recognition as the main path only when structured data cannot be obtained legally and stably.

    5.2 Deterministic processing for stable charts

    For charts with stable layout, limited colors, and clear cell rules, process in this order:

    image quality check → region crop → grid location → cell sampling → color classification → symbol recognition → matrix validation.

    Do not classify color from a single pixel. Text edges, anti-aliasing, and background noise change pixel values. Sample multiple points inside a cell or measure color distribution in the valid area.

    If digits must be read, handle character regions separately. Correct color classification does not imply correct digit recognition.

    If business rules map colors or fixed symbols to values, put that mapping in explicit configuration. If color is only a display attribute, do not treat it as the real number.

    5.3 Do not force an answer on low-confidence samples

    The recognition module should return both a result and quality signals: whether the grid is complete, whether colors fall in known ranges, whether characters are ambiguous.

    Use these signals to filter exceptions. Do not treat uncalibrated internal scores as true accuracy.

    For close colors, blurry characters, abnormal sizes, or conflicting rules, recapture, use a fallback recognizer, or send to human review. Do not default to the “most similar” result.

    5.4 Validate scope with labeled samples

    Build a human-checked sample set covering normal charts, different sizes, edge colors, missing cells, and abnormal pages.

    Evaluate at least:

    • cell-level accuracy;
    • share of fully correct matrices;
    • accuracy of final business calculations;
    • share of abnormal samples successfully intercepted.

    Do not mix these metrics. Few cell errors can still include critical mistakes in a large matrix.

    6. Rule Calculation: Turn Repeated Corrections into Executable Constraints

    An agent accepting a correction in chat does not mean the capability has permanently changed. Context shifts, missing prompts, or generation variance can bring old errors back.

    The fix is not repeating “don’t make that mistake next time.” Encode business rules in the system.

    6.1 Versioned rule dictionary

    Each rule should specify input format, logic, boundary conditions, missing-value handling, and output meaning.

    Example:

    1. Rule ID: R-01
    2. Input: numeric matrix with fixed rows and columns
    3. Preconditions: dimensions correct; elements in the allowed set
    4. Missing values: return pending-review status
    5. Logic: execute a deterministic formula confirmed by the business
    6. Output: computed value, rule version, input validation result

    A model can help organize rules, but official rules need business confirmation. Do not use formulas the model inferred on the fly.

    6.2 Add a regression test for every bug found

    A fix is real only when there is a reproducible input, an expected result, and an automated check.

    Tests should cover normal input, empty input, wrong dimensions, unknown symbols, boundary values, and duplicate records. After changing recognition or calculation code, run these tests before release.

    6.3 Separate business rules from exception handling

    Do not hard-code recognition failure into a business result. Unreadable cells must not be filled with zero unless the business defines zero as the legal missing-value meaning.

    Otherwise technical faults are packaged as real data and are hard to spot at aggregation time.

    7. Orchestration: Failure Is Allowed; Loss of Control Is Not

    Maintain a clear state for each task:

    pending → located → captured → recognized → calculated → aggregated.

    Any stage may enter “retryable failure” or “pending human review,” but must not skip required checks and jump to complete.

    Sketch:

    1. For each task:
    2. Check whether a valid completed result already exists
    3. Validate page and query object
    4. Obtain and inspect screenshots
    5. Recognize the matrix and check quality
    6. Run deterministic rules
    7. Save results and version information
    8. On failure:
    9. Record stage, reason, and scene
    10. Decide whether a limited retry is allowed
    11. If unrecoverable, send to human review

    Retries should depend on failure type. Transient network errors can retry; expired auth needs login again; rule conflicts need review; page-structure change needs capture logic updates.

    Writes should be idempotent. Re-running the same task must not create duplicate stats. Task keys can combine business object, time range, screenshot type, and rule version so batches and rule versions do not overwrite each other.

    8. Aggregation: Report Results and Data Quality

    Aggregation must not be a single final number. State the data basis.

    List at least planned tasks, successes, failures, pending review, and how many actually entered calculation. Ratios need an explicit denominator so readers do not assume every planned task was included.

    Deduplicate before aggregation. For missing data, say whether records were excluded and why. Cross-batch analysis needs a unified time window and rule version; otherwise numbers look comparable but come from different processing standards.

    Model-written reports should cite computed metrics and keep quality notes. If data is incomplete, state that conclusions cover only successfully processed parts.

    9. Cost, Security, and Go-Live Acceptance

    9.1 Optimize cost across the full chain

    Do not count only model-call fees. Include development and maintenance, runtime resources, exception review, and error repair.

    Local deterministic processing for stable charts, assisted recognition for a few hard samples, and models for explanations of structured results is usually easier to budget than full vision on every image. Measure actual tasks; do not promise a fixed savings ratio.

    9.2 Least privilege for data and access

    Do not put login credentials in prompts, ordinary logs, or screenshot filenames. Set access, retention, and deletion by sensitivity of screenshots and reports.

    If using external inference, confirm whether data may leave the environment and redact unnecessary personal or sensitive fields.

    9.3 Expand from small-batch validation

    A reasonable sequence is: single-path validation, small-batch human comparison, full-batch run, then continuous observation.

    Acceptance is not “the program did not throw.” It is correct input objects, traceable key artifacts, calculations matching a human baseline, discoverable failures, and recovery without duplicate data.

    Old hardware can support a prototype, but continuous operation also needs storage, resource use, power-loss recovery, and scheduler stability. One successful run is not proof of production readiness.

    Conclusion: Reliable Automation Comes from Constraints, Not a One-Off Prompt

    Handing repetitive work to an agent really means building a production flow with clear inputs, validation conditions, rule versions, and recovery.

    Agents help understand problems, organize rules, analyze exceptions, and generate explanations. Fixed programs handle repeated operations and deterministic calculation. Tests and monitoring prove the system remains trustworthy.

    When every error becomes a locator, a test sample, and an execution constraint, automation moves from “it ran once” to “it stays usable.” Reducing manual steps is only the first step. Accurate results, visible exceptions, and a maintainable process are the long-term value.