.agents/skills/perform-task/references/phase-prompts.md
Use these templates as Codex subagent messages. Use them as same-session
checklists only for intentional current-session build work, Phase 7, or when
delegation is unavailable from the start at the current agent depth. Replace
every applicable placeholder: <TASK>, <TASK_ID>, <WORK_DIR>,
<PROJECT_FILE>, <PREVIOUS_CONTEXT>, <BUILD>, <N>,
<OWNED_WRITE_SET>, <R>, <R-1>, and <phase-name>.
<WORK_DIR>/logs/phase-<phase-name>.prompt.md before execution.spawn_agent message.<WORK_DIR>/logs/phase-<phase-name>.result.md with exact
STATUS:, ARTIFACTS:, TOUCHED:, BLOCKER:, and NOTES: fields.fork_turns: "none" by default. If the phase depends on thread-only context or UI attachments, pass it explicitly or use the smallest positive turn fork needed.spawn_agent schema exposes; do not invent role, model, or reasoning arguments. Inherit the parent model/reasoning selection, or match it if the host explicitly supports overrides.spawn_agent, and tell the phase it is a leaf that must not delegate.wait_agent for at most 60 seconds per call; use elapsed wall-clock windows for stall decisions. Use 30-60 second polls when a phase appears close to landing.wait_agent is mailbox-wide and may wake for another agent or user input. A timeout is not failure. After every wake, handle new user input if any, inspect the saved target with list_agents, and check the expected artifact and matching progress file.send_message while the target is running or followup_task when it is idle, asking it to refresh progress, finish the artifact, and return the compact block.interrupt_agent if needed, confirm the turn stopped, and retry the disposable phase once with a new unique name. There is no close-agent operation.codex exec, background shell child processes, or JSONL child-session logging from this skill.Append this verbatim to every delegated phase prompt:
You are a leaf phase worker. Do not spawn or delegate to other agents.
Before deep work, create or update the matching progress file in `<WORK_DIR>/logs/`.
Use `phase-<phase-name>.progress.md` as a concise heartbeat with:
- `Heartbeat: <N>` on the first line, incremented on each meaningful update
- Current step
- Files being read or edited
- Concrete findings or decisions so far
- Blocker or next checkpoint
Update it sparingly: preferably at natural milestones, and otherwise only after a longer quiet stretch such as roughly 5-10 minutes.
Keep it tiny so the parent can usually rely on file mtime or the heartbeat counter instead of rereading the whole file.
Do not wait until the final artifact to write progress.
Append this verbatim to every delegated phase prompt:
Before replying in chat, write the required artifact(s) to disk.
Reply in 8 lines or fewer using exactly these keys:
STATUS: <DONE|BLOCKED|APPROVED|NEEDS_CHANGES>
ARTIFACTS: <paths>
TOUCHED: <repo paths or none>
BLOCKER: <none or one short line>
Do not restate the full context, plan, diff, or long reasoning in the chat reply.
context.md exists and is non-empty. For a
project task, project.proposed.md must also exist and be non-empty.plan.md exists, contains a ## Status section, and no unintended source edits were made.plan.md contains both Phases: in the Status section and Assessed: yes.R wrote review<R>-<lens>.md with a ## Verdict: line and a non-empty ## Checked section. A lens report that records no checked surfaces is incomplete work: rerun that lens rather than accepting it.review<R>.md exists with a ## Verdict: line, a non-empty ## Coverage section, and a ## Dropped section.visual.md cites its available
design sources (images when supplied; otherwise request facts and repository/baseline anchors),
records assumptions, and contains desktop anchors, an ordered derivation, tolerances, and
falsifiable geometry checks. Missing mockups alone never make the phase incomplete.You are a context-gathering agent for a large C++ codebase (Telegram Desktop).
TASK: <TASK>
YOUR JOB: Read AGENTS.md, inspect the codebase, find all files and code relevant to this task, and write self-contained implementation context.
Steps:
1. Read AGENTS.md for project conventions and build instructions.
2. When `<PROJECT_FILE>` is not `none`, read it as the current durable project
blueprint and preserve everything still accurate in the proposal.
3. Search the codebase for files, classes, functions, and patterns related to the task.
4. Read all potentially relevant files. Be thorough and prefer reading more rather than less.
5. For each relevant file, note:
- file path
- relevant line ranges
- what the code does and how it relates to the task
- key data structures, function signatures, and patterns used
6. Look for similar existing features that could serve as a reference implementation.
7. Check api.tl if the task involves Telegram API.
8. Check .style files if the task involves UI.
9. Check lang.strings if the task involves user-visible text.
Write `<WORK_DIR>/project.proposed.md` only when `<PROJECT_FILE>` is not
`none`. It is not used by the current task. Describe the project as if this
task is approved and fully working, so the performer can promote it only after
approval. Include:
- Project: What this project does (feature description, goals, scope)
- Architecture: High-level architectural decisions, which modules are involved, how they interact
- Key Design Decisions: Important choices made about the approach
- Relevant Codebase Areas: Which parts of the codebase this project touches, key types and APIs involved
Do not include temporal state like "Current State", "Pending Changes", "Not yet implemented", or "TODO". Describe the project as a complete, coherent whole.
Always write `<WORK_DIR>/context.md`.
This is the primary task-specific implementation context. All downstream phases should be able to work from this file plus the referenced source files. It must be self-contained. Include:
- Task Description: The full task restated clearly
- Relevant Files: Every file path with line ranges and descriptions
- Key Code Patterns: How similar things are done in the codebase, with snippets when useful
- Data Structures: Relevant types, structs, classes
- API Methods: Any TL schema methods involved, copied from api.tl when useful
- UI Styles: Any relevant style definitions
- Localization: Any relevant string keys
- Build Info: Build command and any special notes
- Reference Implementations: Similar features that can serve as templates
Be extremely thorough. Another agent with no prior context will rely on this file.
Do not implement code in this phase.
You are a context-gathering agent for a follow-up task on an existing project in a large C++ codebase (Telegram Desktop).
NEW TASK: <TASK>
YOUR JOB: Read the existing project state, gather any additional context needed, and produce fresh documents for the new task.
Steps:
1. Read AGENTS.md for project conventions and build instructions.
2. Read <PROJECT_FILE>. This is the project-level blueprint describing everything done so far.
3. Read <PREVIOUS_CONTEXT>. This is the previous task's gathered context.
4. Understand what has already been implemented by reading the actual source files referenced in the project file and previous context.
5. Based on the new task description, search the codebase for any additional files, classes, functions, and patterns that are relevant to the new task but not already covered.
6. Read all newly relevant files thoroughly.
Write two files.
File 1: `<WORK_DIR>/project.proposed.md`
Write a single coherent proposed project document that describes everything,
including this task's changes, as fully implemented and working. Do not modify
`<PROJECT_FILE>` during this phase.
It should incorporate:
- everything from the existing project document that is still accurate and relevant
- the new task's functionality described as part of the project, not as a pending change
- any changed design decisions or architectural updates from the new task requirements
It should not contain:
- temporal state such as "Current State", "Pending Changes", or "TODO"
- history of how requirements changed between tasks
- references to "the old approach" versus "the new approach"
- task-by-task changelog or timeline
- information that contradicts the new task requirements
File 2: `<WORK_DIR>/context.md`
This is the primary document for the new task. It must be self-contained and should include:
- Task Description: The new task restated clearly, with enough project background that an implementation agent can understand it without reading other AI task files
- Relevant Files: Every file path with line ranges relevant to this task
- Key Code Patterns: How similar things are done in the codebase
- Data Structures: Relevant types, structs, classes
- API Methods: Any TL schema methods involved
- UI Styles: Any relevant style definitions
- Localization: Any relevant string keys
- Build Info: Build command and any special notes
- Reference Implementations: Similar features that can serve as templates
Be extremely thorough. Another agent with no prior context should be able to work from this file alone.
Do not implement code in this phase.
You are a planning agent. You must create a detailed implementation plan.
Read these files:
- <WORK_DIR>/context.md
- Then read the specific source files referenced in context.md to understand the code deeply.
Create a detailed plan in: <WORK_DIR>/plan.md
The plan.md should contain:
## Task
<one-line summary>
## Approach
<high-level description of the implementation approach>
## Files to Modify
<list of files that will be created or modified>
## Files to Create
<list of new files, if any>
## Implementation Steps
Each step must be specific enough that an agent can execute it without ambiguity:
- exact file paths
- exact function names
- what code to add, modify, or remove
- where exactly in the file (after which function, in which class, and so on)
Number every step. Group steps into phases if there are more than about eight steps.
### Phase 1: <name>
1. <specific step>
2. <specific step>
### Phase 2: <name> (if needed)
1. <specific step>
## Build Verification
- build command to run
- expected outcome
## Status
- [ ] Phase 1: <name>
- [ ] Phase 2: <name> (if applicable)
- [ ] Build verification
- [ ] Code review
Do not implement code in this phase.
You are a plan assessment agent. Review and refine an implementation plan.
Read these files:
- <WORK_DIR>/context.md
- <WORK_DIR>/plan.md
- Then read the actual source files referenced to verify the plan makes sense.
Assess the plan:
1. Correctness: Are the file paths and line references accurate? Does the plan reference real functions and types?
2. Completeness: Are there missing steps? Edge cases not handled?
3. Code quality: Will the plan minimize code duplication? Does it follow existing codebase patterns from AGENTS.md?
4. Design: Could the approach be improved? Are there better patterns already used in the codebase?
5. Phase sizing: Each phase should be implementable by a single agent in one session. If a phase has more than about 8-10 substantive code changes, split it further.
Update plan.md with your refinements. Keep the same structure but:
- fix any inaccuracies
- add missing steps
- improve the approach if you found better patterns
- ensure phases are properly sized for single-agent execution
- add a line at the top of the Status section: `Phases: <N>`
- add `Assessed: yes` at the bottom of the file
If the plan is small enough for a single agent (roughly 8 steps or fewer), mark it as a single phase.
Do not implement code in this phase.
Run one implementation unit per plan phase. Keep implementation phases sequential by default. Parallelize only if their write sets are disjoint and the plan makes that safe.
For each phase in the plan that is not yet marked as done, use this prompt:
You are an implementation agent working on phase <N> of an implementation plan.
Read these files first:
- <WORK_DIR>/context.md
- <WORK_DIR>/plan.md
Then read the source files you will be modifying.
Your owned write set for this phase:
<OWNED_WRITE_SET>
YOUR TASK: Implement only Phase <N> from the plan:
<paste the specific phase steps here>
Rules:
- Follow the plan precisely.
- Follow AGENTS.md coding conventions.
- You are not alone in the codebase. Respect existing changes and do not revert unrelated work.
- Do not modify AI task files except the Status section in plan.md and the matching
`logs/phase-<phase-name>.progress.md` heartbeat required by this prompt.
- When done, update plan.md Status section: change `- [ ] Phase <N>: ...` to `- [x] Phase <N>: ...`
- Do not work on other phases.
When finished, report what you did, which files you changed, and any issues encountered.
After each implementation phase:
git diff --name-only.Only run this phase if the task modified project source code.
Prefer running the build in the main session because it is critical-path work. If you delegate it, use a worker subagent and wait immediately for the result.
You are a build verification agent.
Read these files:
- <WORK_DIR>/context.md
- <WORK_DIR>/plan.md
The implementation is complete. Your job is to build the project and fix any build errors that block the planned work.
Steps:
1. Run the resolved Debug build command from context.md (`<BUILD>`) at the repository root. On WSL
this is the repository Docker entry point; do not run native Windows CMake against that tree.
2. If the build succeeds, update plan.md: change `- [ ] Build verification` to `- [x] Build verification`
3. If the build fails:
a. Read the error messages carefully
b. Read the relevant source files
c. Fix the errors in accordance with the plan and AGENTS.md conventions
d. Rebuild and repeat until the build passes
e. Update plan.md status when done
Rules:
- Only fix build errors. Do not refactor or improve code beyond what is needed for a passing build.
- Follow AGENTS.md conventions.
- If build fails with file-locked errors (C1041, LNK1104, "cannot open output file", or similar access-denied lock issues), stop and report the lock. Do not retry.
- You are not alone in the codebase. Respect existing changes and do not revert unrelated work.
When finished, report the build result and which files, if any, you changed.
After build verification passes, run up to 3 review-fix iterations. Set iteration counter R = 1.
Each iteration runs four independent review lenses over the same diff, then one
synthesis pass that produces the single review<R>.md the fix phase consumes. The
lenses never read each other's reports: independence is what makes their agreement
evidence rather than an echo. Their write sets are disjoint (one report file each),
so they may run in parallel; when delegation is unavailable, run them as sequential
checklists in the current session and keep the same four reports.
The lenses are:
| Lens | Report file | Angle |
|---|---|---|
correctness | review<R>-correctness.md | Does it do the specified thing, on every path it touches |
lifetime | review<R>-lifetime.md | Ownership, object lifetime, re-entrancy, threading |
reuse | review<R>-reuse.md | Duplication of what the repository already has |
structure | review<R>-structure.md | Placement, minimality, dead code, conventions |
Review loop:
LOOP:
1. Run the scheduled Phase 6a lenses for iteration R.
R = 1 -> all four lenses.
R > 1 -> every lens whose finding survived synthesis in iteration R-1,
plus `lifetime` unconditionally. A fix pass is the most likely
moment for a new ownership or lifetime error to be introduced,
so that lens never goes unrun over changed code.
2. Run synthesis phase 6s with iteration R. It writes review<R>.md.
3. Read review<R>.md verdict:
- "APPROVED" -> go to FINISH
- "NEEDS_CHANGES" -> run fix phase 6b
4. After fix work completes and build passes:
R = R + 1
If R > 3 -> go to FINISH
Otherwise -> go to step 1
FINISH:
- Update plan.md: change `- [ ] Code review` to `- [x] Code review`
- Proceed to Phase 7 on native, non-WSL Windows; otherwise proceed to Completion
Every lens prompt is the shared preamble below, then its own Angle section, then the
shared report contract. Replace <LENS> with the lens name and <R> with the
iteration.
You are one of four independent code-review lenses for Telegram Desktop (C++ / Qt).
Your lens is <LENS>, iteration <R>.
Other lenses cover the other angles. Do not review outside your assigned angle, and
never soften or skip a finding because another lens might also catch it — you cannot
see their reports and they cannot see yours.
Read these files:
- <WORK_DIR>/context.md
- <WORK_DIR>/plan.md
- AGENTS.md
- REVIEW.md
- If R > 1, also read <WORK_DIR>/review<R-1>.md for what the previous iteration
already required, so you do not re-file a fix that has since been applied.
Then run `git diff` to see the current uncommitted changes for this task, and read
every modified source file IN FULL. The diff hides the context a change lands in,
and most real defects are visible only in that context.
Review only what this task changed. A pre-existing problem outside this task's diff
is not a finding, however tempting.
Default to NOT CLEAN. A clean verdict is a positive claim that you looked at each
surface and found nothing — not the absence of an objection. You must report what
you checked, and a report whose Checked section does not account for the diff is
incomplete work, not a fast approval.
A finding is admissible only if you can state the concrete failure it produces: the
specific input, state, or call sequence that yields a crash, a wrong result, or a
maintenance cost a future reader pays. "Could be cleaner", "consider extracting",
and "might be a problem" are not findings. If you cannot name the failure, drop it.
Do not suggest comments or docstrings.
correctnessANGLE — behavior and correctness. Does the change produce the behavior the task and
plan specify, on every path it touches?
- Logic errors: inverted conditions, wrong operator, off-by-one, wrong variable.
- Missing branches: early return, empty or absent data, a failed or cancelled
network reply, the not-found case, the zero and one-element cases.
- State left inconsistent when an operation fails partway through.
- Behavior in adjacent code paths the diff touches but the task did not intend to
change.
- Values crossing an API boundary — network, settings, a peer or session lookup —
used without checking what the boundary can actually return.
- Obviously pathological work in a hot path: per-frame paint, resize, scroll, or a
loop over every message or dialog.
lifetimeANGLE — lifetime, ownership and safety. Will this crash, and who owns what?
- Use-after-free and dangling references: a reference or pointer to a temporary, or
into a container that can reallocate or rehash before the next use.
- Ownership: for every object the change introduces or stores, name the owner and
confirm the owner outlives every user. Watch widget parent/child ownership, raw
pointers escaping the scope that owns them, and `not_null` invariants that the
change can now violate.
- Reactive and callback lifetimes: every subscription bound to a lifetime that dies
with everything its handler dereferences; captures that can be destroyed before
the callback runs; guarded-callback and weak-pointer use where the target can go
away.
- Re-entrancy and destruction order: can this run while something it dereferences is
being destroyed; can a handler destroy the object that invoked it.
- Thread assumptions: main-thread-only APIs reached from another thread; data shared
across threads without synchronization.
- Iterator or reference invalidation across a mutation of the container.
reuseANGLE — duplication and reuse. Does the repository already have this?
This lens is not satisfied by reading the diff. Reuse lives OUTSIDE the diff, which
is exactly why a single generalist reviewer misses it. Search the repository before
you judge anything.
- For each helper, widget, algorithm, constant, string, or style value the change
introduces: search for an existing equivalent, then either use it or state in your
report why the existing one does not fit. Report the search you ran.
- Logic repeated within the change itself that should be shared.
- A reimplementation of an established repository pattern instead of following it —
the strongest finding this lens produces, and the one that compounds worst if it
ships.
- New style values that duplicate an existing token; new localization strings that
duplicate an existing key.
structureANGLE — structure, simplicity and conventions. Does it read like the rest of the
codebase, and is it no bigger than it needs to be?
- Placement: each piece lives in the module it logically belongs to. Flag module
structure only when a large new chunk clearly belongs elsewhere.
- Decomposition: an extracted helper that would CLEARLY improve readability. Do not
file marginal splits.
- Minimality: diff hunks with no functional effect; changes broader than the task
requires; abstraction, indirection, validation, or error handling for cases that
cannot happen; a compatibility shim or flag where the code can simply change.
- Dead code: anything added or left behind that nothing reaches.
- Conventions: REVIEW.md mechanical rules and AGENTS.md coding conventions.
- Local idiom: comment density, naming, and construction match the surrounding code.
Write your report to <WORK_DIR>/review<R>-<LENS>.md. Do not write review<R>.md —
the synthesis phase owns that file.
## Lens: <LENS> — iteration <R>
## Checked
<One line per surface you examined and cleared: the file and function, and what you
verified about it under THIS angle. This section is the evidence behind a clean
verdict, and it is required even when you do have findings — list everything you
cleared alongside them. For the reuse lens, include the searches you ran.>
## Findings
<Omit the section entirely when you have none.>
### <short title>
- File(s): <paths, with line references>
- Failure: <the concrete input, state, or sequence -> the crash, wrong result, or
maintenance cost it produces>
- Fix: <the specific change to make>
- Confidence: <high | medium | low>
## Verdict: <CLEAN or FINDINGS>
Reply in the compact block. Do not restate the diff or the report body in chat.
You are the review synthesizer for iteration <R>. Four independent lenses reviewed
the same task diff. Produce the single review<R>.md that the fix phase implements.
Read every <WORK_DIR>/review<R>-*.md that exists for this iteration, plus
<WORK_DIR>/context.md, <WORK_DIR>/plan.md, REVIEW.md, and the task diff itself.
You are the last filter before work is created, and you are adversarial toward the
findings, not toward the code. Apply in order:
1. Merge duplicates. Several lenses may describe one underlying defect from
different angles. Keep one entry, with the clearest failure statement, and pick
the category that matches the actual defect.
2. Confirm each finding against the code yourself. Do not take a lens at its word.
A finding whose failure statement you cannot reproduce by reading the diff and
the surrounding file is DROPPED, whatever confidence the lens claimed.
3. Drop findings that fall outside this task's diff.
4. Order what survives by impact: crashes and wrong behavior first, then duplication
and placement, then minimality and conventions.
Verdict rule: NEEDS_CHANGES if any finding survives, otherwise APPROVED. An APPROVED
verdict must carry the merged Checked coverage from every lens that ran — that
coverage is the evidence for approval, and an APPROVED review without it is
incomplete work.
Write <WORK_DIR>/review<R>.md:
## Code Review - Iteration <R>
## Summary
<1-2 sentence overall assessment>
## Coverage
<Merged Checked lines from every lens that ran this iteration, grouped by lens.>
## Verdict: <APPROVED or NEEDS_CHANGES>
If the verdict is NEEDS_CHANGES, continue with:
## Changes Required
### <Issue 1 title>
- Category: <correctness | lifetime | duplication | wrong placement | function decomposition | module structure | dead code | minimality | style>
- File(s): <file paths>
- Problem: <clear description, including the concrete failure>
- Fix: <specific description of what to change>
## Dropped
<Each finding you dropped and why, or `none`. This is how the next iteration knows
not to re-file it.>
When finished, report your verdict clearly as: APPROVED or NEEDS_CHANGES.
You are a review fix agent. You implement improvements identified during code review.
Read these files:
- <WORK_DIR>/context.md
- <WORK_DIR>/plan.md
- <WORK_DIR>/review<R>.md
Then read the source files mentioned in the review.
YOUR TASK: Implement all changes listed in review<R>.md.
Rules:
- Implement exactly the review changes, nothing more.
- Follow AGENTS.md coding conventions.
- You are not alone in the codebase. Respect existing changes and do not revert unrelated work.
- Do not modify AI task files except where the review process explicitly requires it.
After all changes are made:
1. Run the resolved Debug build command from context.md (`<BUILD>`) at the repository root.
2. If the build fails, fix build errors and rebuild until it passes.
3. If build fails with file-locked errors (C1041, LNK1104, "cannot open output file", or similar access-denied lock issues), stop and report the lock. Do not retry.
When finished, report what changes were made and which files you touched.
Run this phase only in a native, non-WSL Windows checkout and only after the review loop has finished. Keep WSL/Linux text LF/no-BOM.
Use the current task's result logs as the source of truth for what Codex touched. Do not sweep the whole repo and do not rewrite unrelated files from a dirty worktree.
You are performing the final native-Windows-only text normalization phase for perform-task.
Read these files:
- <WORK_DIR>/plan.md
- <WORK_DIR>/logs/phase-4*.result.md
- <WORK_DIR>/logs/phase-5*.result.md
- <WORK_DIR>/logs/phase-6*.result.md
Your job:
- Collect the union of repo file paths listed in the exact `TOUCHED:` fields in those result logs.
- Keep only files inside the repository that currently exist and are textual project files: source, headers, build/config files, localization files, style files, and similar text assets.
- Exclude `out/`, binary files, and unrelated user files that were not touched by Codex in this task.
- Rewrite each kept file so all line endings are CRLF.
- If a kept file is UTF-8 or ASCII text, write it back as UTF-8 without BOM. Never add a UTF-8 BOM to source/config/project text files.
- Preserve file content otherwise. Preserve whether the file ended with a trailing newline.
Rules:
- Run this phase in the current session on native, non-WSL Windows.
- Do not modify files outside the touched-file set for the current task.
- Do not rewrite binary files.
- When scripting this phase, do not use writer APIs or defaults that emit UTF-8 with BOM.
- If a file cannot be normalized safely, record it as a failure instead of silently skipping it.
When finished:
1. Write `<WORK_DIR>/logs/phase-7-line-endings.result.md`
2. Include:
- whether the phase completed
- which files were normalized
- which files were skipped and why
- whether any UTF-8 BOMs were removed or verified absent
- any failures that need to be mentioned in the final summary
When all phases, including build verification, code review, and Windows line ending normalization when applicable, are done:
plan.md and prepare the compact performer result.$START_TIME (format as Xh Ym Zs, omitting zero components).context.md or plan.md is not written properly by a phase, rerun that phase in a fresh subagent with more specific instructions.For each phase:
<WORK_DIR>/logs/phase-<phase-name>.prompt.md<WORK_DIR>/logs/phase-<phase-name>.progress.md heartbeat while work is in flight<WORK_DIR>/logs/phase-<phase-name>.result.md with STATUS:, ARTIFACTS:,
TOUCHED:, BLOCKER:, and NOTES: fields.For review iterations, include the iteration and the lens in the file name, for example:
phase-6a-review-1-correctness.prompt.mdphase-6a-review-1-correctness.result.mdphase-6a-review-1-lifetime.prompt.mdphase-6a-review-1-reuse.prompt.mdphase-6a-review-1-structure.prompt.mdphase-6s-synthesis-1.prompt.mdphase-6s-synthesis-1.result.mdphase-6b-fix-1.prompt.mdphase-6b-fix-1.result.mdUse this pattern conceptually for delegated phases:
fork_turns: "none" unless a minimal recent-turn fork is required.list_agents; use elapsed five-minute windows rather than poll count for stall checks.send_message for a running target or followup_task for an idle one. After a second unchanged window, interrupt if needed and retry the disposable phase once with a unique task name.Do not replace this pattern with shell-launched codex exec.