chore(doc):Polish the blog and translate it

This commit is contained in:
david_bai
2025-12-26 20:51:06 +08:00
parent 49e20edd80
commit 0b82fc2d47
8 changed files with 1894 additions and 35 deletions
+2
View File
@@ -71,3 +71,5 @@ logs/
# Temporary files
.temp/
.tmp/
AGENTS.md
@@ -0,0 +1,318 @@
---
title: "Damit KI nicht mehr abschweift: ein praxistaugliches CollaborationPlaybook (mit Vorlagen)"
description: "Geht KICode ständig am Thema vorbei? Mit AGENTS.md, einem AI Playbook und einem plan-firstWorkflow wird Codex/Claude zum echten Teammate: weniger Nacharbeit, bessere Wartbarkeit. Mit Next.jsPraxisbeispielen."
date: "2025-12-26"
author: "david bai"
cover: "/blog-assets/privydrop-open-source.jpg"
tags:
["KIZusammenarbeit", "Codex", "EngineeringProzess", "Open Source", "Next.js"]
status: "published"
---
![](/blog-assets/privydrop-open-source.jpg)
Kommt dir das bekannt vor?
- Du bittest KI, einen Bug zu fixen—und sie ändert gleich „hilfsbereit“ auch UnrelatedCode. Am Ende revertierst du von Hand.
- Du schreibst endlose Prompts, aber die KI findet die richtigen Dateien nicht und „rät“.
- Mitten in einer langen Unterhaltung vergisst sie Constraints; die Qualität fällt abrupt ab.
Wenn du KI nur als „schnellere Suche“ nutzt, fallen diese Probleme kaum auf. Sobald du KI aber als „kollaborierenden Teammate“ behandelst, wirken sie direkt auf DeliveryQualität.
Dieser Artikel zeigt einen **umsetzbaren EngineeringProzess**, der KIZusammenarbeit von „PromptMagie“ zu einem **reproduzierbaren Workflow** macht. In PrivyDrop wurden FeatureEntwicklung und Bugfixing spürbar schneller und stabiler—nicht durch mehr Risiko, sondern durch weniger Nacharbeit.
Am Ende hast du eine minimale Struktur, die du in jedes Repo kopieren kannst:
- `AGENTS.md`: harte RepoConstraints (Red Lines, Defaults, Definition of Done)
- `docs/ai-playbook/index.md`: ein einseitiger HighSignalIndex
- `docs/ai-playbook/code-map.md`: CodeLandkarte (wo ändern)
- `docs/ai-playbook/flows.md`: zentrale Flows (wie es läuft)
- `docs/ai-playbook/collab-rules.md`: Kollaborationsregeln + ChangePlanTemplate (wie wir arbeiten)
Alle Beispiele stammen aus dem OpenSourceRepo PrivyDrop:
[https://github.com/david-bai00/PrivyDrop](https://github.com/david-bai00/PrivyDrop)
Und OpenAI hat kürzlich eine sehr ähnliche Praxisperspektive veröffentlicht:
[https://openai.com/index/shipping-sora-for-android-with-codex/](https://openai.com/index/shipping-sora-for-android-with-codex/)
---
## Step 0: Grenzen und „done“ definieren (nicht mit Prompts starten)
Dieser Schritt macht nur eins: „Was heißt fertig?“ glasklar definieren. Sonst optimiert KI auf „läuft irgendwie“, nicht auf „läuft langfristig wartbar nach Teamstandard“.
Drei minimale Constraints:
1. **Boundary**: was niemals passieren darf (Privacy/ArchitekturRedlines, ProtokollKompatibilität, Guardrails für kritische Parameter)
2. **Scope**: ein Ziel pro Änderung, keine „wenn ich schon dabei bin…“
3. **Done**: Build/Tests + manuelle RegressionCheckliste müssen stehen
In einem Satz zusammengefasst (und an den Anfang jeder Anfrage):
```text
Ein Ziel, zuerst der Plan; Privacy/ArchitekturRedlines nie brechen; done heißt: Build grün + RegressionChecklist.
```
---
## ❌ Häufige AntiPatterns (bitte vermeiden)
Drei Klassiker:
1. **„Ändere den Code“ ohne Plan**
- Folge: 10 Dateien später stellst du fest, dass die Richtung falsch war—Rollback wird teuer
- Besser: zuerst ChangePlan, Implementierung erst nach Approval
2. **Alle Dokus in den Prompt kippen**
- Folge: KontextOverload; die KI verliert das Wesentliche (findet nicht mal Entry Points)
- Besser: HighSignalIndex + CodeMap
3. **„Nebenbei optimieren“ erlauben**
- Folge: ein PR mit mehreren Zielen; Review wird schwer, Bugs schwerer revertierbar
- Besser: SingleScope, minimal, gut rollbackbar
---
## Step 1: `AGENTS.md` schreiben (harte Constraints, stabil wiederverwendet)
Sieh `AGENTS.md` als maschinenlesbare Version eurer „Defaults“ und „Red Lines“. Nicht Theorie—sondern **wiederverwendbare Regeln pro Session**.
In PrivyDrop reichen fünf Punkte:
- Plan first: `AGENTS.en.md`
- One change, one purpose: `AGENTS.en.md`
- Privacy & architecture red line: `AGENTS.en.md`
- Docs must stay in sync: `AGENTS.en.md`
- Verification required: `AGENTS.en.md`
Datei: [AGENTS.en.md](https://github.com/david-bai00/PrivyDrop/blob/main/AGENTS.en.md)
Minimale StarterStruktur:
```md
# AGENTS — Repo Rules
First Principles
- Plan-first: Propose a change plan and get approval before writing code
- Single-scope: One PR solves one goal; avoid “while Im here” fixes
- Redlines: Never cross privacy/architecture/protocol/key-parameter guardrails
- Docs-sync: Keep the playbook docs in sync when entry points/flows/interfaces change
- Validation: Must include build/tests and key manual regression checklist
```
### Mehrsprachigkeit
Pragmatischer Ansatz:
- `AGENTS.en.md` als kanonische Version
- Lokalisierte Varianten nach Bedarf (z. B. `AGENTS.<locale>.md`)
- Nach dem Clone lokal den passenden Symlink setzen:
```bash
# English users
ln -s AGENTS.en.md AGENTS.md
```
- `AGENTS.md` in `.gitignore`, um SymlinkKonflikte zu vermeiden
> 💡 **KernInsight**
> Zuverlässige KIZusammenarbeit entsteht nicht durch „bessere Prompts“, sondern indem Constraints Teil des Repos werden. `AGENTS.md` macht Regeln wiederverwendbar, der AI Playbook macht Kontext langlebig.
---
## Step 2: `docs/ai-playbook/index.md` schreiben (HighSignalEinstieg)
Ein Hauptgrund für Drift: **KI kennt eure echten Einstiegspunkte nicht**. Dann werden Dateien „erraten“ statt gezielt gefunden.
Das IndexDokument soll:
- in 30 Sekunden lesbar sein (Snapshot + LinkIndex)
- per Klick zu code-map / flows / collab-rules führen
Referenz: [docs/ai-playbook/index.md](https://github.com/david-bai00/PrivyDrop/blob/main/docs/ai-playbook/index.md)
MinimalTemplate:
```md
# AI Playbook — Index
## Project Snapshot
- Stack: Next.js / Node / ...
- Red lines: ...
## Document Index
- Code map: docs/ai-playbook/code-map.md
- Key flows: docs/ai-playbook/flows.md
- Collaboration rules: docs/ai-playbook/collab-rules.md
```
---
## Step 3: `code-map.md` schreiben (wo ändern)
Ziel: schnelle Orientierung, nicht Vollständigkeit.
- nur Schlüsselverzeichnisse und EntryFiles
- pro EntryFile ein Satz: Verantwortlichkeit
- bei einer Anfrage: erst 38 Kandidaten aus der CodeMap, dann DeepDive
Referenz: [docs/ai-playbook/code-map.md](https://github.com/david-bai00/PrivyDrop/blob/main/docs/ai-playbook/code-map.md)
Optional: „Common requests → Entry Points“:
```md
Common request routing
- New page / SEO: frontend/app/**/page.tsx + metadata.ts
- i18n copy: frontend/constants/messages/*
- Blog: frontend/content/blog/* + frontend/lib/blog.ts
```
---
## Step 4: `flows.md` schreiben (wie es läuft)
Wenn code-map „wo“ beantwortet, beantwortet flows „wie“. Das verhindert KIVoodoo:
- Sequenz + Invarianten => weniger „BauchgefühlPatches“
- DebugPitfalls werden zur wiederverwendbaren Checklist
Referenz: [docs/ai-playbook/flows.md](https://github.com/david-bai00/PrivyDrop/blob/main/docs/ai-playbook/flows.md)
Mindestens enthalten:
1. **Key flow / sequence** (Mermaid wenn sinnvoll)
2. **DebugCheckliste**
3. **MicroPlanTemplate** (Planfirst erzwingen)
---
## Step 5: „Plan first“ erzwingen (Plan = MiniDesignDoc)
Der echte Hebel: Reviews nach vorne ziehen—vom „Diff lesen“ zum „Plan lesen“.
Template in `collab-rules.md` fixieren:
[docs/ai-playbook/collab-rules.md](https://github.com/david-bai00/PrivyDrop/blob/main/docs/ai-playbook/collab-rules.md)
```text
Title: <short, clear title>
Goals
- <what you want to achieve>
Scope / Files
- <list of files youll change/add + why>
Approach
- <implementation plan and key design points>
Risks & Mitigations
- <risk> → <mitigation>
Acceptance Criteria
- <verifiable acceptance items>
Rollback
- <how to revert quickly>
Docs to Update
- docs/ai-playbook/index.md / code-map.md / flows.md / collab-rules.md / others?
Validation
- Build: next build
- Manual: <key cases & regression points>
```
Stabiler Ablauf:
1. index + code-map + flows lesen (readonly)
2. Zustand + Constraints in eigenen Worten restaten (einmal korrigieren)
3. ChangePlan schreiben (erst dann implementieren)
---
## Step 5.1: Context Endurance (Checkpoint → neuer Chat)
Bei langen Aufgaben sinkt Qualität oft. StandardMove: Zustand in eine Datei schreiben, dann im neuen Chat fortsetzen; oder Context vorher komprimieren.
```md
# Handoff
## Problem statement (35 sentences)
## Confirmed plan (bullets)
## Done / Not done
## Key files and entry points
## Red lines and invariants
## Acceptance & regression checklist
## Next-step checklist
```
---
## Step 6: Den Loop schließen (Agent wie ein neues Teammitglied behandeln)
Pipeline:
1. Anfrage → Constraints (`AGENTS.md`)
2. Navigation → Entry Points (`index + code-map`)
3. Alignment → Sequenzen (`flows`)
4. Plan → MiniDesignDoc (`collab-rules`)
5. Umsetzung → klein & singlescope
6. Verifikation → `next build` + manuelle Regression
7. Sync → PlaybookDocs aktuell halten
---
## 💬 PromptBeispiele (copyready)
---
**Role**
You are a senior Next.js full-stack engineer with strong product instincts. Your collaboration quality determines whether this repo can iterate sustainably—be thorough and professional.
**Task kickoff**
Please read `docs/ai-playbook/index.md` to understand the project context, code map, and collaboration rules. The current request is: "xxx".
**Working style**
Please deeply read relevant docs/code. Think systematically, ask clarifying questions, then propose analysis + a change plan for review. Implement only after approval.
---
## IndustryReferenz: OpenAI und Codex
[https://openai.com/index/shipping-sora-for-android-with-codex/](https://openai.com/index/shipping-sora-for-android-with-codex/)
---
## Minimale Ordnerstruktur (kopierbar)
```text
AGENTS.en.md # Canonical rules (English)
AGENTS.<locale>.md # Optional localized rules
AGENTS.md # Symlink (created locally after git clone)
docs/
ai-playbook/
index.md # High-signal entry point
code-map.md
flows.md
collab-rules.md
```
---
## Schluss
KIgestützte Entwicklung reduziert Rigorosität nicht—sie erhöht sie. Nachhaltige Geschwindigkeit kommt aus starken Constraints: Regeln externalisieren, plan-first, Flows dokumentieren, Kontext langlebig machen.
@@ -0,0 +1,381 @@
---
title: "Keep AI on Track: A Practical, Repeatable Collaboration Playbook (with Templates)"
description: "Tired of AI-written code going off the rails? Turn Codex/Claude into a real teammate with AGENTS.md, an AI Playbook, and a plan-first workflow—less rework, more maintainable code. Includes real Next.js examples."
date: "2025-12-26"
author: "david bai"
cover: "/blog-assets/privydrop-open-source.jpg"
tags:
["AI Collaboration", "Codex", "Engineering Process", "Open Source", "Next.js"]
status: "published"
---
![](/blog-assets/privydrop-open-source.jpg)
Have you ever been in this situation?
- You ask AI to fix a bug, and it “helpfully” changes unrelated code—then you end up reverting by hand
- You write a mountain of prompts, and AI still cant find the right files; it just “guesses”
- Halfway through a long chat, AI forgets the constraints and quality drops off a cliff
If you treat AI as “a faster search box,” these issues stay hidden. But the moment you treat AI as “a collaborator,” they hit delivery quality head-on.
This post walks through an **actionable engineering workflow** that turns AI collaboration from “prompt witchcraft” into a **repeatable process**. After adopting it in PrivyDrop, shipping features and fixing bugs got noticeably faster and steadier—not by taking bigger risks, but by doing less rework.
By the end, youll have a minimal structure you can copy into any repo:
- `AGENTS.md`: repo-level hard constraints (red lines, defaults, definition of done)
- `docs/ai-playbook/index.md`: a one-page, high-signal entry point
- `docs/ai-playbook/code-map.md`: a code map (where to change)
- `docs/ai-playbook/flows.md`: key flows (how it runs)
- `docs/ai-playbook/collab-rules.md`: collaboration rules + change-plan template (how we work)
All examples come from the open-source project PrivyDrop—feel free to follow along:
[https://github.com/david-bai00/PrivyDrop](https://github.com/david-bai00/PrivyDrop)
Also, OpenAI recently published a hands-on write-up with a very similar mindset:
[https://openai.com/index/shipping-sora-for-android-with-codex/](https://openai.com/index/shipping-sora-for-android-with-codex/)
---
## Step 0: Define boundaries and “done” (dont start with prompts)
This step does only one thing: make “what done looks like” explicit. Otherwise AI will do everything it can to make the code “run,” not to make it “run in the maintainable way your team expects.”
Start with three minimal constraints:
1. **Boundary**: what must never happen (privacy/architecture red lines, protocol compatibility, guardrails on key parameters)
2. **Scope**: one change, one goal—no “while Im here”
3. **Done**: build/tests/manual regression checklist must be written down
Compress them into a single sentence and put it at the top of every request:
```text
Single goal, plan first; never cross privacy/architecture red lines; done means it builds and includes a regression checklist.
```
---
## ❌ Common anti-patterns (avoid these traps)
Before we begin, here are the three most common wrong approaches:
1. **Tell AI to “change code” without a plan**
- Result: 10 files changed, then you realize the direction is wrong—rollback becomes painful
- Better: require a change plan first; implement only after approval
2. **Dump every document into the prompt**
- Result: context overload; AI cant see the signal (it cant even locate entry points)
- Better: provide a high-signal index + code map
3. **Let AI “optimize things on the side”**
- Result: one PR mixes multiple goals; review cost doubles; bugs get harder to roll back
- Better: single-scope changes that are easy to revert
---
## Step 1: Write `AGENTS.md` (repo-level hard constraints, consistently reused)
Think of `AGENTS.md` as a machine-readable version of your teams “defaults” and “red lines.” Its job isnt to explain theory—its to be **reapplied in every session**.
In PrivyDrop, five lines are enough to cover the core of engineering collaboration constraints:
- Plan first: `AGENTS.en.md`
- One change, one purpose: `AGENTS.en.md`
- Privacy & architecture red line: `AGENTS.en.md`
- Docs must stay in sync: `AGENTS.en.md`
- Verification required: `AGENTS.en.md`
File: [AGENTS.en.md](https://github.com/david-bai00/PrivyDrop/blob/main/AGENTS.en.md)
If you want a minimal starter, heres a good shape (keep it short, strict, and executable):
```md
# AGENTS — Repo Rules
First Principles
- Plan-first: Propose a change plan and get approval before writing code
- Single-scope: One PR solves one goal; avoid “while Im here” fixes
- Redlines: Never cross privacy/architecture/protocol/key-parameter guardrails
- Docs-sync: If flows/entry points/interfaces change, update the playbook docs
- Validation: Must include build/tests and key manual regression checklist
```
### Multi-language support
If your repo needs multilingual collaboration, a pragmatic pattern is:
- Keep `AGENTS.en.md` as the canonical version
- Add localized variants as needed (e.g. `AGENTS.<locale>.md`)
- After cloning, each contributor can create a language-specific symlink locally:
```bash
# English users
ln -s AGENTS.en.md AGENTS.md
```
- Add `AGENTS.md` to `.gitignore` to avoid symlink conflicts
> 💡 **Key insight**
> The secret of reliable AI collaboration isnt “better prompts.” Its “making constraints part of the repo.” `AGENTS.md` makes rules reusable, and the AI Playbook makes context durable.
---
## Step 2: Write `docs/ai-playbook/index.md` (a high-signal entry point)
One of the most common reasons AI goes off track: **it cant find your real entry points**. Then it “guesses” where to change things.
Your index page should do two things:
- Readable in 30 seconds: only “project snapshot + link index”
- One-click navigation: send readers/AI to code-map / flows / collab-rules
Reference implementation: [docs/ai-playbook/index.md](https://github.com/david-bai00/PrivyDrop/blob/main/docs/ai-playbook/index.md)
Minimal template (copy-pasteable):
```md
# AI Playbook — Index
## Project Snapshot
- Stack: Next.js / Node / ...
- Red lines: ...
## Document Index
- Code map: docs/ai-playbook/code-map.md
- Key flows: docs/ai-playbook/flows.md
- Collaboration rules: docs/ai-playbook/collab-rules.md
```
---
## Step 3: Write `code-map.md` (where to change: entry points + one-line responsibilities)
The code map is for “fast navigation,” not “teaching you how to implement.” The writing rules are simple:
- List only key directories and key entry files
- One sentence per entry file: what its responsible for
- When a new request arrives: hit 38 candidate files in the code map before deep reading
Reference implementation: [docs/ai-playbook/code-map.md](https://github.com/david-bai00/PrivyDrop/blob/main/docs/ai-playbook/code-map.md)
Optional: add a “common requests → entry points” cheat sheet to reduce search cost further:
```md
Common request routing
- New page / SEO: frontend/app/**/page.tsx + metadata.ts
- i18n copy: frontend/constants/messages/*
- Blog: frontend/content/blog/* + frontend/lib/blog.ts
```
How to generate (and iterate) a code map:
- First version: ask AI to summarize “directories + key entry points” for navigation—not completeness.
- Iteration: treat it as a living doc. Update it incrementally per PR/commit (file list), instead of rewriting it from scratch.
---
## Step 4: Write `flows.md` (how it runs: key sequences + debug points + micro-plan template)
If code-map answers “where to change,” flows answers “how it runs.” This is hugely valuable for AI:
- If you write down the sequence and invariants, AI stops “patching by vibes”
- You can compress past pitfalls into a reusable debug checklist
Reference implementation: [docs/ai-playbook/flows.md](https://github.com/david-bai00/PrivyDrop/blob/main/docs/ai-playbook/flows.md) (with split deep dives)
At minimum, include:
1. **Key flow / sequence** (Mermaid if useful)
2. **Debug checklist** (the most important logs/states)
3. **Micro-plan template** (force plan-first before coding)
How to generate (and iterate) flows:
- First version: ask AI to restate the end-to-end flow + key sequence + invariants. You review/correct (especially red lines and invariants), then commit it to docs.
- Iteration: keep it up to date incrementally when interfaces/sequences change.
---
## Step 5: Make “plan first” enforceable (a plan = a mini design doc)
This is where the speed-up really comes from: move the review earlier—from “reading diff” to “reading the plan.”
Put the plan template in `collab-rules.md` and treat it as a hard constraint.
PrivyDrop template: [docs/ai-playbook/collab-rules.md](https://github.com/david-bai00/PrivyDrop/blob/main/docs/ai-playbook/collab-rules.md)
You can reuse this structure directly (goals/scope/approach/risks/acceptance/rollback/validation):
```text
Title: <short, clear title>
Goals
- <what you want to achieve>
Scope / Files
- <list of files youll change/add + why>
Approach
- <implementation plan and key design points>
Risks & Mitigations
- <risk> → <mitigation>
Acceptance Criteria
- <verifiable acceptance items>
Rollback
- <how to revert quickly>
Docs to Update
- docs/ai-playbook/index.md / code-map.md / flows.md / collab-rules.md / others?
Validation
- Build: next build
- Manual: <key cases & regression points>
```
In practice, a steadier workflow is:
1. Read playbook index + code-map + flows (read-only, no code changes)
2. Restate the current state and constraints in your own words (you correct once)
3. Produce a change plan (implementation only after approval)
> ⚠️ **Pitfall avoidance**
> Correct direction during the plan stage; avoid building and then tearing down. Single-scope changes keep rollback cheap and merging easier.
---
## Step 5.1: Context endurance (checkpoint → new chat)
In long tasks, output quality dropping is almost inevitable. Make “endurance” a standard move: when you see guessing, forgotten constraints, or drift—write the state into a file, then continue in a new chat; or run a “compress/summarize” step to shrink context before continuing.
Minimal handoff template (put it in `docs/ai-playbook/handoff.md` or a temporary file):
```md
# Handoff
## Problem statement (35 sentences)
## Confirmed plan (bullets)
## Done / Not done
## Key files and entry points
## Red lines and invariants
## Acceptance & regression checklist
## Next-step checklist
```
The goal isnt “beautiful docs.” Its moving context from the chat window into a file that the next session can read reliably.
---
## Step 6: Close the collaboration loop (treat the agent like a new teammate)
Once you have the pieces above, collaboration becomes a stable pipeline:
1. Request → constraints (cite `AGENTS.md`)
2. Navigation → entry points (cite `index + code-map`)
3. Alignment → sequences (cite `flows`)
4. Planning → mini design doc (cite `collab-rules` template)
5. Implementation → small, single-scope change (easy rollback)
6. Verification → `next build` + key manual regression points
7. Sync → keep playbook docs up to date
The most visible benefit for me: shipping features and fixing bugs is faster and steadier. More importantly, “fast” comes from **less rework**, not more risk:
- Correct direction at plan time; avoid throwing work away
- Single-scope changes keep rollback cheap and merges easy
- Flows turn past pitfalls into a checklist you can reuse
If you want a gate, put these two questions into your PR template:
- Does this PR include a change plan link/summary?
- Did you update `docs/ai-playbook/*` (if entry points/flows/interfaces changed)?
## 💬 Prompt examples (ready to copy)
Once your AI Playbook exists, you can start a collaboration session with something like this:
---
**Role**
You are a senior Next.js full-stack engineer with strong product instincts. Your collaboration quality determines whether this repo can iterate sustainably—be thorough and professional.
**Task kickoff**
Please read `docs/ai-playbook/index.md` to understand the project context, code map, and collaboration rules. The current request is: "xxx".
**Working style**
Please deeply read relevant docs/code. Think systematically, ask clarifying questions, then propose analysis + a change plan for review. Implement only after approval.
---
**Why this works**
- **Role**: sets quality bar and responsibility boundaries
- **Kickoff**: forces reading the playbook instead of guessing
- **Working style**: makes “plan first” part of the workflow
---
## Industry reference: How OpenAI uses Codex to run a sprint
In “How we used Codex to build Sora for Android in 28 days,” OpenAI describes a workflow that matches this playbook closely:
[https://openai.com/index/shipping-sora-for-android-with-codex/](https://openai.com/index/shipping-sora-for-android-with-codex/)
Key points to align with:
- Treat the agent like a new senior engineer: capable, but needs clear architecture/constraints
- Externalize rules: maintaining a strong `AGENTS.md` pays off
- Plan before real changes: plans are mini design docs—debug the plan before debugging the code
- Context endurance: when you hit context limits, write plans to files for the next session
- Multi-session parallelism: its closer to “managing a team” than using a single tool
Android and web are different, but the method transfers: **improve inputs, and outputs stabilize**.
---
## A minimal directory structure you can copy
```text
AGENTS.en.md # Canonical rules (English)
AGENTS.<locale>.md # Optional localized rules
AGENTS.md # Symlink (created locally after git clone)
docs/
ai-playbook/
index.md # High-signal entry point
code-map.md
flows.md
collab-rules.md
```
If you already have docs scattered everywhere: start with `index.md` to unify entry points; then fill in code-map/flows/templates.
---
## 🚀 Next steps
1. **Start now**: copy the minimal structure into your repo and begin with `AGENTS.md`
2. **Reference implementation**: visit [PrivyDrop GitHub](https://github.com/david-bai00/PrivyDrop) and browse the full AI Playbook
3. **Feedback**: if this helps (or you hit pitfalls), open an issue on GitHub or leave a comment
4. **Star**: if its valuable, consider starring PrivyDrop 🌟
---
## Closing
AI-assisted development doesnt reduce the need for rigor—it increases it. The sustainable speed-up doesnt come from longer prompts, but from stronger engineering constraints: externalize rules, plan first, codify flows, and make context durable.
If you want to go further, this can evolve into a “copyable repo scaffold”: PR templates, issue templates, and a ready-to-use `AGENTS.md` + playbook starter kit.
@@ -0,0 +1,367 @@
---
title: "Que la IA no se desvíe: un método de colaboración realmente aplicable (con plantillas)"
description: "¿La IA escribe código y se sale del tema? Convierte Codex/Claude en un compañero de equipo con AGENTS.md, un AI Playbook y un flujo plan-first: menos retrabajo, más mantenibilidad. Con ejemplos reales en Next.js."
date: "2025-12-26"
author: "david bai"
cover: "/blog-assets/privydrop-open-source.jpg"
tags:
["Colaboración con IA", "Codex", "Proceso de ingeniería", "Código abierto", "Next.js"]
status: "published"
---
![](/blog-assets/privydrop-open-source.jpg)
¿Te suena alguno de estos escenarios?
- Le pides a la IA que arregle un bug, pero termina tocando código que no tiene nada que ver—y luego te toca revertir a mano
- Escribes un montón de prompts y aun así no encuentra el archivo correcto; acaba “adivinando”
- A mitad de una conversación larga, empieza a olvidar restricciones y la calidad se desploma
Si tratas la IA como “un buscador más rápido”, estos problemas no se notan. Pero cuando la tratas como “un compañero de colaboración”, se convierten en un factor directo de calidad y entrega.
En este artículo muestro un **método de ingeniería accionable** para que la colaboración con IA deje de ser “magia de prompts” y se convierta en un **proceso repetible**. En PrivyDrop, después de aplicarlo, el ritmo de nuevas funciones y fixes se volvió notablemente más rápido y estable—no por asumir más riesgo, sino por reducir el retrabajo.
Al final tendrás una estructura mínima que puedes copiar a cualquier repositorio:
- `AGENTS.md`: restricciones duras a nivel de repo (líneas rojas, valores por defecto, definición de done)
- `docs/ai-playbook/index.md`: entrada de una sola página (alta señal)
- `docs/ai-playbook/code-map.md`: mapa de código (dónde tocar)
- `docs/ai-playbook/flows.md`: flujos clave (cómo corre)
- `docs/ai-playbook/collab-rules.md`: reglas de colaboración + plantilla de plan de cambio (cómo trabajamos)
Todos los ejemplos vienen del repo open source PrivyDrop (puedes comparar con la implementación):
[https://github.com/david-bai00/PrivyDrop](https://github.com/david-bai00/PrivyDrop)
Y esta práctica de OpenAI tiene una filosofía muy similar:
[https://openai.com/index/shipping-sora-for-android-with-codex/](https://openai.com/index/shipping-sora-for-android-with-codex/)
---
## Step 0: Define límites y “done” (no empieces por el prompt)
Este paso hace una sola cosa: dejar claro qué significa “terminado”. Si no, la IA va a optimizar por “que funcione”, no por “que funcione de forma mantenible como espera tu equipo”.
Define tres restricciones mínimas:
1. **Boundary (límite)**: lo que nunca debe ocurrir (líneas rojas de privacidad/arquitectura, compatibilidad de protocolo, guardrails de parámetros críticos)
2. **Scope (alcance)**: un objetivo por cambio; prohibido “ya que estoy, optimizo…”
3. **Done (hecho)**: build/tests + checklist de regresión manual deben quedar escritos
Resúmelo en una frase y ponlo al inicio de cada solicitud:
```text
Un solo objetivo, primero el plan; no cruzar líneas rojas de privacidad/arquitectura; “done” significa que compila y trae checklist de regresión.
```
---
## ❌ Antipatrones comunes (evita estas trampas)
Antes de empezar, tres errores típicos:
1. **Pedirle a la IA “cambia el código” sin plan**
- Resultado: cambia 10 archivos y luego descubres que la dirección era incorrecta; revertir duele
- Correcto: exigir un plan primero; implementar solo tras aprobarlo
2. **Meter todos los documentos en el prompt**
- Resultado: explosión de contexto; la IA pierde la señal (ni encuentra los entry points)
- Correcto: usar index + code-map como navegación de alta señal
3. **Dejar que la IA “arregle cosas de paso”**
- Resultado: un PR mezcla múltiples objetivos; el review se encarece y los bugs son más difíciles de revertir
- Correcto: single-scope, cambios mínimos y reversibles
---
## Step 1: Escribe `AGENTS.md` (restricciones duras, reutilizables)
Piensa en `AGENTS.md` como la versión “legible por máquina” de los valores por defecto y líneas rojas del equipo. No es teoría: es **un mecanismo de reutilización**.
En PrivyDrop, cinco puntos bastan para cubrir el núcleo:
- Plan first: `AGENTS.en.md`
- One change, one purpose: `AGENTS.en.md`
- Privacy & architecture red line: `AGENTS.en.md`
- Docs must stay in sync: `AGENTS.en.md`
- Verification required: `AGENTS.en.md`
Archivo: [AGENTS.en.md](https://github.com/david-bai00/PrivyDrop/blob/main/AGENTS.en.md)
Plantilla mínima sugerida (corta, estricta y accionable):
```md
# AGENTS — Repo Rules
First Principles
- Plan-first: Propose a change plan and get approval before writing code
- Single-scope: One PR solves one goal; avoid “while Im here” fixes
- Redlines: Never cross privacy/architecture/protocol/key-parameter guardrails
- Docs-sync: Keep the playbook docs in sync when entry points/flows/interfaces change
- Validation: Must include build/tests and key manual regression checklist
```
### Soporte multi-idioma
Un patrón práctico:
- Mantén `AGENTS.en.md` como versión canónica
- Añade variantes localizadas si hace falta (p. ej. `AGENTS.<locale>.md`)
- Tras clonar, cada persona crea el symlink local según idioma:
```bash
# English users
ln -s AGENTS.en.md AGENTS.md
```
- Añade `AGENTS.md` a `.gitignore` para evitar conflictos de symlinks
> 💡 **Idea clave**
> La colaboración con IA no se arregla con “mejores prompts”, sino con “restricciones dentro del repo”. `AGENTS.md` hace que las reglas se reutilicen; el AI Playbook hace que el contexto dure.
---
## Step 2: Escribe `docs/ai-playbook/index.md` (entrada de alta señal)
Una razón común por la que la IA se desvía: **no sabe dónde están tus entry points reales**. Entonces propone cambios por suposiciones.
El index debe lograr dos cosas:
- Se lee en 30 segundos: solo “snapshot del proyecto + índice de enlaces”
- Navegación de un clic: llevar a code-map / flows / collab-rules
Referencia: [docs/ai-playbook/index.md](https://github.com/david-bai00/PrivyDrop/blob/main/docs/ai-playbook/index.md)
Plantilla mínima:
```md
# AI Playbook — Index
## Project Snapshot
- Stack: Next.js / Node / ...
- Red lines: ...
## Document Index
- Code map: docs/ai-playbook/code-map.md
- Key flows: docs/ai-playbook/flows.md
- Collaboration rules: docs/ai-playbook/collab-rules.md
```
---
## Step 3: Escribe `code-map.md` (dónde tocar)
El objetivo es “localizar rápido”, no “enseñar a implementar”:
- Solo directorios clave y archivos de entrada clave
- Una frase por archivo: su responsabilidad
- Al llegar una solicitud: identifica 38 candidatos en code-map antes de leer en profundidad
Referencia: [docs/ai-playbook/code-map.md](https://github.com/david-bai00/PrivyDrop/blob/main/docs/ai-playbook/code-map.md)
Opcional: añade una tabla de “solicitud común → entry points”:
```md
Common request routing
- New page / SEO: frontend/app/**/page.tsx + metadata.ts
- i18n copy: frontend/constants/messages/*
- Blog: frontend/content/blog/* + frontend/lib/blog.ts
```
Cómo generarlo y mantenerlo:
- Primera versión: que la IA resuma “directorios + entry points” para navegación, no para exhaustividad
- Iteración: actualiza incrementalmente por PR/commit; evita reescrituras completas
---
## Step 4: Escribe `flows.md` (cómo corre)
Si code-map responde “dónde tocar”, flows responde “cómo corre”. Para la IA, esto es oro:
- Con secuencia + invariantes claros, deja de “parchear por intuición”
- Los pitfalls históricos se vuelven checklist reutilizable
Referencia: [docs/ai-playbook/flows.md](https://github.com/david-bai00/PrivyDrop/blob/main/docs/ai-playbook/flows.md)
Incluye al menos:
1. **Secuencia / flow clave** (Mermaid si hace falta)
2. **Checklist de debug** (logs/estados cruciales)
3. **Plantilla de micro-plan** (plan-first antes de tocar código)
Guía de creación/iteración:
- Primera versión: que la IA reexponga el flujo E2E + secuencia clave + invariantes; tú corriges (sobre todo red lines e invariantes) y lo dejas en docs
- Iteración: actualizar por cambios en interfaces/secuencias
---
## Step 5: Haz “plan first” obligatorio (un plan = mini diseño)
Aquí está el acelerador: mover el review de “leer el diff” a “leer el plan”.
Fija una plantilla en `collab-rules.md` y úsala como regla dura.
Plantilla PrivyDrop: [docs/ai-playbook/collab-rules.md](https://github.com/david-bai00/PrivyDrop/blob/main/docs/ai-playbook/collab-rules.md)
Estructura reutilizable:
```text
Title: <short, clear title>
Goals
- <what you want to achieve>
Scope / Files
- <list of files youll change/add + why>
Approach
- <implementation plan and key design points>
Risks & Mitigations
- <risk> → <mitigation>
Acceptance Criteria
- <verifiable acceptance items>
Rollback
- <how to revert quickly>
Docs to Update
- docs/ai-playbook/index.md / code-map.md / flows.md / collab-rules.md / others?
Validation
- Build: next build
- Manual: <key cases & regression points>
```
Un flujo más estable en la práctica:
1. Leer index + code-map + flows (solo lectura, sin tocar código)
2. Reexplicar estado actual y restricciones (tú corriges una vez)
3. Escribir el plan de cambio (implementación solo tras aprobación)
> ⚠️ **Evita pitfalls**
> Corrige la dirección en la fase de plan; evita construir y luego tirar. Single-scope baja el costo de rollback y facilita el merge.
---
## Step 5.1: Resistencia de contexto (checkpoint → chat nuevo)
En tareas largas, la caída de calidad es casi inevitable. Conviértelo en un hábito: cuando aparezcan suposiciones, olvidos o deriva, escribe el estado en un archivo y continúa en un chat nuevo; o comprime/resume el contexto antes de seguir.
Plantilla mínima de handoff (en `docs/ai-playbook/handoff.md` o archivo temporal):
```md
# Handoff
## Problem statement (35 sentences)
## Confirmed plan (bullets)
## Done / Not done
## Key files and entry points
## Red lines and invariants
## Acceptance & regression checklist
## Next-step checklist
```
No es “escribir bonito”: es hacer que el contexto sea reutilizable fuera del chat.
---
## Step 6: Cierra el loop (trata al agente como a un nuevo compañero)
Con todo lo anterior, la colaboración se vuelve una tubería estable:
1. Solicitud → restricciones (citar `AGENTS.md`)
2. Localización → entry points (citar `index + code-map`)
3. Alineación → secuencia (citar `flows`)
4. Plan → mini diseño (plantilla en `collab-rules`)
5. Implementación → cambios pequeños y single-scope (rollback fácil)
6. Verificación → `next build` + regresiones clave
7. Sincronización → docs del playbook al día
El beneficio más visible: más velocidad y estabilidad. Y esa velocidad viene de **menos retrabajo**:
- Corregir dirección al planear, no al final
- Single-scope hace barato el rollback y fácil el merge
- Flows convierte pitfalls en checklist
Si quieres una puerta de control, añade estas dos preguntas al PR template:
- ¿Incluye link/resumen del plan de cambio?
- ¿Actualizaste `docs/ai-playbook/*` si cambiaste entry points/flows/interfaces?
## 💬 Ejemplos de prompt (listos para copiar)
---
**Role**
You are a senior Next.js full-stack engineer with strong product instincts. Your collaboration quality determines whether this repo can iterate sustainably—be thorough and professional.
**Task kickoff**
Please read `docs/ai-playbook/index.md` to understand the project context, code map, and collaboration rules. The current request is: "xxx".
**Working style**
Please deeply read relevant docs/code. Think systematically, ask clarifying questions, then propose analysis + a change plan for review. Implement only after approval.
---
## Referencia de industria: cómo OpenAI organiza un sprint con Codex
OpenAI describe un flujo muy parecido aquí:
[https://openai.com/index/shipping-sora-for-android-with-codex/](https://openai.com/index/shipping-sora-for-android-with-codex/)
Puntos a alinear:
- Tratar al agente como un “nuevo senior”: capaz, pero necesita arquitectura/limitaciones claras
- Externalizar reglas: mantener un `AGENTS.md` fuerte compensa
- Plan antes de cambios reales: depura el plan antes que el código
- Resistencia de contexto: cuando llegues al límite, escribe el plan en un archivo y continúa
- Multi-sesión en paralelo: más parecido a “gestionar un equipo” que a usar una sola herramienta
---
## Estructura mínima de directorios (copiable)
```text
AGENTS.en.md # Canonical rules (English)
AGENTS.<locale>.md # Optional localized rules
AGENTS.md # Symlink (created locally after git clone)
docs/
ai-playbook/
index.md # High-signal entry point
code-map.md
flows.md
collab-rules.md
```
Si ya tienes docs dispersas: empieza por `index.md` para unificar el acceso; luego completa code-map/flows/plantillas.
---
## 🚀 Próximos pasos
1. **Empieza ya**: copia la estructura mínima y comienza por `AGENTS.md`
2. **Implementación de referencia**: [PrivyDrop GitHub](https://github.com/david-bai00/PrivyDrop)
3. **Feedback**: abre un issue o comenta si te sirve (o te atoras)
4. **Star**: si te aporta valor, deja una estrella 🌟
---
## Cierre
El desarrollo asistido por IA no reduce la necesidad de rigor; la incrementa. La velocidad sostenible no viene de prompts más largos, sino de restricciones más fuertes: reglas externalizadas, plan-first, flows codificados y contexto durable.
@@ -0,0 +1,162 @@
---
title: "Empêcher lIA de dérailler : une méthode de collaboration vraiment applicable (avec templates)"
description: "Votre IA part dans tous les sens quand elle code ? Transformez Codex/Claude en vrai coéquipier grâce à AGENTS.md, un AI Playbook et un workflow plan-first : moins de retours en arrière, plus de maintenabilité. Exemples Next.js inclus."
date: "2025-12-26"
author: "david bai"
cover: "/blog-assets/privydrop-open-source.jpg"
tags:
["Collaboration IA", "Codex", "Processus dingénierie", "Open Source", "Next.js"]
status: "published"
---
![](/blog-assets/privydrop-open-source.jpg)
Vous avez déjà vécu ça ?
- Vous demandez à lIA de corriger un bug et elle modifie aussi du code hors sujet — puis vous devez revert à la main
- Vous écrivez des tonnes de prompts, mais elle ne trouve pas les bons fichiers et finit par “deviner”
- Au milieu dune longue discussion, elle oublie les contraintes et la qualité chute brutalement
Si vous utilisez lIA comme “une recherche plus rapide”, ces problèmes restent invisibles. Mais dès que vous la considérez comme “un coéquipier”, ils impactent directement la qualité de livraison.
Cet article présente une **méthode dingénierie exécutable** pour transformer la collaboration IA — de la “magie de prompts” vers un **processus reproductible**. Dans PrivyDrop, après adoption, lajout de features et les bugfixes sont devenus plus rapides et plus stables : non pas en prenant plus de risques, mais en réduisant les retours en arrière.
À la fin, vous obtenez une structure minimale copiable dans nimporte quel repo :
- `AGENTS.md` : contraintes du repo (lignes rouges, valeurs par défaut, définition de done)
- `docs/ai-playbook/index.md` : point dentrée 1 page (haute densité de signal)
- `docs/ai-playbook/code-map.md` : carte du code (où changer)
- `docs/ai-playbook/flows.md` : flows clés (comment ça tourne)
- `docs/ai-playbook/collab-rules.md` : règles de collaboration + template de plan de changement (comment on travaille)
Tous les exemples viennent du repo open source PrivyDrop :
[https://github.com/david-bai00/PrivyDrop](https://github.com/david-bai00/PrivyDrop)
OpenAI a aussi publié un retour dexpérience très proche dans lesprit :
[https://openai.com/index/shipping-sora-for-android-with-codex/](https://openai.com/index/shipping-sora-for-android-with-codex/)
---
## Step 0 : définir les limites et le “done” (ne pas commencer par les prompts)
Ce step fait une seule chose : rendre explicite ce que “terminé” veut dire. Sinon, lIA optimise pour “ça marche”, pas pour “ça marche durablement et maintenablement”.
Trois contraintes minimales :
1. **Boundary** : ce qui ne doit jamais arriver (privacy/architecture red lines, compatibilité de protocole, guardrails de paramètres critiques)
2. **Scope** : un objectif par changement, pas de “tant quon y est…”
3. **Done** : build/tests + checklist de régression manuelle à écrire
À mettre en une phrase en tête de chaque demande :
```text
Un seul objectif, plan dabord ; ne jamais franchir les red lines privacy/architecture ; done = build OK + checklist de régression.
```
---
## ❌ Antipatterns fréquents
1. **Demander à lIA de “modifier le code” sans plan**
2. **Tout jeter dans le prompt (overload de contexte)**
3. **Laisser lIA “optimiser au passage”**
Le remède est toujours le même : index + code-map + flows, puis un plan approuvé avant dimplémenter.
---
## Step 1 : écrire `AGENTS.md` (contraintes du repo, réutilisables)
`AGENTS.md` = la version “machinereadable” de vos règles et lignes rouges. Dans PrivyDrop, cinq points suffisent :
- Plan first : `AGENTS.en.md`
- One change, one purpose : `AGENTS.en.md`
- Privacy & architecture red line : `AGENTS.en.md`
- Docs must stay in sync : `AGENTS.en.md`
- Verification required : `AGENTS.en.md`
Fichier : [AGENTS.en.md](https://github.com/david-bai00/PrivyDrop/blob/main/AGENTS.en.md)
```md
# AGENTS — Repo Rules
First Principles
- Plan-first: Propose a change plan and get approval before writing code
- Single-scope: One PR solves one goal; avoid “while Im here” fixes
- Redlines: Never cross privacy/architecture/protocol/key-parameter guardrails
- Docs-sync: Keep the playbook docs in sync when entry points/flows/interfaces change
- Validation: Must include build/tests and key manual regression checklist
```
---
## Step 2 : `docs/ai-playbook/index.md` (entrée hautesignal)
Référence : [docs/ai-playbook/index.md](https://github.com/david-bai00/PrivyDrop/blob/main/docs/ai-playbook/index.md)
---
## Step 3 : `code-map.md` (où changer)
Référence : [docs/ai-playbook/code-map.md](https://github.com/david-bai00/PrivyDrop/blob/main/docs/ai-playbook/code-map.md)
---
## Step 4 : `flows.md` (comment ça tourne)
Référence : [docs/ai-playbook/flows.md](https://github.com/david-bai00/PrivyDrop/blob/main/docs/ai-playbook/flows.md)
---
## Step 5 : rendre “plan first” obligatoire
Template : [docs/ai-playbook/collab-rules.md](https://github.com/david-bai00/PrivyDrop/blob/main/docs/ai-playbook/collab-rules.md)
---
## 💬 Prompt de démarrage (copiable)
---
**Role**
You are a senior Next.js full-stack engineer with strong product instincts. Your collaboration quality determines whether this repo can iterate sustainably—be thorough and professional.
**Task kickoff**
Please read `docs/ai-playbook/index.md` to understand the project context, code map, and collaboration rules. The current request is: "xxx".
**Working style**
Please deeply read relevant docs/code. Think systematically, ask clarifying questions, then propose analysis + a change plan for review. Implement only after approval.
---
## Référence OpenAI
[https://openai.com/index/shipping-sora-for-android-with-codex/](https://openai.com/index/shipping-sora-for-android-with-codex/)
---
## Structure minimale (copiable)
```text
AGENTS.en.md # Canonical rules (English)
AGENTS.<locale>.md # Optional localized rules
AGENTS.md # Symlink (created locally after git clone)
docs/
ai-playbook/
index.md # High-signal entry point
code-map.md
flows.md
collab-rules.md
```
---
## Conclusion
Le développement assisté par IA ne réduit pas lexigence de rigueur : il laugmente. La vitesse durable vient de contraintes claires, de plans approuvés, de flows documentés et dun contexte qui survit aux conversations.
@@ -0,0 +1,381 @@
---
title: "AIを迷走させない:すぐ使える協働のエンジニアリング手法(テンプレ付き)"
description: "AIにコードを書かせると脱線しがち?AGENTS.md・AI Playbook・Plan-first の型で、Codex/Claude を“協働できる相棒”に。手戻りを減らし、保守性を上げる。Next.js 実戦例つき。"
date: "2025-12-26"
author: "david bai"
cover: "/blog-assets/privydrop-open-source.jpg"
tags:
["AI協働", "Codex", "エンジニアリングプロセス", "オープンソース", "Next.js"]
status: "published"
---
![](/blog-assets/privydrop-open-source.jpg)
こんな経験はありませんか?
- AI にバグ修正を頼んだら、関係ないコードまで“親切に”直されて、結局手で戻す羽目になる
- プロンプトを山ほど書いても、AI が正しいファイルに辿り着けず、最後は“当てずっぽう”
- 会話が長くなると制約を忘れはじめ、出力品質が急降下する
AI を「速い検索ボックス」として使うなら、これらの問題は表面化しません。けれど AI を「一緒に作る相棒」として扱った瞬間、納期と品質に直撃します。
この記事では、AI 協働を「プロンプトの呪文」から **再現可能なプロセス** に変える、**実行可能なエンジニアリング手法** を紹介します。PrivyDrop では、この型を導入してから機能追加・バグ修正のテンポが明らかに速く、そして安定しました。速さの理由は冒険ではなく、**手戻りが減った** ことです。
最終的に、どんなリポジトリにもそのまま移植できる最小セットが手に入ります:
- `AGENTS.md`:プロジェクトのハード制約(レッドライン、デフォルト、Done の定義)
- `docs/ai-playbook/index.md`:高シグナルな入口(1ページ索引)
- `docs/ai-playbook/code-map.md`:コード地図(どこを触るか)
- `docs/ai-playbook/flows.md`:重要フロー(どう動くか)
- `docs/ai-playbook/collab-rules.md`:協働ルール + 変更計画テンプレ(どう進めるか)
例はすべて OSS の PrivyDrop から。実装と照らし合わせて読めます:
[https://github.com/david-bai00/PrivyDrop](https://github.com/david-bai00/PrivyDrop)
さらに、OpenAI の実践記事も考え方が近いです:
[https://openai.com/index/shipping-sora-for-android-with-codex/](https://openai.com/index/shipping-sora-for-android-with-codex/)
---
## Step 0:境界と Done を先に決める(プロンプトから始めない)
このステップでやることは 1 つだけ。「何をもって完了とするか」を明文化します。そうしないと AI は、とにかくコードを「動かす」方向に全力を出してしまい、チームが求める「長期的に保守できる形で動かす」にはなりません。
まずは最小限の 3 つを定義します:
1. **Boundary(境界)**:絶対にやってはいけないこと(プライバシー/アーキテクチャのレッドライン、プロトコル互換、重要パラメータの護栏)
2. **Scope(範囲)**:一度に一つの目的。「ついで修正」禁止
3. **Done(完了条件)**:ビルド/テスト/手動回帰チェックは必ず書く
短く 1 文に圧縮して、毎回の依頼の冒頭に置きます:
```text
目的は単一、まず計画。プライバシー/アーキテクチャのレッドラインを越えない。完了は build が通り、回帰チェックが書かれていること。
```
---
## ❌ よくあるアンチパターン:ここは踏まない
始める前に、ありがちな 3 つの間違い:
1. **計画なしで AI に「コードを直して」と言う**
- 結果:10 ファイル変わってから方向違いに気づき、戻すコストが爆発する
- 正解:先に変更計画を出させ、承認してから実装
2. **ドキュメントを全部 AI に投げる**
- 結果:文脈が飽和して要点が消える(入口ファイルすら見つけられない)
- 正解:高シグナルな index + code-map に絞る
3. **AI に「ついでに最適化」させる**
- 結果:PR が複数目的で混ざり、レビューが重く、バグの切り戻しも難しい
- 正解:単一テーマで最小・可逆に
---
## Step 1`AGENTS.md` を書く(ハード制約を強制的に再利用する)
`AGENTS.md` は、チームの「デフォルト」と「レッドライン」を機械可読にしたものだと捉えると分かりやすいです。目的は理屈の説明ではなく、**毎回の会話で確実に効かせること**。
PrivyDrop では、工学的な協働に必要な要点は 5 行に集約できます:
- Plan first`AGENTS.en.md`
- One change, one purpose`AGENTS.en.md`
- Privacy & architecture red line`AGENTS.en.md`
- Docs must stay in sync`AGENTS.en.md`
- Verification required`AGENTS.en.md`
ファイル: [AGENTS.en.md](https://github.com/david-bai00/PrivyDrop/blob/main/AGENTS.en.md)
ゼロから最小版を作るなら、例えばこの形(短く・硬く・実行可能に):
```md
# AGENTS — Repo Rules
First Principles
- Plan-first: Propose a change plan and get approval before writing code
- Single-scope: One PR solves one goal; avoid “while Im here” fixes
- Redlines: Never cross privacy/architecture/protocol/key-parameter guardrails
- Docs-sync: Keep the playbook docs in sync when entry points/flows/interfaces change
- Validation: Must include build/tests and key manual regression checklist
```
### 多言語対応
多言語で運用するなら、現実的にはこうすると安定します:
- `AGENTS.en.md` をカノニカル(基準)として保つ
- 必要に応じてローカライズ版(例:`AGENTS.<locale>.md`)を追加する
- clone 後、各自がローカルで言語に合わせた symlink を作る:
```bash
# English users
ln -s AGENTS.en.md AGENTS.md
```
- symlink 衝突を避けるため `.gitignore` に `AGENTS.md` を入れる
> 💡 **核心の洞察**
> AI 協働の本質は「良いプロンプト」ではなく「制約をリポジトリの一部にすること」。`AGENTS.md` はルールを再利用可能にし、AI Playbook は文脈を持続可能にします。
---
## Step 2`docs/ai-playbook/index.md`(高シグナルな入口索引)を書く
AI が脱線する最大要因のひとつは、**あなたのコードの“入口”を知らない** こと。結果、ファイルを推測で探し、提案も推測になります。
索引ページの目的は 2 つ:
- 30 秒で読める:プロジェクト概要 + リンク索引だけ
- 1 クリックで飛べる:読者/AI を code-map / flows / collab-rules に誘導する
参考実装: [docs/ai-playbook/index.md](https://github.com/david-bai00/PrivyDrop/blob/main/docs/ai-playbook/index.md)
最小テンプレ(そのままコピー可):
```md
# AI Playbook — Index
## Project Snapshot
- Stack: Next.js / Node / ...
- Red lines: ...
## Document Index
- Code map: docs/ai-playbook/code-map.md
- Key flows: docs/ai-playbook/flows.md
- Collaboration rules: docs/ai-playbook/collab-rules.md
```
---
## Step 3`code-map.md`(どこを触るか)を書く:入口ファイル + 役割 1 行
コード地図のゴールは「素早く当てる」ことで、「教科書」ではありません。書き方はシンプルです:
- 重要ディレクトリと入口ファイルだけ列挙
- 入口ファイルは 1 行で責務を書く
- 依頼が来たら、まず code-map で 3–8 個の候補を当ててから深掘り
参考実装: [docs/ai-playbook/code-map.md](https://github.com/david-bai00/PrivyDrop/blob/main/docs/ai-playbook/code-map.md)
オプション:よくある依頼 → 入口の早見表も便利です:
```md
Common request routing
- New page / SEO: frontend/app/**/page.tsx + metadata.ts
- i18n copy: frontend/constants/messages/*
- Blog: frontend/content/blog/* + frontend/lib/blog.ts
```
生成と運用:
- 初版:AI に「ディレクトリ + 入口ファイル」を要約させ、完璧さより“当てやすさ”を優先
- 更新:PR ごとに差分でメンテ。丸ごと書き直しは避ける
---
## Step 4`flows.md`(どう動くか)を書く:時系列 + デバッグ要点 + マイクロ計画
code-map が「どこを触るか」なら、flows は「どう動くか」です。AI にとって価値が大きい理由は:
- 時系列と不変条件が書かれていれば、AI は“雰囲気修正”をしなくなる
- 過去の落とし穴をチェックリストに圧縮して再利用できる
参考実装: [docs/ai-playbook/flows.md](https://github.com/david-bai00/PrivyDrop/blob/main/docs/ai-playbook/flows.md)
最低限入れたい 3 つ:
1. **重要フロー / 時系列**(必要なら Mermaid
2. **デバッグ要点**(見るべきログ/状態)
3. **マイクロ計画テンプレ**(計画→承認→実装を強制)
運用のコツ:
- 初版:AI に E2E フロー + 重要時系列 + 不変条件を復唱させ、あなたが修正して文書化
- 更新:インターフェース/時系列が変わったら差分で追従
---
## Step 5:「Plan first」を工程化する(計画 = ミニ設計書)
ここが一番効きます。レビューを「diff を読む」から「計画を読む」へ前倒しします。
`collab-rules.md` に計画テンプレを固定し、強制ルールとして運用します。
PrivyDrop テンプレ: [docs/ai-playbook/collab-rules.md](https://github.com/david-bai00/PrivyDrop/blob/main/docs/ai-playbook/collab-rules.md)
構造はこのまま再利用できます:
```text
Title: <short, clear title>
Goals
- <what you want to achieve>
Scope / Files
- <list of files youll change/add + why>
Approach
- <implementation plan and key design points>
Risks & Mitigations
- <risk> → <mitigation>
Acceptance Criteria
- <verifiable acceptance items>
Rollback
- <how to revert quickly>
Docs to Update
- docs/ai-playbook/index.md / code-map.md / flows.md / collab-rules.md / others?
Validation
- Build: next build
- Manual: <key cases & regression points>
```
実運用でさらに安定する流れ:
1. index + code-map + flows を読む(読み取り専用、コードは触らない)
2. 現状と制約を自分の言葉で復唱する(あなたが 1 回だけ矯正)
3. 変更計画を書く(承認後に実装)
> ⚠️ **避坑**
> 計画段階で方向を直す。書いてから壊すのを避ける。単一テーマは rollback とマージを軽くします。
---
## Step 5.1:文脈の持久力(チェックポイント → 新しい会話)
長いタスクで品質が落ちるのはほぼ必然です。そこで“持久力”を作業手順にします:推測が増えた/制約を忘れた/脱線したら、状態をファイルに書き出して新しい会話へ。あるいは compress/summarize で文脈を圧縮して続けます。
最小の引き継ぎテンプレ(`docs/ai-playbook/handoff.md` か一時ファイルに):
```md
# Handoff
## Problem statement (35 sentences)
## Confirmed plan (bullets)
## Done / Not done
## Key files and entry points
## Red lines and invariants
## Acceptance & regression checklist
## Next-step checklist
```
狙いは“綺麗な文書”ではなく、文脈をチャットからファイルへ移し、次のセッションでも安定して読めるようにすることです。
---
## Step 6:協働を閉ループにする(新入社員を迎えるように agent を扱う)
上の部品が揃うと、協働は安定したパイプラインになります:
1. 依頼 → 制約(`AGENTS.md` を引用)
2. 位置特定 → 入口(`index + code-map` を引用)
3. すり合わせ → 時系列(`flows` を引用)
4. 計画 → ミニ設計書(`collab-rules` テンプレ)
5. 実装 → 小さく単一テーマ(切り戻しやすい)
6. 検証 → `next build` + 手動回帰点
7. 同期 → playbook を最新に保つ
体感のメリットは明確で、機能追加/バグ修正が速く、そして安定します。重要なのは「速さ」は冒険ではなく **手戻りの削減** から来ること:
- 計画で方向を直し、作って壊すを減らす
- 単一テーマで rollback を軽く、マージを簡単に
- flows で過去の罠を checklist 化して再利用
門番を置くなら、PR テンプレにこの 2 行を入れると効きます:
- 変更計画のリンク/要約はあるか?
- 入口/フロー/IF が変わったなら `docs/ai-playbook/*` を更新したか?
## 💬 すぐ使えるプロンプト例
AI Playbook ができたら、例えばこう始められます:
---
**Role**
You are a senior Next.js full-stack engineer with strong product instincts. Your collaboration quality determines whether this repo can iterate sustainably—be thorough and professional.
**Task kickoff**
Please read `docs/ai-playbook/index.md` to understand the project context, code map, and collaboration rules. The current request is: "xxx".
**Working style**
Please deeply read relevant docs/code. Think systematically, ask clarifying questions, then propose analysis + a change plan for review. Implement only after approval.
---
**Why this works**
- **Role**: sets quality bar and responsibility boundaries
- **Kickoff**: forces reading the playbook instead of guessing
- **Working style**: makes “plan first” part of the workflow
---
## 業界参照:OpenAI は Codex でスプリントをどう回すか
OpenAI の「28 日で Android 版 Sora を作るために Codex をどう使ったか」は、この playbook と驚くほど一致します:
[https://openai.com/index/shipping-sora-for-android-with-codex/](https://openai.com/index/shipping-sora-for-android-with-codex/)
合わせたいポイント:
- agent は“新しいシニアエンジニア”として扱う:強いが、制約とアーキテクチャの明確化が必要
- ルールの外部化:強い `AGENTS.md` を保守するのは効く
- 実装前に計画:計画はミニ設計書。コードより先に計画をデバッグ
- 文脈の持久力:限界が来たら計画をファイルへ書き、次のセッションへ
- マルチセッション並列:単一ツールより“チームを運用する”に近い
領域は違っても方法は移植できます:**入力を良くすれば、出力は安定します**。
---
## そのままコピーできる最小ディレクトリ構成
```text
AGENTS.en.md # Canonical rules (English)
AGENTS.<locale>.md # Optional localized rules
AGENTS.md # Symlink (created locally after git clone)
docs/
ai-playbook/
index.md # High-signal entry point
code-map.md
flows.md
collab-rules.md
```
すでに文書が散らばっているなら、まず `index.md` で入口を収束させ、その後に code-map/flows/テンプレを埋めるのが近道です。
---
## 🚀 次にやること
1. **今すぐ始める**:最小構成をあなたのリポジトリにコピーし、まず `AGENTS.md` から
2. **参考実装** [PrivyDrop GitHub](https://github.com/david-bai00/PrivyDrop) で AI Playbook 全体を見る
3. **フィードバック**:役立った/詰まったら issue やコメントで共有
4. **Star**:価値があれば PrivyDrop に star を 🌟
---
## 結び
AI 支援開発は厳密さを減らすのではなく、むしろ増やします。持続可能なスピードは、長いプロンプトではなく強い工程制約から生まれます:ルールの外部化、Plan-first、フローの文書化、そして文脈の持久力。
さらに工程化するなら、PR/issue テンプレと、すぐ使える `AGENTS.md`/playbook 初期セットを含む「コピーできるリポジトリ雛形」に進化させるのも良いです。
@@ -0,0 +1,162 @@
---
title: "AI가 엇나가지 않게: 바로 적용 가능한 협업 엔지니어링 방법 (템플릿 포함)"
description: "AI로 코드를 쓰면 자꾸 탈선하나요? AGENTS.md, AI Playbook, plan-first 워크플로로 Codex/Claude를 ‘함께 일하는 동료’로 만들 수 있습니다. 재작업을 줄이고 유지보수성을 높입니다. Next.js 실전 예시 포함."
date: "2025-12-26"
author: "david bai"
cover: "/blog-assets/privydrop-open-source.jpg"
tags:
["AI 협업", "Codex", "엔지니어링 프로세스", "오픈 소스", "Next.js"]
status: "published"
---
![](/blog-assets/privydrop-open-source.jpg)
이런 상황을 겪어본 적 있나요?
- AI에게 버그를 고쳐 달라고 했더니, 상관없는 코드까지 손대서 결국 수동으로 되돌렸다
- 프롬프트를 잔뜩 써도 올바른 파일을 못 찾고, 결국 “찍어서” 수정한다
- 대화가 길어지면 제약을 잊기 시작하고 품질이 급격히 떨어진다
AI를 “더 빠른 검색창”으로만 쓰면 이런 문제는 드러나지 않습니다. 하지만 AI를 “협업하는 동료”로 다루는 순간, 이 문제들은 곧바로 납기와 품질에 영향을 줍니다.
이 글은 AI 협업을 “프롬프트 요술”이 아니라 **재현 가능한 프로세스**로 바꾸는, **실행 가능한 엔지니어링 방법**을 소개합니다. PrivyDrop에서는 이 방식을 적용한 뒤 기능 추가/버그 수정 속도가 더 빠르고 안정적으로 변했습니다. 비결은 더 큰 모험이 아니라 **재작업이 줄어든 것**입니다.
마지막에는 어떤 저장소든 그대로 복사해 넣을 수 있는 최소 구조를 얻게 됩니다:
- `AGENTS.md`: 저장소 레벨의 하드 제약(레드라인, 기본값, Done 정의)
- `docs/ai-playbook/index.md`: 1페이지 인덱스(고신호 진입점)
- `docs/ai-playbook/code-map.md`: 코드 맵(어디를 고칠지)
- `docs/ai-playbook/flows.md`: 핵심 플로우(어떻게 동작하는지)
- `docs/ai-playbook/collab-rules.md`: 협업 규칙 + 변경 계획 템플릿(어떻게 일할지)
모든 예시는 오픈소스 PrivyDrop에서 가져왔습니다:
[https://github.com/david-bai00/PrivyDrop](https://github.com/david-bai00/PrivyDrop)
OpenAI의 실전 글도 접근 방식이 매우 비슷합니다:
[https://openai.com/index/shipping-sora-for-android-with-codex/](https://openai.com/index/shipping-sora-for-android-with-codex/)
---
## Step 0: 경계와 Done을 먼저 정의하기 (프롬프트부터 시작하지 말기)
이 단계는 한 가지를 합니다. “무엇이 완료인가”를 명확히 쓰는 것. 그렇지 않으면 AI는 코드가 “돌아가게” 만드는 데 최적화하고, 팀이 원하는 “오래 유지보수 가능한 방식으로 돌아가게” 만드는 데는 최적화하지 않습니다.
최소 제약 3가지를 먼저 정합니다:
1. **Boundary(경계)**: 절대 하면 안 되는 것(프라이버시/아키텍처 레드라인, 프로토콜 호환, 핵심 파라미터 가드레일)
2. **Scope(범위)**: 한 번에 한 목표. “겸사겸사” 금지
3. **Done(완료)**: 빌드/테스트/수동 회귀 체크리스트를 반드시 작성
요청 맨 앞에 붙일 한 문장으로 압축하면:
```text
목표는 하나, 먼저 계획; 프라이버시/아키텍처 레드라인을 넘지 말 것; Done은 빌드 통과 + 회귀 체크리스트 포함.
```
---
## ❌ 흔한 안티패턴
1. **계획 없이 “코드 고쳐줘”부터 시작**
2. **문서를 전부 프롬프트에 던지기(문맥 과부하)**
3. **“겸사겸사 최적화” 허용**
해법은 같습니다: index + code-map + flows로 길을 잡고, 계획을 승인받은 뒤에만 구현합니다.
---
## Step 1: `AGENTS.md` 쓰기 (하드 제약을 반복 적용)
`AGENTS.md`는 팀의 “기본값과 레드라인”을 기계가 읽을 수 있게 만든 버전입니다. PrivyDrop에서는 아래 다섯 가지가 핵심입니다:
- Plan first: `AGENTS.en.md`
- One change, one purpose: `AGENTS.en.md`
- Privacy & architecture red line: `AGENTS.en.md`
- Docs must stay in sync: `AGENTS.en.md`
- Verification required: `AGENTS.en.md`
파일: [AGENTS.en.md](https://github.com/david-bai00/PrivyDrop/blob/main/AGENTS.en.md)
```md
# AGENTS — Repo Rules
First Principles
- Plan-first: Propose a change plan and get approval before writing code
- Single-scope: One PR solves one goal; avoid “while Im here” fixes
- Redlines: Never cross privacy/architecture/protocol/key-parameter guardrails
- Docs-sync: Keep the playbook docs in sync when entry points/flows/interfaces change
- Validation: Must include build/tests and key manual regression checklist
```
---
## Step 2: `docs/ai-playbook/index.md` 만들기 (고신호 진입점)
참고 구현: [docs/ai-playbook/index.md](https://github.com/david-bai00/PrivyDrop/blob/main/docs/ai-playbook/index.md)
---
## Step 3: `code-map.md` 만들기 (어디를 고칠지)
참고 구현: [docs/ai-playbook/code-map.md](https://github.com/david-bai00/PrivyDrop/blob/main/docs/ai-playbook/code-map.md)
---
## Step 4: `flows.md` 만들기 (어떻게 동작하는지)
참고 구현: [docs/ai-playbook/flows.md](https://github.com/david-bai00/PrivyDrop/blob/main/docs/ai-playbook/flows.md)
---
## Step 5: “plan first”를 강제하기
템플릿: [docs/ai-playbook/collab-rules.md](https://github.com/david-bai00/PrivyDrop/blob/main/docs/ai-playbook/collab-rules.md)
---
## 💬 바로 쓸 수 있는 프롬프트 예시
---
**Role**
You are a senior Next.js full-stack engineer with strong product instincts. Your collaboration quality determines whether this repo can iterate sustainably—be thorough and professional.
**Task kickoff**
Please read `docs/ai-playbook/index.md` to understand the project context, code map, and collaboration rules. The current request is: "xxx".
**Working style**
Please deeply read relevant docs/code. Think systematically, ask clarifying questions, then propose analysis + a change plan for review. Implement only after approval.
---
## OpenAI 참고
[https://openai.com/index/shipping-sora-for-android-with-codex/](https://openai.com/index/shipping-sora-for-android-with-codex/)
---
## 그대로 복사 가능한 최소 디렉터리 구조
```text
AGENTS.en.md # Canonical rules (English)
AGENTS.<locale>.md # Optional localized rules
AGENTS.md # Symlink (created locally after git clone)
docs/
ai-playbook/
index.md # High-signal entry point
code-map.md
flows.md
collab-rules.md
```
---
## 마무리
AI 보조 개발은 엄밀함을 줄이지 않습니다. 오히려 더 필요합니다. 지속 가능한 속도는 더 긴 프롬프트가 아니라 더 강한 엔지니어링 제약에서 나옵니다: 규칙 외부화, 계획 선행, 플로우 문서화, 그리고 문맥의 지속성.
@@ -1,19 +1,27 @@
---
title: " AI 变成可协作队友:AGENTS.md + AI Playbook + 计划先行(附模板)"
description: "一套可复制的 AI 协作工程化方法:规则外化(AGENTS.md)、外部记忆(AI Playbook)、计划先行(变更计划模板)与上下文续航,让新增特性/修复 bug 更快、更稳、更可回滚。"
date: "2025-12-20"
title: " AI 不再跑偏:可落地的协作工程化方法(附模板)"
description: "用 AI 写代码总跑偏?这套方法让 Claude code/Codex 变成可协作队友:AGENTS.mdAI Playbook、变更计划模板,减少返工、提升代码可维护性。附完整实现与 Next.js 实战案例。"
date: "2025-12-26"
author: "david bai"
cover: "/blog-assets/privydrop-open-source.jpg"
tags:
["AI Collaboration", "Codex", "Engineering Process", "Open Source", "Next.js"]
["AI 协作", "Codex", "工程流程", "开源", "Next.js"]
status: "published"
---
![](/blog-assets/privydrop-open-source.jpg)
如果你把 AI 当成“更快的搜索框”,它确实能提速;但当你把 AI 当成“可协作的队友”时,你会立刻遇到另外一类问题:它会猜位置、会跑偏、会顺手大改、会在上下文变长后逐渐失真。
你是否遇到过这样的场景:
这篇文章是一个**教程**:把 AI 协作从“玄学 prompt”落到**可执行的工程流程**。你最终会得到一套可以直接复制进任意代码仓库的最小结构:
- 让 AI 修复一个 bug,结果它把不相关的代码也改了,最后还得手动回滚
- 写了一堆 prompt,AI 还是找不到正确的文件位置,只能靠"猜"
- 对话进行到一半,AI 开始遗忘之前的约束,输出质量断崖式下降
如果你把 AI 当成"更快的搜索框",这些问题不会暴露;但当你把 AI 当成"可协作的队友"时,这些问题会直接影响交付质量。
本文会展示一套**可执行的工程化方法**,让 AI 协作从"玄学 prompt"变成**可复制的流程**。PrivyDrop 项目实践后,新增特性/修复 bug 的节奏明显更快、更稳——不是靠冒险,而是靠减少返工。
你最终会得到一套可以直接复制进任意代码仓库的最小结构:
- `AGENTS.md`:项目级硬约束(红线、默认值、验收方式)
- `docs/ai-playbook/index.md`:一页式索引入口(高信噪比导航)
@@ -22,10 +30,10 @@ status: "published"
- `docs/ai-playbook/collab-rules.md`:协作规则 + 变更计划模板(怎么协作)
本文的所有示例都来自开源仓库 PrivyDrop,你可以直接对照实现:
https://github.com/david-bai00/PrivyDrop
[https://github.com/david-bai00/PrivyDrop](https://github.com/david-bai00/PrivyDrop)
另外,我们也会引用 OpenAI 的一篇实践文章作为“外部佐证”(你会发现方法论非常一致)
https://openai.com/zh-Hans-CN/index/shipping-sora-for-android-with-codex/
另外,最近 OpenAI 的一篇实践文章也有相似的方法论
[https://openai.com/index/shipping-sora-for-android-with-codex/](https://openai.com/index/shipping-sora-for-android-with-codex/)
---
@@ -47,20 +55,37 @@ https://openai.com/zh-Hans-CN/index/shipping-sora-for-android-with-codex/
---
## ❌ 常见反模式:别踩这些坑
在开始之前,先看看最常见的 3 个错误做法:
1. **直接让 AI "改代码",不要计划**
- 后果:改了 10 个文件,最后发现方向错了,回滚成本巨大
- 正确做法:先让 AI 输出变更计划,你批准后再动手
2. **把所有文档都塞给 AI**
- 后果:上下文爆炸,AI 反而抓不住重点(连"入口文件在哪"都找不到)
- 正确做法:用 index + code-map 提供高信噪比导航
3. **让 AI "顺手优化"其他代码**
- 后果:一次 PR 混杂多个目标,code review 成本翻倍,出 bug 难回滚
- 正确做法:单一主题,一次只解决一个明确目标
---
## Step 1:写 `AGENTS.md`(项目级硬约束,强制稳定复用)
把 `AGENTS.md` 理解为:你团队“默认值”和“红线”的机器可读版本。它的作用不是解释原理,而是**在每次会话中都能被重复应用**。
在 PrivyDrop 里,建议重点展示这 5 条(足够代表工程协作约束的核心):
在 PrivyDrop 里,建议重点展示这 5 条(足够代表"工程协作约束"的核心):
- 计划先行:`AGENTS.zh-CN.md:7`
- 单一主题:`AGENTS.zh-CN.md:8`
- 隐私与架构红线:`AGENTS.zh-CN.md:9`
- 文档同步:`AGENTS.zh-CN.md:12`
- 验证要求:`AGENTS.zh-CN.md:13`
- 计划先行:`AGENTS.zh-CN.md`
- 单一主题:`AGENTS.zh-CN.md`
- 隐私与架构红线:`AGENTS.zh-CN.md`
- 文档同步:`AGENTS.zh-CN.md`
- 验证要求:`AGENTS.zh-CN.md`
对应文件(可直接阅读/复制):
https://github.com/david-bai00/PrivyDrop/blob/main/AGENTS.zh-CN.md
对应文件[AGENTS.zh-CN.md](https://github.com/david-bai00/PrivyDrop/blob/main/AGENTS.zh-CN.md)
如果你想从零写一个最小版本,可以用下面这个结构(建议保持短、硬、可执行):
@@ -76,6 +101,26 @@ https://github.com/david-bai00/PrivyDrop/blob/main/AGENTS.zh-CN.md
- Validation:必须给出构建/测试/关键手测回归点
```
### 多语言支持
如果你的项目需要支持多语言协作(比如中英文团队),建议:
- 创建 `AGENTS.zh-CN.md` 和 `AGENTS.en.md`
- 每个协作者首次 clone 仓库后,根据语言选择创建符号链接:
```bash
# 中文用户
ln -s AGENTS.zh-CN.md AGENTS.md
# 英文用户
ln -s AGENTS.en.md AGENTS.md
```
- 在 `.gitignore` 中添加 `AGENTS.md`,避免符号链接冲突
不同语言版本的 `AGENTS.md` 已经包含了各自语言的其他文档引用路径。
> 💡 **核心洞察**
> AI 协作的本质不是"写更好的 prompt",而是"把约束变成代码库的一部分"。AGENTS.md 让规则可复用,AI Playbook 让上下文可延续。
---
## Step 2:写 `docs/ai-playbook/index.md`(高信噪比入口索引)
@@ -84,11 +129,10 @@ AI 最常见的跑偏原因之一是:**不知道你家代码“入口在哪”
索引页要做到两件事:
- 30 秒读完:只放项目快照 + 链接索引
- 30 秒读完:只放"项目快照 + 链接索引"
- 一键跳转:把读者/AI 带到 code-map / flows / collab-rules
参考实现:`docs/ai-playbook/index.zh-CN.md`
https://github.com/david-bai00/PrivyDrop/blob/main/docs/ai-playbook/index.zh-CN.md
参考实现:[docs/ai-playbook/index.zh-CN.md](https://github.com/david-bai00/PrivyDrop/blob/main/docs/ai-playbook/index.zh-CN.md)
最小模板(可直接复制):
@@ -117,8 +161,7 @@ https://github.com/david-bai00/PrivyDrop/blob/main/docs/ai-playbook/index.zh-CN.
- 每个入口文件只写一句话职责
- 看到需求时,先在 code-map 里命中 3–8 个候选文件,再深入读
参考实现:`docs/ai-playbook/code-map.zh-CN.md`
https://github.com/david-bai00/PrivyDrop/blob/main/docs/ai-playbook/code-map.zh-CN.md
参考实现:[docs/ai-playbook/code-map.zh-CN.md](https://github.com/david-bai00/PrivyDrop/blob/main/docs/ai-playbook/code-map.zh-CN.md)
可选:也可以加一段“常见需求 → 入口文件”的速查表,进一步降低定位成本:
@@ -141,11 +184,10 @@ code-map 怎么生成(以及如何迭代):
如果 code-map 解决“去哪改”,flows 解决的就是“怎么跑”。它对 AI 的价值非常大:
- 把时序与不变量写清楚,AI 就不需要凭感觉改
- 你可以把历史上踩过的坑压缩为调试要点,直接复用
- 把时序与不变量写清楚,AI 就不需要"凭感觉改"
- 你可以把"历史上踩过的坑"压缩为调试要点,直接复用
参考实现:`docs/ai-playbook/flows.zh-CN.md`(并拆分了深度阅读小节)
https://github.com/david-bai00/PrivyDrop/blob/main/docs/ai-playbook/flows.zh-CN.md
参考实现:[docs/ai-playbook/flows.zh-CN.md](https://github.com/david-bai00/PrivyDrop/blob/main/docs/ai-playbook/flows.zh-CN.md)(并拆分了深度阅读小节)
建议至少包含三块内容:
@@ -162,12 +204,11 @@ flows 怎么生成(以及如何迭代):
## Step 5:把“计划先行”工程化(计划 = 迷你设计文档)
这是提速的关键:把评审从读 diff前移到读计划
这是提速的关键:把评审从"读 diff"前移到"读计划"
建议在 `collab-rules.md` 里固化计划模板,并把它当成强约束。PrivyDrop 的模板在这里:
建议在 `collab-rules.md` 里固化计划模板,并把它当成强约束。
- `docs/ai-playbook/collab-rules.zh-CN.md`
https://github.com/david-bai00/PrivyDrop/blob/main/docs/ai-playbook/collab-rules.zh-CN.md
PrivyDrop 的模板:[docs/ai-playbook/collab-rules.zh-CN.md](https://github.com/david-bai00/PrivyDrop/blob/main/docs/ai-playbook/collab-rules.zh-CN.md)
模板可以直接复用其中的结构(目标/范围/方案/风险/验收/回滚/验证),参考如下:
@@ -206,9 +247,12 @@ Validation
2. 用自己的话复述现状与约束(你纠正一次)
3. 再产出变更计划(你批准后才允许写代码)
> ⚠️ **避坑指南**
> 计划阶段先纠偏,避免写完再推倒重来;单一主题让回滚成本变低,合并也更容易。
---
## Step 5.1:上下文续航(对话变长就存档换对话
## Step 5.1:上下文续航(对话变长就"存档换对话"
长任务进行到一半时,AI 输出质量下降几乎是必然的。可以把“续航”变成固定动作:当开始出现猜测、遗忘约束、跑偏时,先把当前状态写成一个文件,然后开新对话继续;或者先执行一次“压缩/总结(compress)”把上下文收敛,再继续推进。
@@ -259,12 +303,38 @@ Validation
- 本 PR 是否包含变更计划链接/摘要?
- 是否更新了 `docs/ai-playbook/*`(如涉及入口/流程/接口)?
## 💬 实战提示词样例
当你准备好 AI Playbook 后,可以用类似下面的提示词启动协作:
---
**角色设定**
你是一名资深的 Next.js 全栈工程师,擅长全栈开发、重构优化、bug 定位修复,做了很多成功的在线产品。你的协作质量直接决定了这个开源项目能否长期稳定迭代,请发挥你的专业能力。
**任务启动**
请你阅读 `docs/ai-playbook/index.zh-CN.md` 了解项目背景、代码地图、协作规范等,现在有一个需求为"xxx"。
**工作方式**
请你深入阅读项目相关文档和代码,在充分理解的基础上,结合你丰富的经验和知识,请你系统性、周全的思考,多向我提问来澄清可疑点,然后输出分析结果和行动计划和我讨论,待我同意后实施。
---
**为什么这样写?**
- **角色设定**:明确 AI 的专业身份和责任范围,避免它"不知道该以什么标准输出"
- **任务启动**:强制 AI 先读 playbook,避免凭空猜测
- **工作方式**:把"计划先行"固化为工作流程,避免直接动手改代码
---
## 业界对照:OpenAI 如何用 Codex 组织冲刺(外部佐证)
OpenAI 在《我们如何使用 Codex 在 28 天内构建 Android 版 Sora》里总结了一套非常相似的工作模型:
https://openai.com/zh-Hans-CN/index/shipping-sora-for-android-with-codex/
[https://openai.com/index/shipping-sora-for-android-with-codex/](https://openai.com/index/shipping-sora-for-android-with-codex/)
可以重点对齐这几个点(与本文的方法一一对应):
@@ -274,26 +344,42 @@ https://openai.com/zh-Hans-CN/index/shipping-sora-for-android-with-codex/
- 上下文续航:当达到背景窗口限制时,把计划写入文件供下一次会话继续
- 多会话并行:更像在“管理一个团队”,而不是使用单一工具
规模不必照搬,但方法值得借鉴:**先把输入变好,输出自然会稳定**。
虽然安卓开发与web开发领域不一样,但方法值得借鉴:**先把输入变好,输出自然会稳定**。
---
## 可直接复制的最小目录结构
```text
AGENTS.md
AGENTS.zh-CN.md # 中文规则
AGENTS.en.md # 英文规则
AGENTS.md # 符号链接(git clone 后手动创建)
docs/
ai-playbook/
index.md
index.zh-CN.md # 中文索引
index.md # 英文索引
code-map.zh-CN.md
code-map.md
flows.zh-CN.md
flows.md
collab-rules.zh-CN.md
collab-rules.md
```
如果你已经有文档但分散在各处:先做 index,把入口收束;然后再补 code-map/flows/模板即可。
---
## 🚀 下一步行动
1. **立即开始**:复制最小目录结构到你的项目,从 `AGENTS.md` 开始
2. **参考实现**:访问 [PrivyDrop GitHub](https://github.com/david-bai00/PrivyDrop),查看完整 AI Playbook
3. **给我反馈**:如果这套方法对你有帮助(或踩坑了),欢迎在 GitHub 提 issue 或评论区交流
4. **Star 支持**:如果觉得有价值,给 PrivyDrop 一个 star 🌟
---
## 结语
AI 辅助开发不会减少严谨性要求,反而会增加。真正能把效率变成“可持续复利”的,不是更长的 prompt,而是更强的工程约束:规则外化、计划先行、流程固化、上下文续航。