Practical AI Coding: Steps from Environment Setup to Project Deployment

    AI coding tools can now handle most coding tasks based on natural language descriptions, shifting developers' focus to requirement decomposition, constraint setting, and result review. This article follows a practical workflow covering environment setup, small project exercises, working mode selection, permission and version management, project context files, and the boundaries of multi-agent collaboration.

    Practical AI Coding: Steps from Environment Setup to Project Deployment

    AI programming tools can now handle most coding tasks based on natural language descriptions. Consequently, developers’ focus shifts to requirement decomposition, constraint setting, and result review. This article follows a practical operational sequence, covering environment setup, small project exercises, working mode selection, permission and version management, project context files, and the applicable boundaries of multi-agent collaboration.

    1. Setting Up the Environment

    Before starting, ensure your local toolchain is functional. The table below lists recommended versions and verification commands for common components.

    Component Recommended Version Verification Command Purpose
    Git 2.30 and above git --version Track changes, review diffs, revert files
    Node.js 20 LTS node -v Dependency for CLI components of some AI coding tools
    Python 3.10 and above python --version Run sample projects
    AI Coding Tool CLI Refer to official docs tool_name --version Confirm successful installation and correct path

    Configure your environment following these steps:

    1. Create an independent directory as a test repository, for example: mkdir ai-sandbox && cd ai-sandbox && git init. Complete all initial trials here to avoid affecting other projects.
    2. Write API credentials into environment variables, for example: export API_KEY=your_api_key. Do not write secrets into code or configuration files, nor paste them into the conversation.
    3. Configure minimal permissions. Allow the tool to read and write only within the current project directory, and open only whitelisted commands for execution like testing and formatting. Operations such as deleting files or pushing code should require manual confirmation.
    4. Run git status to check the repository state, then send a side-effect-free instruction, such as “list files in the current directory,” to confirm the tool responds correctly.

    2. Starting with Small Projects

    Beginners should start with small projects. The first exercise is to generate a static personal homepage, aiming to familiarize yourself with describing layout and interaction using natural language. Once completed, move on to the news aggregator exercise below.

    The key mindset for such exercises is that AI will not deliver perfect results in one go. A more reasonable approach is to treat it as a pair programming partner, making only one change per round, checking the result after execution, and then deciding the next step.

    Daily News Aggregator

    Function: Read a set of RSS URLs, fetch the latest entries from each source, and generate a Markdown file sorted by date.

    Tech Stack: Python 3.10 and above, depending on requests and feedparser.

    Directory Structure:

    1. news-aggregator/
    2. ├── aggregator.py
    3. ├── feeds.txt # One RSS URL per line
    4. ├── requirements.txt # requests, feedparser
    5. ├── output/ # Generated daily reports
    6. └── logs/ # Run logs

    Core Code:

    1. import feedparser
    2. import requests
    3. from pathlib import Path
    4. from datetime import datetime
    5. FEEDS = Path("feeds.txt").read_text(encoding="utf-8").split()
    6. OUT = Path("output")
    7. OUT.mkdir(exist_ok=True)
    8. def fetch(url):
    9. resp = requests.get(url, timeout=10)
    10. resp.raise_for_status()
    11. return feedparser.parse(resp.content)
    12. def main():
    13. lines = []
    14. for url in FEEDS:
    15. try:
    16. feed = fetch(url)
    17. except requests.RequestException as e:
    18. print(f"Skipping {url}: {e}")
    19. continue
    20. for entry in feed.entries[:20]:
    21. title = entry.get("title", "Untitled")
    22. link = entry.get("link", "")
    23. lines.append(f"- [{title}]({link})")
    24. name = datetime.now().strftime("%Y%m%d") + ".md"
    25. (OUT / name).write_text("\n".join(lines), encoding="utf-8")
    26. print(f"Wrote {len(lines)} items to {OUT / name}")
    27. if __name__ == "__main__":
    28. main()

    Run Commands:

    1. python -m venv .venv
    2. source .venv/bin/activate # Windows: use .venv\Scripts\activate
    3. pip install -r requirements.txt
    4. python aggregator.py

    For scheduled execution, you can use cron, for instance, running every day at 8:00 AM:

    1. 0 8 * * * cd /absolute/path/news-aggregator && .venv/bin/python aggregator.py >> logs/run.log 2>&1

    Common Troubleshooting:

    Symptom Possible Cause Solution
    All sources fail Network or proxy configuration error Test a single source using curl -I URL
    Titles display garbled text Source encoding is not UTF-8 Check the encoding returned by the source; convert before parsing if necessary
    Content overwritten after repeated runs on the same day Filename only uses the date Use a timestamp for naming, or append to the file
    Scheduled task does not execute Relative paths used Always use absolute paths in cron

    3. Choosing Between Planning and Automated Modes

    Most AI coding tools offer two working modes for different scenarios.

    Dimension Planning Mode Automated Mode
    Applicable Scenarios Refactoring, cross-module changes, tasks with unclear requirements Formatting adjustments, repetitive modifications, tasks with existing test coverage
    AI Behavior Lists steps and impact areas first, waits for confirmation Reads and writes files within authorized scope and executes tests
    Main Risks The plan looks reasonable but misses dependencies Modifying files incorrectly, or executing unauthorized commands
    Permission Suggestions Primarily read-only analysis Restrict to specific directories, use command whitelist
    Manual Review Points Allow execution only after confirming the plan Review diffs after each completion

    For complex tasks, use planning mode first to review the plan. Once confirmed, delegate repetitive work to automated mode.

    4. Permissions, Version Control, and Context Cleanup

    After completing each phased task, review changes with git diff before committing. You can check against the following list before committing:

    1. There are no .env files or secret contents in the repository.
    2. The diff contains only files relevant to the current task.
    3. Test or build commands have passed.
    4. The commit message clearly describes the changes.

    Credentials should be stored in environment variables or in a .env file ignored by .gitignore. Ensure .gitignore includes the .env line.

    If you need to revert a change, first confirm the scope of the issue, then use git restore filename to restore only the affected files. Avoid executing a full repository reset directly to prevent accidentally deleting other uncommitted work.

    The session context can become cluttered as the conversation grows longer. Clean up the context when the following occurs: the conversation has many rounds; the AI starts repeating already solved problems; the task switches to another module. The cleanup method is: write the current conclusions into a document, start a new session, and attach only the files relevant to the new task.

    5. Writing Project Context Files

    Project context files are used to tell the AI about the project’s tech stack, structure, and prohibitions. The file can be named project-context.md and placed in the repository root or .ai/ directory. Tools that support reading project description files will usually load it automatically. If the tool does not support auto-loading, explicitly reference the file in the first message of a new session.

    The file is recommended to be divided into three layers:

    • Global Specifications: Tech stack versions, code style, naming conventions.
    • Architecture Constraints: Directory structure, dependency directions between modules.
    • Behavioral Guardrails: Explicitly prohibited operations, such as “Do not modify core configuration files” or “Do not add new third-party dependencies.”

    Example:

    1. # Project Context Description
    2. ## Tech Stack
    3. - Frontend: React 18 + TypeScript
    4. - Backend: Node.js (Express)
    5. - Database: MongoDB
    6. ## Architecture Constraints
    7. - Follow the MVC structure; controllers are located in `src/controllers/`
    8. - All API responses must be encapsulated using `ResponseHandler`
    9. ## Behavioral Guardrails
    10. - Do not modify dependencies in `package.json` without confirmation
    11. - Must confirm in the conversation before modifying the database Schema

    File maintenance rules:

    • When modifying the context file, commit it via a branch and have it reviewed by team members. Unless explicitly requested by the user, the AI should not directly rewrite this file.
    • Explicit instructions in the current conversation take precedence over default rules in the file. If a conflict arises, the AI should first explain the conflict and then request confirmation.
    • Check the file contents at the end of each iteration to remove outdated rules.

    6. MCP and Multi-Agent Collaboration

    MCP (Model Context Protocol) addresses how models connect to external capabilities. It provides a unified way for models to connect to tools and data sources, such as reading database structures or querying internal documentation. It does not handle task allocation among agents.

    Multi-agent collaboration solves another problem: splitting a large project among multiple agents, for example, with separate agents for frontend, backend, and testing. They need to exchange interface definitions and progress through message queues or shared context files, and finally, a master agent completes the integration.

    A multi-agent approach is suitable for projects with clear module boundaries, defined interfaces, and independent file scopes for each agent. If the task is small or modules are tightly coupled, a single agent paired with a clear context file is usually simpler and easier to review.

    7. Lifecycle Hooks Example

    Lifecycle hooks allow custom scripts to run before or after the AI performs specific actions. The following example automatically formats and runs code linting after a file is edited. Refer to your tool’s documentation for specific integration methods.

    1. #!/usr/bin/env bash
    2. set -euo pipefail
    3. FILE="$1"
    4. npx prettier --write "$FILE" || exit 1
    5. npx eslint "$FILE" || exit 1

    Execution Timing: Runs after each file edit is completed.

    Failure Handling: If any command returns a non-zero exit code, the script stops immediately and outputs an error message. The current diff is retained, and the developer decides whether to fix it or use git restore to revert the file.

    The "$FILE" in the script uses double quotes to prevent errors when the filename contains spaces or special characters.

    8. Conclusion

    Given clear requirements, restricted permissions, and version control, this workflow reduces incorrect modifications and makes each change easier to trace. Results generated by AI still require human review. Making small-scale changes per round and promptly checking the results is generally more stable and easier to debug than delivering a large amount of code all at once.