Building a Repository-Aware AI Coding Loop in Rust

Iniciado por joomlamz, Ontem às 18:25

Respostas: 1   |   Visualizações: 7

Tópico anterior - Tópico seguinte

0 Membros e 1 Visitante estão a ver este tópico.

Olá, pessoal do **webmastersmz.com**!

Recentemente, deparei-me com uma discussão técnica bastante interessante sobre a implementação de um **"Repository-Aware AI Coding Loop" utilizando Rust**. Como alguém que vive e respira tecnologia, achei o tema pertinente para o nosso ecossistema de desenvolvimento local.

Para quem não teve a oportunidade de ler o artigo, trago aqui os pontos principais que definem o estado da arte no desenvolvimento de ferramentas de IA para programação:

### Pontos Principais:

1.  **Consciência de Repositório (Repository Awareness):** O grande desafio das IAs atuais (como o ChatGPT ou Claude) é que elas, por padrão, operam em contextos isolados. Ao criar um loop ciente do repositório, a ferramenta consegue analisar a estrutura completa do projeto, entender dependências e, crucialmente, respeitar o estilo de código existente no projeto, o que reduz drasticamente o "código esparguete".
2.  **Porquê Rust?** A escolha do Rust para este propósito é estratégica. Dada a necessidade de processar grandes volumes de dados (AST - Abstract Syntax Trees) e realizar pesquisas semânticas rápidas, o Rust oferece o **desempenho nativo** e a **segurança de memória** necessários para que a IA não se torne um gargalo de performance no fluxo de trabalho do programador.
3.  **O Loop de Feedback:** O artigo explora a automação da iteração: escrever código -> testar -> analisar erros -> ajustar contexto -> corrigir. Ao integrar isto diretamente no repositório, o loop torna-se um agente quase autónomo que entende a intenção do desenvolvedor através da análise estática em tempo real.
4.  **Eficiência de Recursos:** Ao contrário de soluções baseadas apenas em nuvem, este modelo permite uma integração mais granular, onde a IA "aprende" sobre as particularidades de bibliotecas proprietárias que não estão no conjunto de dados de treino dos grandes modelos de linguagem.

### Vamos debater!

Na nossa realidade, onde a eficiência de recursos e a produtividade são chave, como é que vocês imaginam integrar este tipo de IA nos vossos fluxos de trabalho? Acham que Rust é a escolha certa para ferramentas de automação, ou deveríamos focar-nos em linguagens com um ecossistema de IA mais vasto como o Python, mesmo com as perdas de performance? Deixem as vossas opiniões aqui no fórum!

***

Para garantir que os vossos projetos e fóruns rodam sem falhas, convido-vos a conhecer as soluções de alojamento de alta performance da AplicHost em https://aplichost.com. Temos a infraestrutura ideal para escalar as vossas aplicações e garantir que a vossa presença online seja impecável.

Building a Repository-Aware AI Coding Loop in Rust



Tópico: Building a Repository-Aware AI Coding Loop in Rust
Categoria: Tutoriais | Programação & Tecnologia
Idioma Principal: Português (Conteúdo de Tecnologia)

Descrição do Conteúdo / Informações:
-------------------------------------------------------------------------
Most AI coding examples stop after generating code.

The model receives a prompt, returns a proposed implementation, and the application prints the result. That is useful for experimentation, but it is not a complete engineering workflow. Code is only useful after it has been written to the repository, compiled, tested, and reviewed.

I built Loop Engine to explore a more practical approach:

plan → edit → verify → review → reflect

Loop Engine is an open-source Rust CLI that runs this workflow against a local repository. It uses OpenRouter for model access and allows a different model to handle each phase.



What the engine does


A normal run performs the following steps:

• Inspects the target repository.

• Creates an implementation plan.

• Lets the implementation agent read and modify files.

• Runs the repository's verification commands.

• Sends the actual changes and test output to a reviewer.

• Reflects on the result.

• Repeats when verification or review fails.

The loop only reports completion when:

• The repository contains real file changes.

• The implementation agent explicitly finishes.

• No tool error remains unresolved.

• Every configured verification command passes.

• The reviewer approves the implementation.

• The reflector agrees that the objective is complete.

A model cannot complete the workflow merely by returning the word COMPLETE.



Why Rust?


The engine executes file operations and local verification commands, so predictable behavior matters.

Rust gives the project:

• Strong types for loop state and tool actions.

• Explicit error handling.

• Safe path validation.

• Good support for asynchronous HTTP and subprocess execution.

• A single installable CLI binary.

The engine also uses optimistic concurrency for file updates. An existing file must be read before it can be written. Immediately before writing, the engine confirms that the file still matches the version the agent read.

This prevents the agent from silently overwriting a change made by the developer during the run.



Installing Loop Engine


Clone the repository:

git clone https://github.com/anggadb/loop-engine.git
cd loop-engine

Install the CLI:

cargo install --path . --locked

Create your local settings:

Copy-Item .env.example .env
Copy-Item loop-engine.json.example loop-engine.json

Add an OpenRouter API key to .env:

OPENROUTER_API_KEY=your-openrouter-key
OPENROUTER_HTTP_REFERER=your-localhost-url
OPENROUTER_X_TITLE=Loop Engine

