Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 62 additions & 2 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,67 @@ node server.js

You can browse the apis at <http://localhost:3000>

## API

### Notes

| Method | Path | Description |
|--------|------|-------------|
| POST | `/notes` | Create a note |
| GET | `/notes` | List notes (optional filters) |
| GET | `/notes/:noteId` | Get one note |
| PUT | `/notes/:noteId` | Update a note |
| DELETE | `/notes/:noteId` | Delete a note |

### Note fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `title` | string | No | Defaults to `"Untitled Note"` |
| `content` | string | Yes | Note body |
| `tags` | string[] | No | Labels for organizing notes; defaults to `[]` |

### Create a note

```bash
curl -X POST http://localhost:3000/notes \
-H "Content-Type: application/json" \
-d '{"title":"Q3 Budget","content":"Review expenses","tags":["work","finance"]}'
```

Omitting `tags` creates a note with an empty tags array.

### List and search notes

```bash
# All notes
curl http://localhost:3000/notes

# Filter by tag
curl "http://localhost:3000/notes?tag=work"

# Filter by multiple tags (OR)
curl "http://localhost:3000/notes?tag=work&tag=personal"

# Keyword search in title and content
curl "http://localhost:3000/notes?q=budget"

# Combined tag filter and keyword search
curl "http://localhost:3000/notes?tag=work&q=meeting"
```

### Update a note

```bash
curl -X PUT http://localhost:3000/notes/:noteId \
-H "Content-Type: application/json" \
-d '{"title":"Updated","content":"New content","tags":["personal"]}'
```

If `tags` is omitted from the request body, existing tags are preserved. Send `"tags": []` to clear all tags.

