ernanhughes commited on
Commit
e56d29d
·
verified ·
1 Parent(s): dd44920

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +1463 -11
README.md CHANGED
@@ -1,5 +1,5 @@
1
  ---
2
- title: Codex Manager
3
  emoji: 🧠
4
  colorFrom: yellow
5
  colorTo: indigo
@@ -7,19 +7,1471 @@ sdk: static
7
  pinned: false
8
  ---
9
 
10
- # Nerfies
11
 
12
- This is the repository that contains source code for the [Nerfies website](https://nerfies.github.io).
13
 
14
- If you find Nerfies useful for your work please cite:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  ```
16
- @article{park2021nerfies
17
- author = {Park, Keunhong and Sinha, Utkarsh and Barron, Jonathan T. and Bouaziz, Sofien and Goldman, Dan B and Seitz, Steven M. and Martin-Brualla, Ricardo},
18
- title = {Nerfies: Deformable Neural Radiance Fields},
19
- journal = {ICCV},
20
- year = {2021},
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  }
22
  ```
23
 
24
- # Website License
25
- <a rel="license" href="http://creativecommons.org/licenses/by-sa/4.0/"><img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by-sa/4.0/88x31.png" /></a><br />This work is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-sa/4.0/">Creative Commons Attribution-ShareAlike 4.0 International License</a>.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Codex Manager Building a Prompt-State Runtime for Hackathon-Grade Code Optimization
3
  emoji: 🧠
4
  colorFrom: yellow
5
  colorTo: indigo
 
7
  pinned: false
8
  ---
9
 
10
+ ## TL;DR
11
 
12
+ Codex Manager uses AI to generate code as an artifact, then tests that artifact, diagnoses what happened, and repairs the prompt state that produced it. The code is not the thing being optimized directly. The prompt state is.
13
 
14
+ ## Summary
15
+
16
+ [Humanity’s Last Hackathon](https://huggingface.co/humanitys-last-hackathon?utm_source=chatgpt.com) framed the challenge as a test of **context, not code**: the task was hard enough that the real question was not whether someone could hand-write one clever kernel, but whether they could build a system that used AI effectively under changing constraints.
17
+
18
+ **Codex Manager** is our attempt at that idea: a prompt-state runtime that manages Codex through candidate generation, isolated execution, diagnosis, repair, and verified promotion.
19
+
20
+ ## What Is Codex Manager?
21
+
22
+ Codex Manager starts from one simple claim:
23
+
24
+ > **Codex Manager optimizes PromptState, not code. Candidate code is evidence.**
25
+
26
+ Instead of treating generated code as the answer, the system treats it as a proposal that must survive a controlled loop.
27
+
28
+ Codex proposes a candidate diff. The manager applies it in an isolated workspace. Build, correctness, and benchmark gates decide whether the candidate is real. Failed attempts become diagnoses. Diagnoses become prompt deltas. Prompt deltas update the next `PromptState`. Only candidates that pass correctness and improve the benchmark are allowed to survive.
29
+
30
+ That shift from optimizing code directly to optimizing the state around code generation shaped the entire architecture.
31
+
32
+ Over the course of the build, Codex Manager grew from a small prompt-repair loop into a complete hackathon-style runtime:
33
+
34
+ - task packs
35
+ - shadow execution
36
+ - command benchmarks
37
+ - candidate executor registries
38
+ - reproducible run bundles
39
+ - submission packaging
40
+ - platform exports
41
+ - a full pipeline orchestrator
42
+ - a CLI that runs the workflow from the terminal
43
+
44
+ The result is not just a tool for one benchmark. It is a pattern for agentic coding systems:
45
+
46
+ ```mermaid
47
+ flowchart LR
48
+ %% Start of the loop
49
+ PS["🧠 PromptState<br/>(task, context, lessons, warnings, banned)"]
50
+
51
+ %% Codex generation
52
+ PS -->|"generate()"| C["🤖 Codex<br/>(candidate generator)"]
53
+ C -->|"unified diff"| AR["🔬 AttemptResult<br/>(applied, compiled, correct, speedup)"]
54
+
55
+ %% Evidence gates
56
+ AR -->|"fails gate"| D["🩺 AttemptDiagnosis<br/>(what failed & why)"]
57
+ AR -->|"passes & improves"| PROMO["✅ Promote Candidate<br/>(verified improvement)"]
58
+
59
+ %% Repair & feedback
60
+ D -->|"diagnosis → lesson"| PD["🔄 PromptDelta<br/>(new constraints, lessons, banned moves)"]
61
+ PD -->|"apply delta"| PS
62
+
63
+ %% Styling
64
+ classDef state fill:#e0f0ff,stroke:#3a6ea5,stroke-width:2px,color:#1a2b3c
65
+ classDef evidence fill:#fff7e0,stroke:#d9a34a,stroke-width:2px,color:#4a3a1a
66
+ classDef gate fill:#e6ffe6,stroke:#4a9d4a,stroke-width:2px,color:#1a3c1a
67
+ classDef promote fill:#e6ffe6,stroke:#4a9d4a,stroke-width:3px,color:#0a3d0a,font-weight:bold
68
+
69
+ class PS state
70
+ class C evidence
71
+ class AR evidence
72
+ class D gate
73
+ class PROMO promote
74
+ class PD state
75
+ ```
76
+
77
+ The model generates. The manager evaluates. The prompt state evolves. The artifacts prove what happened.
78
+
79
+ This post walks through that system from the first design decision to the final command-line pipeline, using a concrete `vector_add` example to show how the pieces fit together.
80
+
81
+ ---
82
+
83
+ ## The Core Idea: PromptState, Not Code
84
+
85
+ Once we stopped treating the hackathon as a code-writing contest, the design became much clearer.
86
+
87
+ The thing to optimize was not the kernel.
88
+
89
+ The thing to optimize was the **state around Codex**.
90
+
91
+ We called that state `PromptState`.
92
+
93
+ > PromptState is the evolving memory of the run: the constraints, lessons, warnings, and contracts that shape the next candidate.
94
+
95
+ Most code-generation systems treat the prompt as temporary. A prompt is assembled, sent to the model, and discarded. If the result fails, the next prompt is usually improvised: “try again,” “fix the bug,” “make it faster,” “preserve correctness this time.”
96
+
97
+ That works for small interactions. It does not work as an engineering loop.
98
+
99
+ A serious manager needs a structured object that says:
100
+
101
+ ```text
102
+ Here is what the model currently knows.
103
+ Here are the mistakes it has already made.
104
+ Here are the moves it is no longer allowed to make.
105
+ Here are the patterns it should preserve.
106
+ Here is the exact output contract it must obey.
107
+ ```
108
+
109
+ Codex Manager makes that explicit.
110
+
111
+ A `PromptState` is not just a prompt string. It is the working memory of the run.
112
+
113
+ ```python
114
+ class PromptStateDTO(BaseModel):
115
+ run_id: str
116
+ task_id: str
117
+ attempt_id: str
118
+
119
+ context_pack: str
120
+ system_prompt: str
121
+ user_prompt: str
122
+
123
+ prior_lessons: list[str] = Field(default_factory=list)
124
+ failure_warnings: list[str] = Field(default_factory=list)
125
+ success_patterns: list[str] = Field(default_factory=list)
126
+ banned_moves: list[str] = Field(default_factory=list)
127
+
128
+ output_contract: str
129
+ ```
130
+
131
+ This is the real optimization surface.
132
+
133
+ The code changes every attempt, but the state accumulates.
134
+
135
+ A candidate might fail because it returned prose instead of a diff. Another might apply cleanly but break correctness. Another might pass correctness and regress performance. Each of those outcomes teaches the manager something different. The next prompt should not merely be louder or longer. It should be **more informed**.
136
+
137
+ That is what `PromptState` gives us.
138
+
139
+ The loop becomes:
140
+
141
+ ```text
142
+ PromptState
143
+ → candidate generated by Codex
144
+ → candidate evaluated as evidence
145
+ → failure or success diagnosed
146
+ → prompt delta produced
147
+ → next PromptState
148
+ ```
149
+
150
+ Codex is still doing valuable work. It proposes code. But the manager decides how the next proposal should be shaped.
151
+
152
+ That is the central inversion:
153
+
154
+ > Codex generates candidates. Codex Manager evolves the conditions under which candidates are generated.
155
+
156
+ The candidate code is no longer treated as the final answer. It is treated as an experiment.
157
+
158
+ Did it apply cleanly?
159
+
160
+ Did it build?
161
+
162
+ Did it preserve correctness?
163
+
164
+ Did it improve the benchmark?
165
+
166
+ Did it violate the output contract?
167
+
168
+ Did it touch files it was not allowed to touch?
169
+
170
+ The answers become structured evidence. That evidence becomes a diagnosis. The diagnosis becomes a prompt delta. The prompt delta becomes the next `PromptState`.
171
+
172
+ For example, if a candidate weakens boundary behavior, the manager does not simply say:
173
+
174
+ ```text
175
+ Try again.
176
  ```
177
+
178
+ It updates the next prompt with something specific:
179
+
180
+ ```text
181
+ Previous attempt likely failed because boundary semantics were weakened.
182
+ Preserve bounds checks and mismatched-length behavior.
183
+ Do not assume aligned input sizes.
184
+ Return one valid unified diff against the target file only.
185
+ ```
186
+
187
+ If a candidate passes correctness but slows the benchmark, the next prompt changes differently:
188
+
189
+ ```text
190
+ The previous candidate was correct but slower.
191
+ Avoid extra branching, allocations, sleeps, or unnecessary memory traffic.
192
+ Target the measured hotspot directly.
193
+ Preserve the successful correctness structure.
194
+ ```
195
+
196
+ This gives the run a kind of external learning.
197
+
198
+ The model’s weights do not change. Codex does not become smarter inside the session. But the **context around Codex** becomes more precise, more constrained, and more informed by evidence.
199
+
200
+ That is why the distinction matters.
201
+
202
+ A normal agent loop says:
203
+
204
+ ```text
205
+ generate code
206
+ test code
207
+ retry
208
+ ```
209
+
210
+ Codex Manager says:
211
+
212
+ ```text
213
+ generate candidate
214
+ test candidate
215
+ diagnose evidence
216
+ repair PromptState
217
+ generate under improved constraints
218
+ ```
219
+
220
+ The benchmark still matters. The code still matters. But the thing being improved across attempts is the state that shapes the next candidate.
221
+
222
+ Below is the full prompt-state lifecycle:
223
+
224
+ ```mermaid
225
+ flowchart TD
226
+ A["🗂️ Task Pack<br/>goal, source, tests, benchmark, constraints"] --> B["🧠 PromptState<br/>context, lessons, warnings, banned moves, output contract"]
227
+
228
+ B --> C["🤖 Codex<br/>candidate generator"]
229
+ C --> D["📝 Candidate Diff<br/>proposed code change"]
230
+
231
+ D --> E["🛡️ Isolated Workspace<br/>apply patch safely"]
232
+ E --> F{"🧪 Build + Correctness<br/>passes?"}
233
+
234
+ F -- No --> G["🔬 AttemptResult<br/>failure evidence"]
235
+ F -- Yes --> H{"📊 Benchmark<br/>improves?"}
236
+
237
+ H -- No --> G
238
+ H -- Yes --> I["✅ Promote Candidate<br/>verified improvement"]
239
+
240
+ G --> J["🩺 AttemptDiagnosis<br/>what failed and why"]
241
+ J --> K["🔄 PromptDelta<br/>new constraints, lessons, banned moves"]
242
+ K --> B
243
+
244
+ I --> L["🗃️ Run Artifacts<br/>PROMPTS.log, reports, bundle, submission"]
245
+
246
+ classDef config fill:#f0f0ff,stroke:#6a6a9a,stroke-width:2px,color:#1a1a3c
247
+ classDef state fill:#e0f0ff,stroke:#3a6ea5,stroke-width:2px,color:#1a2b3c
248
+ classDef evidence fill:#fff7e0,stroke:#d9a34a,stroke-width:2px,color:#4a3a1a
249
+ classDef gate fill:#e6ffe6,stroke:#4a9d4a,stroke-width:2px,color:#1a3c1a
250
+
251
+ class A,L config
252
+ class B,K state
253
+ class C,D,G,J evidence
254
+ class E,F,H,I gate
255
+ ```
256
+
257
+ Codex does not learn inside the run.
258
+
259
+ The manager learns externally by turning execution evidence into prompt-state updates.
260
+
261
+ That is the core idea. The model generates. The harness verifies. The manager updates the state. The artifacts prove the path.
262
+
263
+ ---
264
+
265
+ ## The Loop: From Candidate to Evidence
266
+
267
+ Once `PromptState` became the thing we were optimizing, the next question was obvious:
268
+
269
+ > What counts as evidence?
270
+
271
+ A generated candidate is not evidence by itself. It is only a proposal.
272
+
273
+ Codex can return something that looks plausible, follows the shape of the prompt, and even compiles in your head. That does not mean it is correct. It does not mean it is safe. It does not mean it is faster. It does not even mean it is a valid patch.
274
+
275
+ So the manager has to turn every proposal into a structured result.
276
+
277
+ That is the job of `AttemptResult`.
278
+
279
+ In Codex Manager, an attempt is not “whatever the model said.” An attempt is what remains after the candidate has been tested by the system.
280
+
281
+ A simplified version looks like this:
282
+
283
+ ```python
284
+ class AttemptResultDTO(BaseModel):
285
+ run_id: str
286
+ task_id: str
287
+ attempt_id: str
288
+ prompt_hash: str
289
+
290
+ candidate_text: str = ""
291
+ patch_text: str = ""
292
+
293
+ applied: bool = False
294
+ compiled: bool = False
295
+ correctness_passed: bool = False
296
+ benchmark_passed: bool = False
297
+
298
+ baseline_ms: float | None = None
299
+ median_ms: float | None = None
300
+ speedup: float | None = None
301
+
302
+ failure_reason: str | None = None
303
+ raw_test_output: str = ""
304
+ raw_benchmark_output: str = ""
305
+
306
+ metadata: dict = Field(default_factory=dict)
307
+ ```
308
+
309
+ This object is how the system prevents hallucinated promotion.
310
+
311
+ A candidate is not “good” because it sounds good. It is not good because the model says it is optimized. It is not good because the diff looks clever.
312
+
313
+ It is good only if the evidence says it survived the gates.
314
+
315
+ An attempt begins when Codex returns a candidate, usually as a unified diff. The manager does not apply that diff to the real source tree. It creates an isolated workspace, copies the task files into it, and applies the patch there.
316
+
317
+ The flow is deliberately strict:
318
+
319
+ ```text
320
+ candidate diff
321
+ → isolated workspace
322
+ → safe patch application
323
+ → build gate
324
+ → correctness gate
325
+ → benchmark gate
326
+ → AttemptResult
327
+ ```
328
+
329
+ Each gate answers one question:
330
+
331
+ * **Patch gate:** Did the candidate apply cleanly, and did it only touch allowed files?
332
+ * **Build gate:** Does the modified target still compile or pass the syntax/build step?
333
+ * **Correctness gate:** Does the candidate preserve the required behavior?
334
+ * **Benchmark gate:** If correctness passed, did performance improve?
335
+
336
+ That “if correctness passed” matters.
337
+
338
+ A faster wrong answer is not an optimization. It is a bug with good timing.
339
+
340
+ So the benchmark is blocked unless correctness succeeds.
341
+
342
+ That rule became one of the central design constraints:
343
+
344
+ > **No benchmark result counts unless correctness passes.**
345
+
346
+ In practice, this prevents the manager from rewarding the most common failure mode in AI-generated optimization: removing necessary logic, weakening checks, changing edge-case behavior, or altering semantics in exchange for speed.
347
+
348
+ For example, in the `vector_add` task, the baseline implementation preserves Python `zip` semantics:
349
+
350
+ ```python
351
+ def vector_add(a, b):
352
+ return [x + y for x, y in zip(a, b)]
353
+ ```
354
+
355
+ A candidate might try to rewrite it as:
356
+
357
+ ```python
358
+ def vector_add(a, b):
359
+ return [a[i] + b[i] for i in range(len(a))]
360
+ ```
361
+
362
+ That looks reasonable for equal-length arrays. It may even appear faster in a narrow benchmark. But it breaks mismatched-length behavior:
363
+
364
+ ```python
365
+ vector_add([1, 2, 3], [10, 20])
366
+ ```
367
+
368
+ The correct result should preserve `zip` behavior:
369
+
370
+ ```python
371
+ [11, 22]
372
+ ```
373
+
374
+ The rewritten version can index past the shorter list and fail.
375
+
376
+ That failure becomes structured evidence:
377
+
378
+ ```json
379
+ {
380
+ "attempt_id": "attempt_001",
381
+ "applied": true,
382
+ "compiled": true,
383
+ "correctness_passed": false,
384
+ "benchmark_passed": false,
385
+ "failure_reason": "correctness_failed",
386
+ "raw_test_output": "IndexError: list index out of range"
387
+ }
388
+ ```
389
+
390
+ The important thing is not merely that the attempt failed.
391
+
392
+ The important thing is that the failure is now machine-readable.
393
+
394
+ The manager can diagnose it:
395
+
396
+ ```text
397
+ The candidate changed the iteration semantics and broke mismatched-length behavior.
398
+ ```
399
+
400
+ Then the next prompt can be repaired:
401
+
402
+ ```text
403
+ Preserve zip semantics.
404
+ Do not assume equal-length vectors.
405
+ Do not trade correctness for speed.
406
+ ```
407
+
408
+ A different candidate might pass correctness but regress the benchmark:
409
+
410
+ ```json
411
+ {
412
+ "attempt_id": "attempt_002",
413
+ "applied": true,
414
+ "compiled": true,
415
+ "correctness_passed": true,
416
+ "benchmark_passed": true,
417
+ "baseline_ms": 100.0,
418
+ "median_ms": 105.0,
419
+ "speedup": -0.05,
420
+ "failure_reason": "benchmark_regression"
421
  }
422
  ```
423
 
424
+ That is a very different kind of evidence.
425
+
426
+ The code is correct, but it is slower. So the next prompt should not focus on boundary semantics. It should focus on performance discipline:
427
+
428
+ ```text
429
+ The previous candidate was correct but slower.
430
+ Avoid extra branching, allocations, sleeps, or unnecessary memory traffic.
431
+ Target the measured hotspot directly.
432
+ ```
433
+
434
+ And if an attempt finally passes both gates:
435
+
436
+ ```json
437
+ {
438
+ "attempt_id": "attempt_003",
439
+ "applied": true,
440
+ "compiled": true,
441
+ "correctness_passed": true,
442
+ "benchmark_passed": true,
443
+ "baseline_ms": 100.0,
444
+ "median_ms": 84.0,
445
+ "speedup": 0.16,
446
+ "failure_reason": null
447
+ }
448
+ ```
449
+
450
+ then it can be promoted.
451
+
452
+ Not because Codex said it was better.
453
+
454
+ Not because the diff looked clever.
455
+
456
+ Because the evidence survived the gates.
457
+
458
+ This is the difference between autocomplete and engineering.
459
+
460
+ Codex Manager does not ask:
461
+
462
+ ```text
463
+ Does this answer look good?
464
+ ```
465
+
466
+ It asks:
467
+
468
+ ```text
469
+ Did it apply?
470
+ Did it build?
471
+ Did it preserve correctness?
472
+ Did it improve the benchmark?
473
+ What did we learn if it failed?
474
+ ```
475
+
476
+ The final candidate is only the visible output.
477
+
478
+ The real product is the evidence trail that explains why it was accepted.
479
+
480
+ ---
481
+
482
+ ## Diagnosis and Repair: Turning Failure into the Next Prompt
483
+
484
+ An important design was the split between diagnosis and repair:
485
+
486
+ ```text
487
+ AttemptResult → AttemptDiagnosis
488
+ AttemptDiagnosis → PromptDelta
489
+ ```
490
+
491
+ That split became one of the most important architectural choices in the system.
492
+
493
+ The diagnoser answers:
494
+
495
+ > What did the evidence show?
496
+
497
+ The repair policy answers:
498
+
499
+ > How should the next prompt change?
500
+
501
+ Those are not the same question.
502
+
503
+ A failed attempt contains raw evidence: exit codes, compiler output, test failures, benchmark numbers, patch-application errors, and metadata from the isolated workspace. The diagnoser’s job is to turn that raw evidence into a clear interpretation. It should say what failed, why it likely failed, how confident the system is, and what lesson should be carried forward.
504
+
505
+ The repair policy then decides how to mutate the next `PromptState`.
506
+
507
+ That separation matters because a test error should not be allowed to improvise the next instruction. The manager remains in control: evidence becomes diagnosis, diagnosis becomes a structured prompt delta, and only then does `PromptState` evolve.
508
+
509
+ In other words, failure does not trigger a vague retry.
510
+
511
+ Failure becomes a **controlled state transition**.
512
+
513
+ For example, given:
514
+
515
+ ```text
516
+ failure_reason = "bounds_check_missing"
517
+ ```
518
+
519
+ the diagnoser might produce:
520
+
521
+ ```text
522
+ Candidate removed or weakened boundary handling.
523
+ The next prompt must preserve boundary semantics and handle non-divisible input sizes.
524
+ ```
525
+
526
+ The repair policy then translates that diagnosis into explicit prompt-state changes:
527
+
528
+ ```yaml
529
+ user_additions:
530
+ - Explicitly preserve boundary checks and handle non-divisible input sizes.
531
+
532
+ new_failure_warnings:
533
+ - Previous attempt likely failed because boundary guards were missing or weakened.
534
+
535
+ new_banned_moves:
536
+ - Assume aligned sizes
537
+ - Remove tid/count guards
538
+ ```
539
+
540
+ That is very different from saying:
541
+
542
+ ```text
543
+ Try again.
544
+ ```
545
+
546
+ The system now knows *what kind* of retry it is performing.
547
+
548
+ A `compilation_failed` diagnosis produces a different repair:
549
+
550
+ ```yaml
551
+ system_additions:
552
+ - Preserve public interfaces, function names, signatures, buffer bindings, and required imports.
553
+
554
+ user_additions:
555
+ - Before changing syntax, compare against the baseline and keep the smallest compilable edit.
556
+
557
+ new_banned_moves:
558
+ - Pseudocode
559
+ - Undefined symbols
560
+ - Changed public interface
561
+ ```
562
+
563
+ A `benchmark_regression` produces a different repair again:
564
+
565
+ ```yaml
566
+ user_additions:
567
+ - The previous candidate was correct but slower.
568
+ - Target a smaller hotspot-specific optimization.
569
+ - Avoid extra branching, sleeps, allocations, or unnecessary memory traffic.
570
+
571
+ new_failure_warnings:
572
+ - Previous candidate regressed benchmark performance.
573
+ ```
574
+
575
+ This is the point of the split. The manager does not treat all failures as equal. A syntax failure, a correctness failure, a benchmark regression, and a malformed model response all require different prompt changes.
576
+
577
+ Once failures are typed this way, the manager can build a small operating manual for itself:
578
+
579
+ | Failure | What the diagnoser sees | How the prompt is repaired |
580
+ | ----------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------- |
581
+ | `candidate_generation_failed` | The executor failed to return a usable candidate | Simplify the output contract; require one valid artifact only |
582
+ | `patch_apply_failed` | The candidate was not a clean diff or touched the wrong file | Require a minimal unified diff against the exact target file |
583
+ | `compilation_failed` | Syntax, imports, interface, or build contract broke | Preserve signatures, imports, bindings, and public interface |
584
+ | `correctness_failed` | Behavior changed even if the code built | Preserve semantics before optimizing speed |
585
+ | `bounds_check_missing` | Boundary or size assumptions broke edge cases | Preserve bounds checks and handle non-divisible sizes |
586
+ | `benchmark_regression` | Candidate was correct but slower | Avoid extra branching, allocation, sync, or memory traffic |
587
+ | `benchmark_failed` | Benchmark crashed or stopped emitting required metrics | Preserve benchmark compatibility and output format |
588
+
589
+ That table is the manager’s memory during a run.
590
+
591
+ It is not memory in the model weights. It is memory in the surrounding system. The next prompt becomes more constrained because the last attempt produced evidence.
592
+
593
+ This gives the loop its shape:
594
+
595
+ ```text
596
+ Attempt fails
597
+ → evidence is classified
598
+ → diagnosis records the lesson
599
+ → repair policy mutates PromptState
600
+ → next attempt is generated under better constraints
601
+ ```
602
+
603
+ The prompt state evolves through structured deltas, not ad-hoc string rewrites.
604
+
605
+ That is what makes the process traceable. Every prompt change can be connected back to a specific attempt, a specific failure class, and a specific repair rule. When the final candidate is promoted, we can inspect the path that led there:
606
+
607
+ ```text
608
+ attempt_001/
609
+ result.json
610
+ diagnosis.md
611
+ next_prompt_delta.md
612
+
613
+ attempt_002/
614
+ result.json
615
+ diagnosis.md
616
+ next_prompt_delta.md
617
+
618
+ attempt_003/
619
+ result.json
620
+ diagnosis.md
621
+ next_prompt_delta.md
622
+ ```
623
+
624
+ The final code is not floating in space. It has provenance. The retry is more than a loop around the same mistake.
625
+
626
+ ---
627
+
628
+ ## The Staircase We Built
629
+
630
+ We built Codex Manager in layers.
631
+
632
+ Each layer has one job, and each job removes one source of instability from the system. The result looks like a pipeline because that is what it is: a layered runtime where candidates move from context, to execution, to evidence, to packaging.
633
+
634
+ This is the current layer stack:
635
+
636
+ | Step | Layer | Job | What it stabilizes |
637
+ | ---- | --------------------- | ----------------------------------------------------- | ------------------------------------------------------- |
638
+ | 1 | Prompt-state loop | Turn attempt results into prompt updates | Ad-hoc retrying |
639
+ | 2 | Runtime contract | Define the engine/facade/profile boundary | Hardcoded execution paths |
640
+ | 3 | Shadow execution | Apply and test candidates in isolated workspaces | Blind mutation of real source |
641
+ | 4 | Executor registry | Swap mock, scripted, and live candidate generators | Model lock-in |
642
+ | 5 | Task packs | Load external task definitions from YAML/JSON | Hardcoded benchmark problems |
643
+ | 6 | Run bundles | Preserve complete run artifacts and replay metadata | Unreplayable runs |
644
+ | 7 | Command adapter | Run build, correctness, and benchmark commands | Toy-only evaluation |
645
+ | 8 | Submission packager | Convert run evidence into judge-ready artifacts | Messy or incomplete submission outputs |
646
+ | 9 | Platform adapters | Translate submissions into target platform layouts | Platform-specific branch logic inside the core runtime |
647
+ | 10 | Pipeline orchestrator | Run the full workflow as one deterministic sequence | Manual multi-step operation |
648
+ | 11 | CLI | Expose the pipeline as terminal commands and profiles | Python-snippet operation under pressure |
649
+
650
+ The important thing is that the layer stack keeps the system understandable. Each part has a narrow responsibility, and the whole thing composes into a pipeline.
651
+
652
+ ---
653
+
654
+ ## Cold Example 1: A Portable `vector_add` Task Pack
655
+
656
+ The task pack is where the system stops being a demo. It is the contract between the outside world and the manager: the problem, source file, allowed patch paths, build command, correctness command, benchmark command, output contract, and known failure modes.
657
+
658
+ ```yaml
659
+ task_id: command_vector_add_pack
660
+ profile: kernel_optimization
661
+ goal: Optimize the command-mode vector_add kernel while preserving correctness.
662
+ max_attempts: 3
663
+
664
+ execution:
665
+ mode: command
666
+ source_dir: source
667
+ target_file: kernel.py
668
+ allowed_patch_paths:
669
+ - kernel.py
670
+ build_command: python -m py_compile kernel.py
671
+ correctness_command: python test_kernel.py
672
+ benchmark_command: python bench_kernel.py
673
+ benchmark_output_format: key_value
674
+ baseline_key: baseline_ms
675
+ score_key: median_ms
676
+ higher_is_better: false
677
+ baseline_ms: 100.0
678
+ target_speedup: 0.10
679
+
680
+ context:
681
+ operation_name: vector_add
682
+ hardware_target: deterministic_python_command
683
+ output_contract: Return one valid unified diff against kernel.py and nothing else.
684
+ correctness_contract:
685
+ - Preserve vector_add(a, b) behavior.
686
+ - Do not modify tests or benchmarks.
687
+ - Handle empty vectors.
688
+ - Handle mismatched vector lengths using zip semantics.
689
+ benchmark_contract:
690
+ - Benchmark output must print baseline_ms=<float>.
691
+ - Benchmark output must print median_ms=<float>.
692
+ - Lower median_ms is better.
693
+ known_failure_modes:
694
+ - Touching test files invalidates the candidate.
695
+ - Syntax errors fail the build gate.
696
+ - Removing zip semantics may break mismatched length behavior.
697
+ ```
698
+
699
+ There is no hidden Python factory here. The task defines its own source, target, tests, benchmark, output contract, failure modes, and scoring semantics.
700
+
701
+ This is important because the task is no longer hardcoded into Python. The manager can ingest it, build a context pack, run the same loop, and produce the same audit trail for any task that follows the contract.
702
+
703
+ ---
704
+
705
+ ## Cold Example 2: Command-Driven Evaluation
706
+
707
+ The command runner turns a candidate diff into evidence.
708
+
709
+ For each candidate, it runs a strict five-phase pipeline:
710
+
711
+ ```text
712
+ Patch → Build → Correctness → Benchmark → Metric parse
713
+ ```
714
+
715
+ The benchmark harness emits simple key-value output:
716
+
717
+ ```text
718
+ baseline_ms=100.0
719
+ median_ms=84.0
720
+ ```
721
+
722
+ The parser computes `speedup = (baseline_ms - median_ms) / baseline_ms`, giving `(100.0 - 84.0) / 100.0 = 0.16`. A 16% speedup only matters if correctness passed first.
723
+
724
+ Here’s the actual attempt chain observed in a mock run:
725
+
726
+ - **Attempt 1:** patch applies, build passes, correctness fails → `failure_reason = correctness_failed` → prompt adds: *preserve zip semantics*
727
+ - **Attempt 2:** correctness passes, benchmark regresses → `failure_reason = benchmark_regression` → prompt adds: *avoid extra branching and allocations*
728
+ - **Attempt 3:** correctness passes, benchmark improves → **promoted**
729
+
730
+ This deterministic progression proves that the manager can recover from both safety and performance failures without human intervention.
731
+
732
+ ---
733
+
734
+ ## Cold Example 3: One Command Pipeline
735
+
736
+ By the end, the whole workflow became one terminal command:
737
+
738
+ ```bash
739
+ writer codex-manager pipeline run \
740
+ --task examples/codex_manager/command_vector_add/task.yaml \
741
+ --output-root runs/blog_vector_add_smoke \
742
+ --platform generic_command \
743
+ --executor mock \
744
+ --create-zip \
745
+ --overwrite
746
+ ```
747
+
748
+ A real smoke run produced:
749
+
750
+ ```text
751
+ Pipeline run
752
+ Status: completed
753
+ Pipeline id: pipe_e140aaaa0ae6
754
+ Run id: cmrun_dbc92100fcb7
755
+ Submission id: submission_384f757e2f35
756
+ Platform export id: export_189cb76315d3
757
+ Submission zip path: runs/blog_vector_add_smoke/submission.zip
758
+ Pipeline report: runs/blog_vector_add_smoke/pipeline_report.md
759
+
760
+ Pipeline validation
761
+ Valid: True
762
+ ```
763
+
764
+ That single command runs:
765
+
766
+ ```text
767
+ task pack load
768
+ → prompt-state optimization
769
+ → command execution
770
+ → bundle generation
771
+ → submission packaging
772
+ → platform export
773
+ → validation
774
+ ```
775
+
776
+ ---
777
+
778
+ ## The Artifact Trail: Evidence Has Structure
779
+
780
+ By the time a run finishes, Codex Manager has not only produced a candidate. It has produced a trail.
781
+
782
+ That trail matters because agentic code systems are otherwise hard to inspect. A model may return a plausible answer, but without the surrounding evidence we cannot tell whether the answer was lucky, verified, overfit, unsafe, or simply accepted because no one looked closely enough.
783
+
784
+ Codex Manager writes the evidence down.
785
+
786
+ At the attempt level, each executed attempt gets its own directory:
787
+
788
+ ```text
789
+ attempts/
790
+ attempt_001/
791
+ prompt.md
792
+ result.json
793
+ diagnosis.md
794
+ next_prompt_delta.md
795
+
796
+ attempt_002/
797
+ prompt.md
798
+ result.json
799
+ diagnosis.md
800
+ next_prompt_delta.md
801
+
802
+ attempt_003/
803
+ prompt.md
804
+ result.json
805
+ diagnosis.md
806
+ next_prompt_delta.md
807
+ ```
808
+
809
+ That directory is the chain of custody for each candidate.
810
+
811
+ * `prompt.md` shows what Codex saw.
812
+ * `result.json` shows what happened when the candidate was executed.
813
+ * `diagnosis.md` explains what the evidence meant.
814
+ * `next_prompt_delta.md` shows how the next prompt changed.
815
+
816
+ A run also keeps a separate timeline of prompt states:
817
+
818
+ ```text
819
+ prompt_states/
820
+ attempt_001/
821
+ prompt.md
822
+ attempt_002/
823
+ prompt.md
824
+ attempt_003/
825
+ prompt.md
826
+ attempt_004/
827
+ prompt.md
828
+ ```
829
+
830
+ That distinction matters.
831
+
832
+ `attempts/` contains candidates that were actually executed. `prompt_states/` contains the evolving state of the run, including the next prompt state that would be used if another attempt were needed.
833
+
834
+ So the final unexecuted next state can still be inspected, but it does not masquerade as an executed attempt.
835
+
836
+ This gives the artifact model clean boundaries:
837
+
838
+ ```text
839
+ attempts/
840
+ attempt_001/
841
+ prompt.md
842
+ result.json
843
+ diagnosis.md
844
+ next_prompt_delta.md
845
+
846
+ prompt_states/
847
+ attempt_004/
848
+ prompt.md
849
+ ```
850
+
851
+ At the run level, Codex Manager writes:
852
+
853
+ ```text
854
+ run_manifest.json
855
+ context_pack.md
856
+ PROMPTS.log
857
+ report.md
858
+ validation.json
859
+ best/
860
+ ```
861
+
862
+ At the submission level, it writes:
863
+
864
+ ```text
865
+ submission_manifest.json
866
+ README.md
867
+ summary.json
868
+ prompt_evolution.json
869
+ evidence/
870
+ best/
871
+ ```
872
+
873
+ And once the full pipeline runs, it writes:
874
+
875
+ ```text
876
+ pipeline_manifest.json
877
+ pipeline_summary.json
878
+ pipeline_report.md
879
+ pipeline_events.jsonl
880
+ task_run/
881
+ submission/
882
+ platform_export/
883
+ ```
884
+
885
+ The pipeline manifest ties the whole chain together with IDs and hashes:
886
+
887
+ ```json
888
+ {
889
+ "status": "completed",
890
+ "pipeline_id": "pipe_5298de9da2df",
891
+ "run_id": "cmrun_b608c9be1db5",
892
+ "submission_id": "submission_01281797e2a5",
893
+ "platform_export_id": "export_efdbf4e960b2",
894
+ "chain_of_custody": {
895
+ "run_bundle": "446b95950ed91687a24016450ff310e9bb37b80a44794147c053416b892ba214",
896
+ "submission": "9afec5d1f8f7587e491fd3f7264495a6138a1a881c27e1b2bd30535fa20cee52",
897
+ "platform_export": "6960142bad20b2d16b60693bc111e9c2b59bc7a9dddac9b439ef0b53389c4bb8"
898
+ }
899
+ }
900
+ ```
901
+
902
+ That is the point of the artifact trail.
903
+
904
+ The system is not asking anyone to trust a generated file. It preserves the context, the candidate, the execution result, the diagnosis, the repair, the submission, and the export.
905
+
906
+ A judge can inspect it. A developer can replay it. A future run can use the same evidence to improve the next context.
907
+
908
+ The final code is only the visible tip of the run. The artifact trail is the proof that it deserved to survive.
909
+
910
+ ---
911
+
912
+ ## Make the AI Work Harder
913
+
914
+ The point of Codex Manager is to make the AI work harder.
915
+
916
+ A normal coding assistant can produce an answer and move on. If the answer is wrong, the burden falls back on the human: find the bug, explain the failure, rewrite the prompt, run the test again, decide whether the next version is better.
917
+
918
+ That is useful, but it is still mostly human-managed.
919
+
920
+ For this hackathon, the challenge was framed around **context**. Our interpretation was simple: if context is the thing being judged, then the system should not rely on a human manually carrying that context from one attempt to the next. The system itself should preserve the context, update it, and force the next attempt to deal with what happened before.
921
+
922
+ That is what Codex Manager is trying to demonstrate.
923
+
924
+ It gives the AI a structured environment where it cannot simply produce code and disappear. Every candidate has to pass through the same loop:
925
+
926
+ ```text
927
+ generate candidate
928
+ → apply it safely
929
+ → build it
930
+ → test correctness
931
+ → benchmark it
932
+ → diagnose failure
933
+ → repair the next prompt
934
+ → try again under better constraints
935
+ ```
936
+
937
+ The model still proposes the code. But the surrounding system makes the model face evidence.
938
+
939
+ If the model returns prose instead of a diff, the next prompt gets stricter.
940
+
941
+ If the candidate breaks correctness, the next prompt carries that lesson.
942
+
943
+ If the candidate passes correctness but slows the benchmark, the next prompt changes again.
944
+
945
+ If the candidate succeeds, the system promotes it and preserves the trail.
946
+
947
+ This is what we mean by making the AI work harder. We are not just asking it for a better answer. We are building the conditions under which it has to produce one.
948
+
949
+ The manager gives the AI something closer to an external working memory:
950
+
951
+ * what the task is
952
+ * what the output contract is
953
+ * what failed before
954
+ * what moves are banned
955
+ * what patterns should be preserved
956
+ * what the benchmark actually measured
957
+ * what evidence is required before promotion
958
+
959
+ That is the context: an evolving control system where each attempt leaves evidence that shapes the next one.
960
+
961
+ ```mermaid
962
+ flowchart TD
963
+ A["🧠 PromptState"] --> B["🤖 Generate Candidate"]
964
+ B --> C["🛡️ Apply Candidate<br/>in Isolated Workspace"]
965
+ C --> D["🔍 Validate Attempt"]
966
+
967
+ D --> E{"Passed?"}
968
+
969
+ E -- No --> F["🩺 Diagnose Failure"]
970
+ F --> G["🔄 Repair PromptState"]
971
+ G --> A
972
+
973
+ E -- Yes --> H["✅ Promote Candidate"]
974
+ H --> I["🎯 Verified Solution"]
975
+
976
+ subgraph Validation
977
+ D1["⚙️ Build / Compile"]
978
+ D2["🧪 Correctness Tests"]
979
+ D3["📊 Benchmark / Performance"]
980
+ end
981
+
982
+ D --> D1
983
+ D --> D2
984
+ D --> D3
985
+
986
+ classDef state fill:#e0f0ff,stroke:#3a6ea5,stroke-width:2px,color:#1a2b3c
987
+ classDef evidence fill:#fff7e0,stroke:#d9a34a,stroke-width:2px,color:#4a3a1a
988
+ classDef gate fill:#e6ffe6,stroke:#4a9d4a,stroke-width:2px,color:#1a3c1a
989
+
990
+ class A,G state
991
+ class B,F,I evidence
992
+ class C,D,E,H gate
993
+ class D1,D2,D3 gate
994
+ ```
995
+
996
+ This is how we chose to approach the hackathon. If the problem is too broad or too difficult to solve reliably by hand, then the useful demonstration is a system that lets the AI iterate under constraint.
997
+
998
+ It generates a candidate, tests it, records what happened, repairs the next prompt state, and tries again.
999
+
1000
+ It may reach the final solution. It may not. But it gives the AI a structured way to improve its attempts, and it leaves behind artifacts that show the path it took.
1001
+
1002
+ That is our answer to the “context, not code” framing.
1003
+
1004
+ ---
1005
+
1006
+ ## What Comes Next: Applying the Manager
1007
+
1008
+ The next step is to apply Codex Manager to harder tasks.
1009
+
1010
+ The shape is now in place:
1011
+
1012
+ ```text
1013
+ Task Pack
1014
+ → PromptState
1015
+ → Candidate
1016
+ → Isolated Execution
1017
+ → Evidence
1018
+ → Diagnosis
1019
+ → PromptDelta
1020
+ → Run Bundle
1021
+ → Submission
1022
+ → Platform Export
1023
+ ```
1024
+
1025
+ A new target can bring a new source file, a new build command, a new correctness harness, a new benchmark, and a new platform export. The prompt-state loop remains the same.
1026
+
1027
+ For a real kernel task, the path is straightforward:
1028
+
1029
+ ```text
1030
+ Task Pack
1031
+ → Command Mode
1032
+ → Metal build command
1033
+ → Metal correctness harness
1034
+ → Metal benchmark command
1035
+ → same PromptState loop
1036
+ ```
1037
+
1038
+ That is the point of the architecture.
1039
+ The hackathon was the forcing function. The pattern is the output.
1040
+
1041
+ ---
1042
+
1043
+ ---
1044
+
1045
+ ## References
1046
+
1047
+ [Humanity’s Last Hackathon](https://huggingface.co/humanitys-last-hackathon?utm_source=chatgpt.com)
1048
+
1049
+ [How To Win Humanity's Last Hackathon - The hardest agent contest in AI.](https://www.youtube.com/watch?v=xRFuPkp4iP8)
1050
+
1051
+ [OpenAI Codex Documentation](https://developers.openai.com/codex) OpenAI’s documentation for Codex as a coding agent for software development. Useful background for readers who want to understand the Codex product surface and workflow model.
1052
+
1053
+ [Codex CLI Documentation](https://developers.openai.com/codex/cli) Documentation for running Codex locally from the terminal. This is especially relevant to the Codex Manager idea because it frames Codex as a coding agent that can read, change, and run code in a local directory.
1054
+
1055
+ [Codex CLI Reference](https://developers.openai.com/codex/cli/reference) Command and flag reference for Codex CLI. Useful for readers who want to compare Codex Manager’s CLI/pipeline approach with OpenAI’s Codex CLI surface.
1056
+
1057
+ [Codex Web / Cloud Documentation](https://developers.openai.com/codex/cloud) Documentation for delegating coding tasks to Codex in a cloud environment.
1058
+
1059
+ [Codex Skills Documentation](https://developers.openai.com/codex/skills) Documentation on Codex skills and reusable workflows. Relevant to the broader idea of treating context and workflow structure as first-class parts of agentic coding.
1060
+
1061
+ ---
1062
+
1063
+ ## Appendix A: The Codex Manager Loop in Pseudo-Code
1064
+
1065
+ The full implementation has engines, facades, registries, task packs, validators, run bundles, submissions, platform adapters, and a CLI. But the core idea is much smaller.
1066
+
1067
+ At the center is one loop:
1068
+
1069
+ ```text
1070
+ PromptState
1071
+ → Candidate
1072
+ → AttemptResult
1073
+ → AttemptDiagnosis
1074
+ → PromptDelta
1075
+ → next PromptState
1076
+ ```
1077
+
1078
+ Here is that loop in pseudo-code.
1079
+
1080
+ ```python
1081
+ def solve(task_pack, executor, profile, max_attempts):
1082
+ """
1083
+ Solve a task by evolving PromptState, not by trusting generated code.
1084
+ """
1085
+
1086
+ # 1. Load task and build initial context.
1087
+ task = load_task_pack(task_pack)
1088
+ context_pack = build_context_pack(task)
1089
+
1090
+ state = PromptState(
1091
+ task_id=task.id,
1092
+ context_pack=context_pack,
1093
+ prior_lessons=[],
1094
+ failure_warnings=[],
1095
+ banned_moves=[],
1096
+ success_patterns=[],
1097
+ output_contract="Return one valid unified diff and nothing else.",
1098
+ )
1099
+
1100
+ attempts = []
1101
+
1102
+ # 2. Iterate until budget is exhausted or a verified candidate is found.
1103
+ for attempt_index in range(max_attempts):
1104
+ # Codex is a candidate generator, not the source of truth.
1105
+ candidate = executor.generate(state)
1106
+
1107
+ # The profile decides how this task is evaluated.
1108
+ # For command-mode tasks, this means:
1109
+ # patch -> build -> correctness -> benchmark -> metrics
1110
+ result = profile.run_candidate(
1111
+ task=task,
1112
+ state=state,
1113
+ candidate=candidate,
1114
+ )
1115
+
1116
+ attempts.append(result)
1117
+
1118
+ # A candidate only survives if it passes the gates.
1119
+ if result.correctness_passed and result.benchmark_passed and result.speedup > 0:
1120
+ promote(result)
1121
+ break
1122
+
1123
+ # 3. Convert evidence into a diagnosis.
1124
+ diagnosis = diagnose(result)
1125
+
1126
+ # 4. Convert diagnosis into a prompt delta.
1127
+ delta = repair_prompt(diagnosis)
1128
+
1129
+ # 5. Produce the next PromptState.
1130
+ state = apply_delta(state, delta)
1131
+
1132
+ # 6. Preserve the evidence trail.
1133
+ return write_run_bundle(
1134
+ task=task,
1135
+ attempts=attempts,
1136
+ final_state=state,
1137
+ )
1138
+ ```
1139
+
1140
+ That is the heart of the system.
1141
+
1142
+ Codex generates candidates. The manager turns those candidates into evidence. The evidence changes the next prompt.
1143
+
1144
+ ---
1145
+
1146
+ ### The Candidate Is Not Trusted
1147
+
1148
+ The executor only returns text:
1149
+
1150
+ ```python
1151
+ class CandidateExecutor:
1152
+ def generate(self, state: PromptState) -> str:
1153
+ """
1154
+ Return a candidate artifact.
1155
+
1156
+ Usually this is a unified diff.
1157
+ It may come from a mock executor, a scripted executor,
1158
+ or a live Codex/OpenAI-compatible executor.
1159
+ """
1160
+ ...
1161
+ ```
1162
+
1163
+ The executor does not validate the candidate. It does not repair the prompt. It does not promote anything.
1164
+
1165
+ It only generates.
1166
+
1167
+ ---
1168
+
1169
+ ### The Profile Turns a Candidate into Evidence
1170
+
1171
+ A profile knows how to evaluate a task.
1172
+
1173
+ For a command-mode task, evaluation looks like this:
1174
+
1175
+ ```python
1176
+ def run_candidate(task, state, candidate_diff):
1177
+ workspace = create_isolated_workspace(task.source_dir)
1178
+
1179
+ patch = apply_patch(
1180
+ workspace=workspace,
1181
+ patch_text=candidate_diff,
1182
+ allowed_paths=task.allowed_patch_paths,
1183
+ )
1184
+
1185
+ if not patch.applied:
1186
+ return AttemptResult(
1187
+ applied=False,
1188
+ compiled=False,
1189
+ correctness_passed=False,
1190
+ benchmark_passed=False,
1191
+ failure_reason="patch_apply_failed",
1192
+ raw_test_output=patch.error,
1193
+ )
1194
+
1195
+ build = run_command(task.build_command, cwd=workspace)
1196
+
1197
+ if not build.passed:
1198
+ return AttemptResult(
1199
+ applied=True,
1200
+ compiled=False,
1201
+ correctness_passed=False,
1202
+ benchmark_passed=False,
1203
+ failure_reason="compilation_failed",
1204
+ raw_test_output=build.output,
1205
+ )
1206
+
1207
+ correctness = run_command(task.correctness_command, cwd=workspace)
1208
+
1209
+ if not correctness.passed:
1210
+ return AttemptResult(
1211
+ applied=True,
1212
+ compiled=True,
1213
+ correctness_passed=False,
1214
+ benchmark_passed=False,
1215
+ failure_reason=classify_correctness_failure(correctness.output),
1216
+ raw_test_output=correctness.output,
1217
+ )
1218
+
1219
+ benchmark = run_command(task.benchmark_command, cwd=workspace)
1220
+ metrics = parse_benchmark_output(benchmark.output)
1221
+
1222
+ if not benchmark.passed or not metrics.valid:
1223
+ return AttemptResult(
1224
+ applied=True,
1225
+ compiled=True,
1226
+ correctness_passed=True,
1227
+ benchmark_passed=False,
1228
+ failure_reason="benchmark_failed",
1229
+ raw_benchmark_output=benchmark.output,
1230
+ )
1231
+
1232
+ speedup = compute_speedup(metrics)
1233
+
1234
+ return AttemptResult(
1235
+ applied=True,
1236
+ compiled=True,
1237
+ correctness_passed=True,
1238
+ benchmark_passed=True,
1239
+ baseline_ms=metrics["baseline_ms"],
1240
+ median_ms=metrics["median_ms"],
1241
+ speedup=speedup,
1242
+ failure_reason=None if speedup > 0 else "benchmark_regression",
1243
+ raw_test_output=correctness.output,
1244
+ raw_benchmark_output=benchmark.output,
1245
+ )
1246
+ ```
1247
+
1248
+ The key rule is:
1249
+
1250
+ ```python
1251
+ if not correctness.passed:
1252
+ do_not_run_benchmark()
1253
+ ```
1254
+
1255
+ A faster wrong answer is not an optimization.
1256
+
1257
+ ---
1258
+
1259
+ ### Diagnosis Interprets Evidence
1260
+
1261
+ The diagnoser does not edit the prompt. It only classifies what happened.
1262
+
1263
+ ```python
1264
+ def diagnose(result):
1265
+ if result.failure_reason == "patch_apply_failed":
1266
+ return AttemptDiagnosis(
1267
+ failure_class="patch_apply_failed",
1268
+ prompt_lesson=(
1269
+ "The candidate was not a clean patch. "
1270
+ "The next prompt must require one valid unified diff against the target file."
1271
+ ),
1272
+ )
1273
+
1274
+ if result.failure_reason == "compilation_failed":
1275
+ return AttemptDiagnosis(
1276
+ failure_class="compilation_failed",
1277
+ prompt_lesson=(
1278
+ "The candidate failed to build. "
1279
+ "The next prompt must preserve valid syntax, imports, function names, and public interfaces."
1280
+ ),
1281
+ )
1282
+
1283
+ if result.failure_reason == "correctness_failed":
1284
+ return AttemptDiagnosis(
1285
+ failure_class="correctness_failed",
1286
+ prompt_lesson=(
1287
+ "The candidate changed behavior. "
1288
+ "The next prompt must preserve semantics before optimizing speed."
1289
+ ),
1290
+ )
1291
+
1292
+ if result.failure_reason == "benchmark_regression":
1293
+ return AttemptDiagnosis(
1294
+ failure_class="benchmark_regression",
1295
+ prompt_lesson=(
1296
+ "The candidate was correct but slower. "
1297
+ "The next prompt must target a smaller hotspot and avoid extra branching or allocation."
1298
+ ),
1299
+ )
1300
+
1301
+ return AttemptDiagnosis(
1302
+ failure_class="unknown",
1303
+ prompt_lesson="Make a smaller, safer change and preserve the baseline behavior.",
1304
+ )
1305
+ ```
1306
+
1307
+ This keeps interpretation separate from mutation.
1308
+
1309
+ ---
1310
+
1311
+ ### Repair Mutates PromptState
1312
+
1313
+ The repair policy converts a diagnosis into a structured prompt update.
1314
+
1315
+ ```python
1316
+ def repair_prompt(diagnosis):
1317
+ delta = PromptDelta()
1318
+
1319
+ if diagnosis.failure_class == "patch_apply_failed":
1320
+ delta.system_additions.append(
1321
+ "Return one valid unified diff against the exact target file."
1322
+ )
1323
+ delta.banned_moves.extend([
1324
+ "Conversational response",
1325
+ "Whole-file rewrite unless explicitly requested",
1326
+ "Touching unrelated files",
1327
+ ])
1328
+
1329
+ if diagnosis.failure_class == "compilation_failed":
1330
+ delta.system_additions.append(
1331
+ "Preserve imports, function names, signatures, and public interfaces."
1332
+ )
1333
+ delta.banned_moves.extend([
1334
+ "Pseudocode",
1335
+ "Undefined symbols",
1336
+ "Changed public interface",
1337
+ ])
1338
+
1339
+ if diagnosis.failure_class == "correctness_failed":
1340
+ delta.user_additions.append(
1341
+ "Preserve the baseline semantics before attempting performance improvements."
1342
+ )
1343
+
1344
+ if diagnosis.failure_class == "benchmark_regression":
1345
+ delta.user_additions.append(
1346
+ "The previous candidate was correct but slower. "
1347
+ "Avoid extra branching, sleeps, allocations, or unnecessary memory traffic."
1348
+ )
1349
+
1350
+ delta.prior_lessons.append(diagnosis.prompt_lesson)
1351
+ return delta
1352
+ ```
1353
+
1354
+ The repair is explicit. It is not an improvised “try harder.”
1355
+
1356
+ ---
1357
+
1358
+ ### PromptState Carries the Loop Forward
1359
+
1360
+ Applying the delta creates the next state:
1361
+
1362
+ ```python
1363
+ def apply_delta(state, delta):
1364
+ return PromptState(
1365
+ task_id=state.task_id,
1366
+ context_pack=state.context_pack,
1367
+
1368
+ system_prompt=state.system_prompt + "\n" + "\n".join(delta.system_additions),
1369
+ user_prompt=state.user_prompt + "\n" + "\n".join(delta.user_additions),
1370
+
1371
+ prior_lessons=state.prior_lessons + delta.prior_lessons,
1372
+ failure_warnings=state.failure_warnings + delta.failure_warnings,
1373
+ banned_moves=dedupe(state.banned_moves + delta.banned_moves),
1374
+ success_patterns=dedupe(state.success_patterns + delta.success_patterns),
1375
+
1376
+ output_contract=state.output_contract,
1377
+ attempt_index=state.attempt_index + 1,
1378
+ )
1379
+ ```
1380
+
1381
+ The model’s weights do not change.
1382
+
1383
+ The context around the model changes.
1384
+
1385
+ That is the point.
1386
+
1387
+ ---
1388
+
1389
+ ### Artifacts Are Written at Every Step
1390
+
1391
+ A real run writes the evidence trail:
1392
+
1393
+ ```python
1394
+ def write_attempt_artifacts(state, result, diagnosis, delta):
1395
+ write("attempts/{id}/prompt.md", state.render())
1396
+ write("attempts/{id}/result.json", result)
1397
+ write("attempts/{id}/diagnosis.md", diagnosis)
1398
+ write("attempts/{id}/next_prompt_delta.md", delta)
1399
+ ```
1400
+
1401
+ Prompt states get their own timeline:
1402
+
1403
+ ```python
1404
+ def write_prompt_state(state):
1405
+ write("prompt_states/{id}/prompt.md", state.render())
1406
+ ```
1407
+
1408
+ The larger pipeline then packages everything:
1409
+
1410
+ ```python
1411
+ def full_pipeline(task_pack):
1412
+ run = solve_task_pack(task_pack)
1413
+ bundle = build_run_bundle(run)
1414
+ submission = package_submission(bundle)
1415
+ export = export_platform_submission(submission)
1416
+ return validate(export)
1417
+ ```
1418
+
1419
+ That is the full system in miniature.
1420
+
1421
+ The implementation is larger because it has registries, validators, manifests, hashes, and CLI commands. But the idea remains the same:
1422
+
1423
+ ```text
1424
+ generate
1425
+ → validate
1426
+ → diagnose
1427
+ → repair
1428
+ → try again
1429
+ → preserve the evidence
1430
+ ```
1431
+
1432
+ That is Codex Manager.
1433
+
1434
+ ---
1435
+
1436
+ ## Glossary
1437
+
1438
+ | **Term** | **Definition** |
1439
+ | ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1440
+ | **Codex Manager** | A prompt-state runtime that manages Codex through candidate generation, isolated execution, diagnosis, repair, and verified promotion. |
1441
+ | **PromptState** | The structured state around Codex at a given point in the run, including context, prior lessons, failure warnings, banned moves, success patterns, and the output contract. |
1442
+ | **Candidate** | A proposed solution generated by Codex or another candidate executor. It is treated as a proposal, not as a trusted answer. |
1443
+ | **Candidate Diff** | A patch generated by the model, usually as a unified diff against the target file. |
1444
+ | **Attempt** | One cycle of generating a candidate, applying it, validating it, benchmarking it, and recording the result. |
1445
+ | **AttemptResult** | The structured evidence from an attempt, including whether the candidate applied, built, passed correctness, passed benchmark, and improved performance. |
1446
+ | **AttemptDiagnosis** | The manager’s interpretation of an AttemptResult. It identifies what failed, why it likely failed, and what lesson should carry forward. |
1447
+ | **PromptDelta** | A structured update to the next PromptState, such as new constraints, warnings, banned moves, or success patterns. |
1448
+ | **Prompt Repair** | The process of converting an AttemptDiagnosis into a PromptDelta so the next attempt is generated under better constraints. |
1449
+ | **Banned Moves** | Actions the next candidate should avoid, such as touching test files, changing public interfaces, assuming aligned inputs, or returning prose instead of a diff. |
1450
+ | **Success Patterns** | Patterns from successful attempts that should be preserved in future attempts. |
1451
+ | **Context Pack** | The task-specific context given to Codex, including the goal, source constraints, correctness contract, benchmark contract, known failure modes, and output contract. |
1452
+ | **Task Pack** | A portable YAML or JSON task definition that describes the problem, source files, target file, allowed patch paths, build command, correctness command, benchmark command, and context. |
1453
+ | **Execution Mode** | The way a task is evaluated, such as `shadow`, `shadow_mock`, or `command`. |
1454
+ | **Shadow Workspace** | An isolated copy of the source files where candidate patches are applied and tested without modifying the real source tree. |
1455
+ | **Patch Gate** | The validation step that checks whether a candidate diff applies cleanly and only touches allowed files. |
1456
+ | **Build Gate** | The validation step that checks whether the patched target still compiles or passes its build command. |
1457
+ | **Correctness Gate** | The validation step that checks whether the candidate preserves the required behavior. Benchmarking is blocked unless this passes. |
1458
+ | **Benchmark Gate** | The validation step that measures whether a correctness-passing candidate improves performance. |
1459
+ | **Benchmark Regression** | A failure where the candidate passes correctness but performs worse than the baseline. |
1460
+ | **Verified Promotion** | The decision to mark a candidate as the best surviving attempt only after it passes the required gates and improves the benchmark. |
1461
+ | **Candidate Executor** | The component that turns a PromptState into a candidate. Examples include mock, scripted, and OpenAI-compatible executors. |
1462
+ | **Executor Registry** | The registry that lets Codex Manager switch between candidate generators without changing the prompt-state loop. |
1463
+ | **Profile** | A domain-specific evaluator for a class of tasks. For example, a kernel optimization profile knows how to build context and run candidates for kernel-style tasks. |
1464
+ | **Profile Registry** | The registry that lets Codex Manager load different profiles without hardcoding execution paths into the engine. |
1465
+ | **Command Adapter** | The execution path that lets task packs define shell commands for build, correctness, and benchmark evaluation. |
1466
+ | **Run Bundle** | A reproducible package of a completed run, including the run manifest, context pack, prompt log, report, validation output, replay script, attempts, and best candidate evidence. |
1467
+ | **Submission Package** | A judge-ready artifact built from a run bundle, containing the evidence needed to inspect the run and its promoted candidate. |
1468
+ | **Platform Export** | A translated version of the submission package shaped for a specific external platform, such as `generic_command`, `metal_stub`, or `gpu_mode_stub`. |
1469
+ | **Pipeline** | The full end-to-end workflow: task pack, solve, run bundle, submission package, platform export, and validation. |
1470
+ | **Pipeline Manifest** | The machine-readable summary of a full pipeline run, including IDs, output paths, validations, and chain-of-custody hashes. |
1471
+ | **Chain of Custody** | The hash-linked trail connecting a run bundle, submission package, and platform export. |
1472
+ | **PROMPTS.log** | The append-only JSONL log of prompt attempts, prompt hashes, diagnoses, speedups, promotion status, and executor metadata. |
1473
+ | **attempts/** | The directory containing executed attempts. Each attempt contains the prompt, result, diagnosis, and next prompt delta. |
1474
+ | **prompt_states/** | The directory containing PromptState snapshots, including future prompt states that may not have been executed. |
1475
+ | **Replay** | The ability to inspect or rerun a task using the recorded task pack, manifest, and pipeline metadata. |
1476
+ | **Context Machine** | The broader system around Codex that preserves state, evaluates attempts, repairs prompts, and produces artifacts. Codex Manager is the context machine described in this post. |
1477
+