Practical AI-Assisted Coding: Controllability, Cost, and Context Management
This article explains how a team building an industrial data acquisition system used AI coding assistants while keeping control of the process. It covers traceability problems caused by high levels of automation, how usage quotas affect long tasks, and where AI falls short when debugging low-level communication. It also describes reusable engineering practices, including a pre-commit checklist and a project context document.
1. Background and Scope
While building an industrial data acquisition system from scratch, the development team relied heavily on AI coding assistants for requirements analysis, code generation, and troubleshooting. The more capable these tools become, the more important it is to define their execution boundaries. This article covers three practical scenarios: traceability problems caused by excessive automation, the effect of usage quotas on long tasks, and the limits of AI when debugging low-level communication. It ends with a set of reusable engineering practices.
2. Automation Level and Traceability
2.1 The Problem
Some tools can receive a requirement once and then complete the analysis, coding, file changes, and command execution automatically. The results often run right away, but the process is opaque. Developers see only the final code. They cannot tell what assumptions the tool made, which files it changed, or why it chose a particular implementation. When an anomaly appears in production, locating its cause becomes significantly harder.
2.2 Root Cause
The longer the automated chain, the fewer decision points it has. If a tool skips confirmation steps during execution, developers lose visibility into the scope of the changes. This problem is worse when permissions are broad, because the tool can modify several modules, adjust configuration, and run scripts in a single operation.
2.3 Strategies
- Confirm in stages: Ask the tool to output a plan first, then write code, then execute. A person confirms each stage before the next one starts.
- Commit in small steps: Split requirements into minimal changes that can be verified independently. Change one module at a time so that rollback stays simple.
- Review file by file: After generating code, compare the differences between the old and new version of each file. Focus on boundary conditions, exception handling, and resource release.
- Keep an operation log: Record the commands the tool runs and the scope of its changes. If a problem appears, you can trace the timeline.
Use the following checklist before committing:
[ ] The change scope matches the requirement, with no unnecessary modifications[ ] The source and version of every new dependency are confirmed[ ] Exception branches have explicit handling, with no silently swallowed errors[ ] Configuration items contain no hardcoded keys or addresses[ ] The main flow has been verified in a test environment
3. Quota Consumption and Long-Task Management
3.1 The Problem
Most AI coding tools bill by usage or limit how much you can use. When you process large batches of code generation, full-codebase refactoring, or log analysis, a task can stop midway because the quota runs out. After an interruption, the intermediate results may be incomplete, and running the task again consumes more quota.
3.2 Approaches
- Split tasks: Divide large tasks by module or feature point. The output of each subtask should be usable on its own.
- Estimate consumption: Before running a task, estimate the input size and output length. Avoid submitting content that exceeds the quota you have available.
- Record checkpoints: After each subtask finishes, write the results and progress to a document or the version control repository. After an interruption, resume from the checkpoint instead of starting over.
- Prepare fallbacks: For critical steps, prepare a manual or scripted alternative so that work does not stop when the tool is unavailable.
3.3 Key Points
Quota management comes down to reducing wasted usage. Repeatedly pasting background information and restating the same conventions consume a large share of quota. The project context document described in Section 5 can capture this information once, which lowers the cost of each interaction.
4. Low-Level Communication and Hardware Integration
4.1 A Typical Scenario
A host computer communicates with a programmable logic controller (PLC) over a persistent TCP connection, and both sides exchange data using a custom application protocol. After the connection is established, the host computer never receives any data. In this situation, AI-generated code can look logically correct and still fail to solve the actual problem, because the cause is usually in the physical layer, the network layer, or the protocol details.
4.2 Layer-by-Layer Troubleshooting
Check the following layers in order:
- Physical and network layer: Confirm the network cable, switch port, IP address, and port number. Confirm that the firewall allows the traffic.
- Connection layer: Confirm that the connection is actually established. Check whether reconnection or heartbeat mechanisms exist, and whether timeout handling applies when the connection drops.
- Protocol layer: Confirm that the frame header, function code, data length, and checksum fields match the definitions in the device manual.
- Byte order and data types: Confirm that big-endian or little-endian byte order, integer widths, and floating-point encoding match on both sides.
4.3 Value of Packet Capture
A network capture tool records the communication packets, so you can see the exact bytes each side sends. Common problems include request packets with a function code the device does not accept, incorrect length field calculations, and response packets that are split or concatenated without being reassembled correctly. Capture results provide objective evidence for diagnosis and prevent code changes based only on guesswork.
4.4 Example: Parsing a Length-Prefixed Frame
Many industrial protocols use a fixed header followed by a length field. The receiver must read the complete frame according to that length. Otherwise, sticky packets or split packets can cause errors. The following generic pseudocode shows the basic logic:
function readFrame(socket):header = readExactly(socket, 4) // read the fixed-length frame headerif header.magic != EXPECTED_MAGIC:raise ProtocolError("header magic mismatch")length = bytesToUint16BigEndian(header[2:4])body = readExactly(socket, length) // read the complete body based on the lengthreturn parseBody(body)function readExactly(socket, n):buffer = emptywhile length(buffer) < n:chunk = socket.receive(n - length(buffer))if chunk is empty:raise ConnectionClosed()buffer += chunkreturn buffer
The key point of this example is the loop that keeps reading until the required number of bytes arrives. It does not assume that one receive call returns the complete message. The byte order and frame header definition must follow the device manual.
4.5 Division of Work
AI is good at generating boilerplate code from known specifications, but it cannot replace judgment about how the field device actually behaves. For problems like this, developers should provide packet capture data, the protocol documentation for the device model, and a precise description of the symptoms. A person then determines the meaning of the protocol, and the AI tool helps implement and verify the solution.
5. Unifying Conventions with a Project Context Document
5.1 The Problem It Solves
Explaining the tech stack, coding standards, and common commands every time you start a new session takes time and is easy to get incomplete. If you write this information in a context document at the project root, the tool can read it at the start of each session. This keeps conventions consistent and reduces repeated input.
5.2 Recommended Structure
A useful context document usually includes the following sections:
- Project overview: Business goals, system components, and the main data flows.
- Tech stack: Language versions, frameworks, databases, and key dependencies.
- Coding standards: Naming style, layering conventions, unified response structure, and exception handling.
- API conventions: How API documentation is written and which annotations are required.
- Common commands: Commands for starting, building, testing, and deploying.
- Protocol conventions: Frame format, field definitions, and version notes for the communication protocol.
- Prohibited actions: For example, do not modify production configuration directly, and do not commit secrets.
5.3 Example
# Project OverviewAn industrial device data acquisition system built on a separated server and frontend architecture. It receives device data and provides visual query features.# Tech Stack- Backend: a server-side language (see the version in the pom or dependency manifest), with a common web framework and ORM tool- Frontend: a component-based frontend framework with a type system and a common UI component library- Database: relational database# Coding Standards- Use code generation annotations on entity classes to reduce boilerplate- The service layer returns a unified response wrapper, and error codes are defined in one place- API documentation is generated from annotations# Common Commands- Start backend: <backend start command>- Start frontend: <frontend start command># Protocol Conventions- The frame header is 4 bytes. The first 2 bytes are a magic number, and the last 2 bytes are an unsigned big-endian length.- See docs/protocol.md for the detailed field definitions.# Prohibited Actions- Do not write keys or device credentials into code or logs
5.4 Maintenance Principles
- Update with the code: When the tech stack or conventions change, update the context document in the same commit.
- Keep it short: Record only information that affects decisions. A long document is harder to read and consumes more quota.
- Version control it: Change the document through a review process so that team members can track changes.
6. Implementation Checklist
- Add confirmation checkpoints to automated changes, and keep a change log.
- Split long tasks into subtasks that can be completed independently, and record checkpoints.
- For low-level communication problems, capture packets first, then change the code.
- Follow the device manual for protocol details, and verify AI-generated parsing logic against real packets.
- Move stable project conventions into the context document, and maintain it alongside the code.
Following this approach, AI coding tools can handle much of the repetitive work, while key decisions and risk control stay with the developers.