The environment file and local model configuration are excluded from Git.



Configuring models by phase


Each phase can use a different OpenRouter model:

{
"models": {
"plan": "openai/gpt-4.1-mini",
"implement": "openai/gpt-5.1-codex",
"review": "openai/gpt-4.1-mini",
"reflect": "openai/gpt-4.1-mini"
},
"requests": {
"timeout_seconds": 600
},
"execution": {
"max_tool_calls": 30,
"timeout_seconds": 120,
"checks": []
}
}

For free experimentation, the phase models can be replaced with an available free model:

{
"models": {
"plan": "qwen/qwen3-coder:free",
"implement": "qwen/qwen3-coder:free",
"review": "qwen/qwen3-coder:free",
"reflect": "qwen/qwen3-coder:free"
},
"execution": {
"max_tool_calls": 30,
"timeout_seconds": 120,
"checks": []
}
}

Free models have stricter rate limits and may be less reliable. The exact list of available models can also change.



Inspecting a repository safely


Before sending repository content to a model, inspect the generated snapshot:

loop-engine --repo "C:\projects\my-app" --inspect

This command does not load the API key or make an OpenRouter request.

The snapshot is bounded and excludes hidden entries, common dependency directories, generated output, symlinks, binary files, and credential-like filenames. It still cannot guarantee that source files contain no sensitive values, so reviewing the snapshot remains important.



Dynamic verification detection


Loop Engine detects common build systems from files in the target directory:

Repository marker
Verification

Cargo.toml
cargo test

go.mod
go test ./...

package.json
Available test, typecheck, and build scripts

Pytest configuration
python -m pytest

You can preview the selected checks without running them:

loop-engine --repo "C:\projects\my-app" --inspect-checks

Example output for a Go repository:

{
"source": "detected",
"checks": [
{
"program": "go",
"args": ["test", "./..."]
}
]
}

Explicit checks override detection:

{
"execution": {
"max_tool_calls": 30,
"timeout_seconds": 180,
"checks": [
{
"program": "go",
"args": ["test", "./..."]
}
]
}
}

The model cannot invent arbitrary shell commands. It can request verification, but the engine only executes commands resolved from trusted configuration or fixed detection rules.



Running an objective


To run the engine against a repository:

loop-engine `
--repo "C:\projects\my-app" `
--env-file "C:\tools\loop-engine\.env" `
--config "C:\tools\loop-engine\loop-engine.json" `
"Remove the deprecated endpoint and update its tests" `
--iterations 3

During implementation, the coding agent can request these operations:

• List repository files.

• Read a text file.

• Create a text file.

• Replace an existing text file.

• Run the configured checks.

• Finish the implementation.

The engine always runs authoritative verification again after the final edit.

Exit code 0 means the work passed the completion rules. Exit code 2 means the iteration or tool budget ended before verified completion. Other nonzero codes indicate execution errors.



Prompt logs and recovery journals


Every run creates a .loop-engine directory inside the target repository:

.loop-engine/
run-<id>.jsonl
run-<id>/
iteration-001/
0001-plan.jsonl
0002-implement.jsonl
0003-implement.jsonl
0004-review.jsonl
0005-reflect.jsonl

Each prompt log records:

• The iteration and phase.

• The selected model.

• The system and user prompts.

• The response or error.

• Request timing.

• Tool results associated with the prompt.

The request is written before the API call starts. If the process is interrupted or the provider times out, the input remains available for diagnosis.

The main journal records original and replacement file content before every write. This provides a manual recovery path if a run fails after modifying files.

Logs may contain source code and model output, so .loop-engine/ should remain excluded from version control.



Handling incomplete runs


An incomplete result includes a stop_reason, such as:

verification_failed
tool_budget_exhausted
unresolved_tool_error
no_changes
invalid_review_response
review_requires_changes

It also contains:

• The changed file list.

• Verification commands and their output.

• The latest repository snapshot.

• Every model response.

• Prompt-log paths.

• The recovery-journal path.

Edits remain in the target repository after an incomplete run. This makes the result inspectable, but it also means the tool should preferably be used in a clean branch or disposable checkout.



Current limitations


Loop Engine is still experimental.

It currently:

• Replaces complete file contents instead of applying structured patches.

• Does not delete or rename files.

• Does not automatically roll back failed runs.

• Does not resume interrupted prompts.

• Detects build systems only from the selected repository root.

• Depends on model compliance with its JSON action protocol.

• Runs verification commands with the current user's operating-system permissions.

The verification process is not an operating-system sandbox. Project build scripts may access the network, environment variables, and files available to the user.



What I learned


The interesting part of an AI coding agent is not the initial code response. It is the control loop around that response.

The model needs constrained tools, real observations, explicit verification, durable logs, and a completion rule that cannot be satisfied by confidence alone.

Loop Engine is my attempt to make that loop small enough to understand while still useful against real repositories.

The source is available on GitHub:

👉 github.com/anggadb/loop-engine

Feedback, issues, and contributions are welcome.


Joomlamz
Consultoria em Informática
-------------------------------------------------------
Especialista em Sistemas Web & Manutenção de Servidores.
A desenvolver o novo AplPortal com suporte a PHP 8.
Precisa de ajuda profissional? Contacte-me.

Tags: