Research Workflow
Mission
Drive AI R&D tasks with small, testable, evidence-first steps while supporting durable long-running execution, aggressive experience retrieval, and DR-first external search.
Orchestration Order
CRITICAL: Each step below that names a skill MUST be executed by calling Skill(skill: "<name>"). Do NOT simulate or skip the skill — actually invoke it via the Skill tool. Producing output that a skill should produce without invoking that skill is a workflow violation.
For non-trivial tasks, run this order:
Skill(skill: "run-governor")— Initialize run policy (mode + run_id) and reconcile active long actions before any execution.Skill(skill: "project-context")— Resolve runtime context before experiment/report/eval execution. MUST call when env setup is needed.- Understand user objective and current code/evidence state.
Skill(skill: "human-checkpoint")— Clarify ambiguous requirements. MUST call when intake is incomplete.- Complete intake checkpoint before planning or decomposition.
Skill(skill: "memory-manager")— Run bootstrap retrieval and initialize durable working state. MUST call before planning.Skill(skill: "deep-research")— Use as the default external search gateway whenever outside evidence is needed, and always when research-intent keywords appear.Skill(skill: "research-plan")— Build execution plan. MUST call for planning-heavy requests or after deep-research scoping.- Confirm plan as required by mode.
Skill(skill: "experiment-execution")— Execute experiment. MUST call for any actual run/launch/monitor.- Replan on major issues when needed.
- Emit stage reports and maintain report index.
Skill(skill: "memory-manager")— Close-out writeback. MUST call before task completion.Skill(skill: "paper-writing")— Write paper deliverable. MUST call only when user explicitly asks for paper output.
Mode-Aware Interaction Policy
Follow run mode from run-governor:
full-auto- Prefer autonomous decisions.
- Ask user only for hard blockers or major safety risks.
moderate- Confirm finalized plan.
- Confirm before high-resource actions.
detailed- Ask on unclear path.
- Ask before high-resource actions.
If user explicitly asks to switch mode, switch immediately.
User Interaction Routing Policy
Route required user interactions through human-checkpoint:
- In
moderateordetailed, prefer built-in user-question tool (request_user_input). - If built-in tool is unavailable, degrade to concise plain-text questions.
- Apply this routing to intake clarification, plan confirmation, replan confirmation, and parameter approvals.
- Log channel choice as
interaction_channel=request_user_input|plain-text-fallbackand includefallback_reasonwhen used.
Mid-Run Intent Switch Gate (Mandatory)
On each new user message:
- Re-evaluate objective and skill routing before executing the next pending action.
- Retrieve relevant memory before new planning or execution continues.
- If user intent shifts to research/scoping/comparison/root-cause inquiry, call
Skill(skill: "deep-research")immediately — do NOT answer the research question yourself. - Do not continue stale execution plans when the objective changed materially.
- If
deep-researchis skipped, emitdr_skip_reasonwith freshness evidence (date/timestamp and source coverage), then continue. - Cooldown:
- no more than one non-forced deep-research call per stage.
- bypass cooldown when objective changed, contradiction appears, or high-impact uncertainty remains unresolved.
Goal Compilation Gate (Mandatory)
Before planning the first execution batch, translate the user request into machine-checkable success gates. Do not leave stopping conditions as prose only.
Compile at least:
objective_summary: one-sentence task goalprimary_target: final target metric or observable end statepromotion_gates: staged thresholds that must be passed before larger or costlier evaluationnon_regression_guards: what must not degrade materiallybackup_policy: when to preserve best-so-far variantsstop_allowed_only_if: exact conditions that permitdonehard_blockers: the small set of conditions that justify asking the user
Examples of required compilation:
- "keep iterating" or "do not stop" ->
completion_policy=until-target-or-hard-blocker - "target 100% accuracy" -> stretch target plus current promotion gate
- "use about 30 examples first, then try 100" -> ordered evaluation ladder
- "do not overfit a few cases" -> non-regression guard on held-out or previously-correct samples
- "backup strong versions" -> preserve best-so-far artifact before riskier changes
If any of these are measurable but omitted from the compiled goal state, treat that as a workflow defect and repair it before continuing.
Durable Execution Loop
Repeat this loop until completion:
- Compile or refresh success criteria, promotion gates, and done guards.
- Retrieve prior experience:
procedureretrieval is mandatory before each execution batch- add
episoderetrieval when a problem, repeated attempt, or new error signature appears - add
insightretrieval for planning, tradeoffs, or final answer shaping
- Route external search through
deep-researchwhen fresh outside evidence is needed. - Plan the smallest useful next batch.
- If the batch contains a
long_action, persist an action record before waiting. - If the batch contains a
long_action, switch towatch mode. - Act or poll an active action.
- Observe outputs or liveness state.
- If a poll occurred, immediately branch into post-poll handling rather than stopping at a status update.
- Write working delta.
- Evaluate result quality, target progress, and non-regression status against the compiled gates.
- Decide: iterate, replan, checkpoint, or done.
Short Iterative Optimization Policy
Treat local edit-evaluate loops with the same ownership standard as long-running jobs. They are not "one batch and done" tasks.
For iterative optimization tasks:
- establish a baseline score before the first risky change when practical
- define the primary regression set and any promotion gate set before broadening evaluation
- after each batch:
- compare against baseline and best-so-far
- check non-regression guards
- update which promotion gate is next
- if a new best result appears and the user requested preservation or the route is high-risk, snapshot the best-so-far variant before proceeding
- if targets are still unmet and a safe next step exists, default to
iterate, notdone - if repeated attempts plateau or regress, default to
replan - ask the user only for a true blocker, safety/resource gate, or objective ambiguity that cannot be resolved locally
Long-Running Action Policy
Treat an action as long-running when it is expected to exceed 5 minutes, launches a remote or async job, or likely outlives the current model turn.
Before launching a long-running action:
- persist an action record through
run-governor - record:
- command
- cwd
- log path
- success/failure signals
- expected duration
- poll interval
- resume step
- update working state with the active
action_id - choose an initial poll interval, but keep the schedule under model control
- if the action is likely to outlive the current turn, start an external watcher loop before leaving the turn
While the current session remains active:
- use poll loops rather than blocking waits
- the loop should be
model chooses sleep -> run watcher/poll -> inspect -> model chooses next sleep -> continue - if no new output appears, classify as
runningorstalled, notdone - the model may shorten the interval when there is fresh progress, warning signs, or expected completion is near
- the model may lengthen the interval when the process is healthy but idle
- watcher scripts should report status, not own the polling strategy
- after each poll, update working state and next poll time
- after each poll, immediately choose one of:
- continue-watch
- collect-results
- diagnose-stall
- diagnose-failure
- replan
- do not hand the task back to the user merely because the job is long-running
- replan only after explicit lack-of-progress evidence, not because output paused briefly
Post-Poll Handling Policy
After every long-action poll, the agent must keep ownership of the task and continue from the observed state.
Required branches:
running- if the process is healthy, choose the next sleep interval and continue watch mode
- if progress appeared, update working state and keep monitoring
completed- inspect outputs, logs, checkpoints, or metrics immediately
- run downstream validation, analysis, or report generation instead of waiting for the user to come back
stalled- inspect logs and latest outputs
- retrieve
procedureandepisodememory before the next recovery attempt - attempt the smallest safe recovery or replan
failed- inspect failure evidence immediately
- retrieve relevant memory
- attempt the smallest safe recovery, or replan if needed
checkpoint- ask the user only if a true hard blocker, major safety risk, or explicit decision point remains
Default rule:
- Never respond with the equivalent of "the job is running, come back later" unless the user explicitly wants fire-and-forget behavior.
- Long-running work stays inside the watch loop until one of these is true:
- success criteria are met
- a hard blocker requires the user
- a safety/resource gate requires explicit approval
- an external automation takeover was explicitly established
Watch-Loop Prompt Template
When running in watch mode, use this template after every poll so followup handling stays consistent instead of ad hoc.
Template:
- poll the action
- read:
statusstatus_changedprogress_changedfollowup_actionlast_log_tail
- execute the branch for
followup_action - update working delta
- either choose the next sleep interval or continue into diagnosis/result handling immediately
Branch template:
followup_action=continue-watch- summarize what changed
- decide the next sleep interval
- remain in watch mode
followup_action=wait-and-poll- confirm the process is still healthy
- choose the next sleep interval
- remain in watch mode
followup_action=collect-results- inspect outputs, checkpoints, logs, metrics, or artifacts immediately
- validate against success criteria
- continue to downstream analysis/reporting rather than stopping at "completed"
followup_action=diagnose-stall- inspect logs and latest outputs
- retrieve
procedureplus relevantepisodememory - attempt the smallest safe recovery or replan
followup_action=diagnose-failure- inspect failure evidence
- retrieve relevant memory
- run the smallest safe recovery path, or replan if needed
followup_action=replan- update hypothesis and next step
- restart the loop with a new execution batch
Compact prompt form:
textWatch loop: 1. Poll the active action. 2. Read status, status_changed, progress_changed, followup_action, and last_log_tail. 3. If followup_action=continue-watch or wait-and-poll, choose the next sleep interval and keep ownership. 4. If followup_action=collect-results, inspect outputs immediately and continue analysis/validation. 5. If followup_action=diagnose-stall or diagnose-failure, inspect evidence, retrieve memory, and attempt the smallest safe recovery. 6. If followup_action=replan, update the route and continue execution. 7. Do not stop at a mere status update, and do not hand the task back to the user unless a true blocker remains.
Search, Memory, and Deep-Research Policy
Use these in combination:
memory-managerbootstrap is mandatory before planning/execution for non-trivial runs.- Every new user turn must retrieve relevant memory before planning continues.
- Every execution batch must retrieve
procedurememory before acting. - If a problem appears, a new error signature is observed, or repeated attempts are failing, retrieve
episodememory before the next fix attempt. - Before high-resource or irreversible actions, retrieve
procedureplus relevantepisodememory. - During planning, tradeoff analysis, contradiction resolution, or final answer shaping, retrieve
insightmemory. workingmemory reads are mandatory for resume/reconcile, compaction recovery, long-action resume, and final handoff; they are not the only retrieval path.- After every execution batch and every long-action poll cycle, write a concise
workingdelta. - After every stalled or failed poll result, retrieve
procedureplus relevantepisodememory before the next fix attempt. - After every completed poll result, inspect outputs and retrieve
insightmemory if interpretation, report writing, or tradeoff analysis is needed. - All external search must route through
deep-research; do not bypass it with ad hoc search. deep-researchmay choose light/default/deep execution depth internally, but it may not silently skip actual search.- If project-local memory retrieval is low-yield, shared-memory retrieval may query the configured local shared repo as a read-only source.
- If memory or DR is skipped, record
memory_skip_reasonordr_skip_reasonwith concrete evidence. - For unknown errors, use this branch:
- local evidence triage (logs, stack trace, recent changes)
- local memory retrieval (
procedure, thenepisode) - shared-memory retrieval when reusable SOPs or prior debug cases are likely relevant
deep-researchsearch if the issue is still unresolved or freshness-sensitive- minimal fix validation
- If compaction is detected, treat missing working reread as a workflow violation and recover before continuing.
- If deep research was used for open-ended scoping, call
Skill(skill: "research-plan")to convert findings into an execution-ready plan. Skip only if the user explicitly opts out.
Replanning Policy
Trigger replan when:
- major assumption fails
- repeated attempts show no improvement
- new evidence changes route significantly
- resource/risk profile changes
- a long-running action remains
stalledacross multiple polls - post-poll handling repeatedly produces no safe next step
Mode controls whether replan confirmation is required.
Stage Reporting Policy
At each stage completion or major todo completion:
- Save stage report under
<codex-cwd>/logs/runs/<run_id>/reports/. - Update
reports/index.mdwith status and timestamp. - In chat, provide a detailed summary plus report path.
- Do not block execution only because a stage report was emitted.
- If the stage depends on background work, include active action ids, latest liveness state, and next poll plan.
- If the stage delivers data-analysis results, include visualization outputs and saved figure paths (default:
<codex-cwd>/logs/runs/<run_id>/reports/figures/).
Mandatory Visualization Policy
Every report that presents quantitative results MUST include visualizations. This is non-negotiable.
- When writing any report (stage report, final report, evaluation summary) that contains numerical results, tables, or comparisons, you MUST generate matplotlib/code-based figures before finalizing the report.
- At minimum, generate:
- a ranking/comparison chart when multiple strategies, methods, or configurations are compared
- a breakdown chart when per-category/per-subject/per-level data is available
- a trend chart when results vary across an ordered dimension
- Save all figures to
<codex-cwd>/logs/runs/<run_id>/reports/figures/and embed them in the report markdown with relative paths. - Prefer code-generated assets that can be regenerated. Save the generation script alongside the figures.
- If the report scope is large or the visualizations need polished formatting, invoke
Skill(skill: "paper-writing")to handle the report writing and figure integration. - If you are unsure whether a report needs visualization, it does. Over-visualizing is acceptable; under-visualizing is a violation.
Shared Memory Export Gate
Do not export shared memory during core task execution.
- Complete the primary task first.
- Treat shared export as a post-task phase.
- Require
human-checkpointbefore publishing shared memory. - Sync the shared repo before opening the export PR.
Decision Policy
Use this order:
done: all compiled hard gates are satisfied with evidence.checkpoint: decision requires mode-based confirmation or safety gating.iterate: target is still unmet and a validated next step exists.replan: current route is weak, stale, or repeatedly failing to improve.blocked: hard blocker requires user input.
Done guard:
- If
completion_policy=until-target-or-hard-blocker,doneis forbidden while the active promotion gate or hard target remains unmet. - A single successful batch, a clean run, or a partial fix is not sufficient for
done. - If the final stretch target is not yet met but the current promotion gate is met, advance to the next gate instead of stopping.
Evidence Standard
Treat conclusions as valid only when backed by one or more:
- reproducible command output
- measurable metric movement
- file diff tied to behavior change
- corroborated external source
- durable liveness evidence for long-running actions
Required Cycle Output
At end of each cycle, emit:
Run: run_id, mode, current stageState: what is true nowEvidence: key observationsTodo: active/done/blocked highlightsNext Step: smallest safe actionReplan Need: yes or no, with reasonCheckpoint Need: yes or no, with reasonReport Path: stage report path or pending pathInteraction Channel:request_user_input|plain-text-fallback|noneGoal Status: primary target, active promotion gate, non-regression status, and whetherdoneis currently allowedMemory: retrieved layers, key hits, andmemory_skip_reasonwhen relevantDeep Research:dr_used=YES|NO, depth, anddr_skip_reasonor downgrade reasonLiveness: active action ids, current status, next poll time, and current poll interval when background work exists
Violation Recovery Policy
If user interaction was handled outside required routing in non-full-auto modes:
- Acknowledge non-compliance.
- Re-run the missed checkpoint using
human-checkpointand channel policy. - Re-evaluate downstream conclusions that depended on the missed checkpoint.
If a cycle ended while a long-running action had no watch or resume plan:
- Acknowledge the missing liveness protection.
- Persist or reconstruct the action record.
- Establish a poll or watcher plan before resuming normal work.
- Record the recovery step in the next stage report.