## Tutorial
You can find the tutorial for this application at [The CalliCoder Blog](https://www.callicoder.com) -

<https://www.callicoder.com/node-js-express-mongodb-restful-crud-api-tutorial/>
You can find the tutorial for this application at [The CalliCoder Blog](https://www.callicoder.com) -

<https://www.callicoder.com/node-js-express-mongodb-restful-crud-api-tutorial/>
52 changes: 52 additions & 0 deletions agent/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# AI Coding Agent

A reusable, LLM-driven Python agent that explores, plans, implements, validates, and summarizes code changes in a repository.

## Usage

```bash
python agent/main.py \
--repo <path-to-target-repo> \
--task "<natural language description>" \
[--output agent-output/] \
[--model openai/gpt-4o-mini] \
[--api-key KEY]
```

## Requirements

- Python 3.8+
- `OPENROUTER_API_KEY` environment variable or `--api-key` argument

## Directory Structure

```
agent/
├── main.py # CLI entry point
├── llm.py # LLM abstraction (LLMClient + OpenRouterClient)
├── explorer.py # Stage 1: repository inspection
├── planner.py # Stage 2: plan generation
├── executor.py # Stage 3: file modifications via LLM
├── validator.py # Stage 4: change validation
├── summarizer.py # Stage 5: execution summary
├── prompts/ # Prompt templates for each stage
│ ├── repository_analysis.md
│ ├── planning.md
│ ├── implementation.md
│ ├── validation.md
│ └── summary.md
├── requirements.txt
└── README.md
```

## How It Works

1. **Explorer** — walks the target repo, detects language/framework/structure, calls the LLM to analyze
2. **Planner** — reads the analysis, calls the LLM to generate a step-by-step implementation plan
3. **Executor** — reads the plan, modifies files via LLM with complete-file-overwrite strategy, validates before writing
4. **Validator** — checks modified files for syntax validity and structural preservation
5. **Summarizer** — generates a structured markdown summary of the entire execution

## License

MIT
Empty file added agent/__init__.py
Empty file.
121 changes: 121 additions & 0 deletions agent/executor.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
import os
import json
from validator import Validator


class Executor:

def run(self, context):
print("Executing...")
plan = context.get("plan", "")
llm_client = context["llm"]
repo_path = context.get("repo_path", "")
validator = Validator()

output_dir = context.get("output_dir", "agent-output")
plan_path = os.path.join(output_dir, "plan.md")

if not os.path.exists(plan_path):
return {"modifications": [], "error": "Plan file not found"}

with open(plan_path, "r", encoding="utf-8") as fh:
plan_content = fh.read()

files_to_modify = self._extract_files_from_plan(plan_content)

if not files_to_modify:
files_to_modify = self._extract_files_from_analysis(context.get("analysis", ""), plan_content)

modifications = []

for file_info in files_to_modify:
file_path = file_info.get("path", file_info) if isinstance(file_info, dict) else file_info
abs_path = os.path.join(repo_path, file_path)

if not os.path.exists(abs_path):
modifications.append({"file_path": file_path, "success": False, "error": "File not found"})
continue

with open(abs_path, "r", encoding="utf-8") as fh:
original_content = fh.read()

result = self._execute_file(
file_path,
original_content,
plan_content,
llm_client,
context.get("language", "javascript"),
)

modifications.append(result)

if result["success"]:
backup = original_content
try:
with open(abs_path, "w", encoding="utf-8") as fh:
fh.write(result["content"])

validation = validator.validate_file(
abs_path,
result["content"],
original_content,
plan_content,
context.get("language", "javascript"),
)

if not validation["passed"]:
with open(abs_path, "w", encoding="utf-8") as fh:
fh.write(backup)
result["success"] = False
result["error"] = "Post-write validation failed: " + str(validation["checks"])
except Exception as write_err:
with open(abs_path, "w", encoding="utf-8") as fh:
fh.write(backup)
result["success"] = False
result["error"] = str(write_err)

context["modifications"] = modifications
return {"modifications": modifications}

def _extract_files_from_plan(self, plan_content):
files = []
for line in plan_content.split("\n"):
stripped = line.strip()
if stripped.startswith("-") or stripped.startswith("*") or stripped.startswith("1.") or stripped.startswith("2.") or stripped.startswith("3."):
candidates = stripped.split(" ")
for candidate in candidates:
if any(candidate.endswith(ext) for ext in [".js", ".ts", ".py", ".json", ".md", ".jsx", ".tsx"]):
candidate = candidate.strip("`")
if "/" in candidate or candidate.endswith(".md"):
files.append(candidate)
return files

def _extract_files_from_analysis(self, analysis, plan_content):
files = []
combined = analysis + "\n" + plan_content
for line in combined.split("\n"):
stripped = line.strip()
if stripped.startswith("`") and stripped.endswith("`") and len(stripped) > 2:
files.append(stripped.strip("`"))
elif "/" in stripped and (stripped.endswith(".js") or stripped.endswith(".py") or stripped.endswith(".ts")):
files.append(stripped)
return files

def _execute_file(self, file_path, original_content, plan_content, llm_client, language):
prompt_path = os.path.join(os.path.dirname(__file__), "prompts", "implementation.md")
with open(prompt_path, "r", encoding="utf-8") as fh:
template = fh.read()

prompt = template.replace("{plan}", plan_content).replace("{file_path}", file_path).replace("{original_content}", original_content).replace("{language}", language)

messages = [
{"role": "system", "content": "You are an expert code editor applying a plan to a specific file."},
{"role": "user", "content": prompt},
]

content = llm_client.chat(messages, temperature=0.4)

if content.strip():
return {"file_path": file_path, "success": True, "content": content, "error": None}
else:
return {"file_path": file_path, "success": False, "content": original_content, "error": "LLM returned empty response"}
142 changes: 142 additions & 0 deletions agent/explorer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
import os
import glob


def detect_language(repo_path):
markers = {
"python": ["requirements.txt", "setup.py", "pyproject.toml", "setup.cfg"],
"javascript": ["package.json", "jsconfig.json"],
"typescript": ["tsconfig.json", "package.json"],
"go": ["go.mod", "go.sum"],
"rust": ["Cargo.toml"],
"ruby": ["Gemfile"],
}
for lang, files in markers.items():
for f in files:
if os.path.exists(os.path.join(repo_path, f)):
return lang
return "unknown"


def detect_framework(repo_path, language):
if language == "python":
for f in ["requirements.txt", "pyproject.toml"]:
full = os.path.join(repo_path, f)
if os.path.exists(full):
with open(full, "r", encoding="utf-8", errors="replace") as fh:
content = fh.read()
if "flask" in content.lower():
return "Flask"
if "django" in content.lower():
return "Django"
if "fastapi" in content.lower():
return "FastAPI"
return "Python"
if language == "javascript":
pkg_path = os.path.join(repo_path, "package.json")
if os.path.exists(pkg_path):
with open(pkg_path, "r", encoding="utf-8", errors="replace") as fh:
content = fh.read()
if "express" in content.lower():
return "Express"
if "fastify" in content.lower():
return "Fastify"
return "Node.js"
return language


def find_entry_point(repo_path, language):
candidates = {
"python": ["app.py", "main.py", "manage.py", "server.py"],
"javascript": ["server.js", "app.js", "index.js", "main.js"],
"typescript": ["server.ts", "app.ts", "index.ts"],
"go": ["main.go"],
"rust": ["src/main.rs"],
}
for name in candidates.get(language, []):
if os.path.exists(os.path.join(repo_path, name)):
return name
return None


def find_source_tree(repo_path, language):
source_dirs = []
for name in ["src", "app", "lib", "modules", "controllers", "routes", "models"]:
full = os.path.join(repo_path, name)
if os.path.isdir(full):
source_dirs.append(name)
return source_dirs


def find_files(repo_path, pattern):
matches = glob.glob(os.path.join(repo_path, "**", pattern), recursive=True)
return [os.path.relpath(m, repo_path) for m in matches]


def analyze_repo(repo_path, task, llm_client):
from llm import LLMClient
assert isinstance(llm_client, LLMClient)

language = detect_language(repo_path)
framework = detect_framework(repo_path, language)
entry_point = find_entry_point(repo_path, language)
source_tree = find_source_tree(repo_path, language)

all_files = []
for root, dirs, files in os.walk(repo_path):
dirs[:] = [d for d in dirs if d not in (".git", "node_modules", "__pycache__", ".venv", "venv")]
for f in sorted(files):
rel = os.path.relpath(os.path.join(root, f), repo_path)
all_files.append(rel)

route_files = [f for f in all_files if "route" in f.lower() and f.endswith((".js", ".ts", ".py"))]
controller_files = [f for f in all_files if "controller" in f.lower() and f.endswith((".js", ".ts", ".py"))]
model_files = [f for f in all_files if "model" in f.lower() and f.endswith((".js", ".ts", ".py"))]
config_files = [f for f in all_files if f.endswith((".json", ".yaml", ".yml", ".toml", ".cfg", ".ini")) and "package" not in f.lower()]

prompt_path = os.path.join(os.path.dirname(__file__), "prompts", "repository_analysis.md")
with open(prompt_path, "r", encoding="utf-8") as fh:
template = fh.read()

prompt = template.replace("{repo_path}", repo_path).replace("{task}", task)

messages = [
{"role": "system", "content": "You are a code analysis expert. Analyze the repository structure and return a structured markdown analysis."},
{"role": "user", "content": prompt},
]

analysis = llm_client.chat(messages, temperature=0.3)

return {
"analysis": analysis,
"language": language,
"framework": framework,
"entry_point": entry_point,
"source_tree": source_tree,
"route_files": route_files,
"controller_files": controller_files,
"model_files": model_files,
"config_files": config_files,
"all_files": all_files,
}


class Explorer:

def run(self, context):
print("Exploring...")
repo_path = context["repo_path"]
task = context["task"]
llm_client = context["llm"]

result = analyze_repo(repo_path, task, llm_client)

output_dir = context.get("output_dir", "agent-output")
os.makedirs(output_dir, exist_ok=True)
analysis_path = os.path.join(output_dir, "analysis.md")
with open(analysis_path, "w", encoding="utf-8") as fh:
fh.write(result["analysis"])

context["analysis"] = result["analysis"]
context["explorer_result"] = result
return context
Loading