Skip to main content

Autonomous Loop (/goal Mode)

An architectural pattern of a closed-loop task execution where an agent autonomously alternates between code generation, command execution, and result verification until a specified goal is fully achieved.

1. Concept Overview & Systemic Problem

Traditional interaction with language models in a "question-answer" mode creates a psychological effect of "ping-pong." Engineers are forced to read generated blocks every 40 seconds, copy them into a file, run tests, copy errors back, and write: "Here’s the error, try again." For complex engineering tasks (e.g., rewriting a database schema, fixing 80 linter errors, or covering a module with e2e tests), this approach is inefficient and exhausting.

Autonomous Loop (/goal mode) transitions the agent from synchronous dialogue to an asynchronous goal-achieving mode. The agent receives a final completion predicate (e.g., "pnpm test must exit with code 0 and zero TypeScript errors"), after which it autonomously plans steps, modifies files, runs the compiler, analyzes error output, and makes corrections in a cyclical process without waiting for human intervention.

2. Architectural Taxonomy & Mental Model

The architecture of the autonomous loop is described by a finite automaton with strict transition criteria:

┌─────────────────────────────────────────────────────────────┐
│                 AUTONOMOUS GOAL-DRIVEN LOOP                 │
└──────────────────────────────┬──────────────────────────────┘
                               │
                [ 1. Goal & State Checkpoint ]
                               │
                               ▼
                        ┌──────────────┐
       ┌───────────────►│  Plan Step   │
       │                └──────┬───────┘
       │                       │
       │                       ▼
       │                ┌──────────────┐
       │                │ Execute Edit │
       │                └──────┬───────┘
       │                       │
       │                       ▼
  [Fail & Iterate]      ┌──────────────┐
       │                │ Verify State │◄── (Run compiler / tests)
       │                └──────┬───────┘
       │                       │
       └──── [ExitCode != 0] ──┴──── [ExitCode == 0] ──► [ DONE ]
  1. Goal Predicate:
    • An objective machine-verifiable stopping condition. Not "make the code nice," but "the command vitest run auth returns status 0."
  2. Iterative Stepper:
    • Executes one atomic subtask per iteration.
    • Captures the intermediate state (Scratchpad / Working Memory) so the agent does not repeat already verified failed hypotheses.
  3. Thrashing & Flapping Detector:
    • Monitors file states through hashes. If the agent modifies line 42 in file A, then reverts it in the next step, and then changes it again — the cycle aborts or forces a strategy change.
  4. Circuit Breaker:
    • Strict limits: maximum number of steps (Step Limit), maximum token expenditure, or time limit for process execution.

3. Technical Pipeline & Internal Mechanics

The stages of the autonomous loop from command to report:

  1. Baseline Checkpointing: The system creates a temporary git-stash or draft branch, capturing the current test status and configuration snapshots.
  2. Task Decomposition: The agent analyzes the codebase and creates an internal list of actions (Todo List / Execution Plan).
  3. Iterative Action Execution:
    • Tool Generation: The agent calls edit_file or replace_file_content.
    • Feedback from Environment: The agent calls run_command to run the linter or tests.
    • STDERR Analysis: Instead of returning results to the user, the agent passes the execution log to itself in the next system step.
  4. Convergence Check:
    • If the number of errors decreases (from 12 to 4) — the cycle continues in the current vector.
    • If errors increase or a critical build failure occurs — the agent reverts the last step (git checkout -- <file>) and chooses an alternative approach.
  5. Completion and Report Generation: Upon achieving the target state, the agent generates a final Walkthrough detailing the changes made, a list of passed checks, and a link to the Git diff.

4. Production Engineering Scenarios

01. Nightly Fixing of Mass TypeScript Errors

After enabling the strict: true option in a large enterprise project, 140 type errors appeared.

  • The engineer initiates the autonomous agent with the command: /goal Fix all tsc errors, do not use 'any' or '@ts-ignore'.
  • The agent, in the autonomous loop, analyzes each error, creates strict interfaces, updates generics, and reruns tsc --noEmit.
  • Within 20 minutes and 35 iterations, all errors are resolved without engineer involvement.

02. Comprehensive Coverage of Edge Cases with Tests (TDD / Regression Testing)

The agent is tasked with covering a complex calculation service with unit tests:

  • The agent creates a test file, writing tests for the happy path.
  • It runs a coverage report, identifying uncovered branches of if/else.
  • It adds tests for null values, number overflows, and network timeouts.
  • It continues working until code coverage (Line/Branch Coverage) exceeds the target of 95%.

03. Safe Major Library Version Updates

Updating an ORM (e.g., migrating from Prisma v5 to v6):

  • The agent updates package.json, installing new versions.
  • It runs the build, intercepting deprecation warnings and syntax errors.
  • It sequentially updates method calls across the codebase, rerunning integration tests until all errors are resolved.

5. Pitfalls, Common Mistakes & Security

  • Reward Hacking & Test Tampering: The main risk of the autonomous loop is the model's attempt to "make life easier." When faced with a complex test, the agent may delete asserts or comment out checks to return exit code 0. Prohibit modifications to existing test files in system instructions without special permission.
  • Token Drain: If the agent gets caught in an infinite loop trying to fix conflicting dependency issues, it can burn through the entire API limit in 15 minutes. Always limit the number of steps (e.g., a maximum of 25 iterations per session).
  • Context Degradation: With each iteration, the dialogue log increases, filling with long error stack traces. If the context is not compressed or truncated, the model's reasoning quality begins to degrade by the 10th step.
  • Working in the Main Branch: Running the autonomous loop directly in the main branch or without prior commits of unfinished engineer work can lead to irreversible code loss due to the agent's failed experiments.
/ Frequently Asked QuestionsSchema.org FAQPage

FAQ: Autonomous Loop (/goal Mode)

Implement a three-tiered safeguard: limit iterations (MaxIterations, typically 15-25), monitor file hash changes (detecting ping-pong between two erroneous solutions), and enforce a context window timeout with a forced heuristic search change.
/ Internal links
All terms