@lyupro/codex-bridge 0.1.3 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/README.md +18 -4
  3. package/bin/codex-bridge.mjs +29 -0
  4. package/cli/doctor.mjs +26 -3
  5. package/cli/install.mjs +18 -4
  6. package/cli/manifest.mjs +6 -4
  7. package/cli/projects.mjs +92 -0
  8. package/cli/prune-args.mjs +133 -0
  9. package/cli/prune-plan.mjs +205 -0
  10. package/cli/prune.mjs +278 -0
  11. package/cli/read.mjs +103 -0
  12. package/cli/run-lookup.mjs +59 -0
  13. package/cli/runs-inventory.mjs +173 -0
  14. package/cli/settings-merge.mjs +18 -4
  15. package/cli/stop.mjs +4 -37
  16. package/cli/table.mjs +110 -0
  17. package/package.json +1 -1
  18. package/src/agents/codex-build.md +12 -10
  19. package/src/agents/codex-review.md +11 -5
  20. package/src/agents/codex-scout.md +11 -10
  21. package/src/commands/usage.md +4 -3
  22. package/src/hook-definitions.mjs +22 -0
  23. package/src/hooks/live-runs.mjs +98 -0
  24. package/src/hooks/prune-guard.mjs +62 -0
  25. package/src/hooks/reply-guard.mjs +45 -22
  26. package/src/hooks/worktree-lock.mjs +70 -0
  27. package/src/meta/deadline.mjs +19 -0
  28. package/src/meta/events.mjs +166 -0
  29. package/src/meta/reason.mjs +29 -0
  30. package/src/meta/reply.mjs +40 -7
  31. package/src/meta/run-state.mjs +7 -1
  32. package/src/meta/startup.mjs +21 -0
  33. package/src/meta/transport.mjs +35 -0
  34. package/src/meta/verdict.mjs +40 -42
  35. package/src/required-inputs.mjs +49 -6
  36. package/src/retention.mjs +120 -0
  37. package/src/run-codex.mjs +3 -3
  38. package/src/run-config.json +5 -1
  39. package/src/run-config.mjs +54 -1
  40. package/src/runner/attach.mjs +1 -1
  41. package/src/runner/codex-cmd.mjs +119 -31
  42. package/src/runner/continuation.mjs +107 -0
  43. package/src/runner/launcher.mjs +23 -40
  44. package/src/runner/worker.mjs +11 -3
  45. package/src/write-meta.mjs +31 -22
@@ -11,7 +11,7 @@
11
11
  */
12
12
  import fs from 'node:fs';
13
13
  import path from 'node:path';
14
- import { changedPaths, line, readText } from './paths.mjs';
14
+ import { changedPaths, line, readJson, readText } from './paths.mjs';
15
15
  import { splitRunChanges } from './environment.mjs';
16
16
  import { scoutCoverage } from './verdict.mjs';
17
17
 
@@ -22,6 +22,29 @@ const runChanges = (runDir) =>
22
22
  changedPaths(readText(path.join(runDir, 'state-before.txt')), readText(path.join(runDir, 'state-after.txt'))),
23
23
  );
24
24
 
25
+ const readCommand = (runDir) => `codex-bridge read ${runDir}`;
26
+
27
+ function formatBytes(bytes) {
28
+ const units = ['B', 'KB', 'MB', 'GB'];
29
+ let value = bytes;
30
+ let index = 0;
31
+ while (value >= 1024 && index < units.length - 1) {
32
+ value /= 1024;
33
+ index += 1;
34
+ }
35
+ return `${value.toFixed(1)} ${units[index]}`;
36
+ }
37
+
38
+ function retentionReply(runDir) {
39
+ const retention = readJson(path.join(runDir, 'status.json'))?.retention;
40
+ const bytes = Number(retention?.bytes_freed);
41
+ const runs = Number(retention?.runs);
42
+ const days = Number(retention?.days);
43
+ if (!Number.isFinite(bytes) || bytes <= 0 || !Number.isFinite(runs) || runs <= 0
44
+ || !Number.isFinite(days) || days <= 0) return null;
45
+ return `Retention: freed ${formatBytes(bytes)} from ${runs} runs older than ${days} days`;
46
+ }
47
+
25
48
  export const AGENTS = {
26
49
  'codex-scout': {
27
50
  result: 'result.json',
@@ -45,13 +68,15 @@ function scoutReply(ctx) {
45
68
  const top = (r.findings || [])[0];
46
69
  const unknowns = (r.unknowns || []).filter(Boolean);
47
70
  const coverage = scoutCoverage(ctx.runDir, r);
71
+ const retention = retentionReply(ctx.runDir);
48
72
  return [
49
73
  `OK — ${line(r.answer, 160)}`,
50
74
  // Any explicit question gets a coverage line, including a valid one-question order.
51
75
  ...(coverage ? [`Coverage: ${coverage}`] : []),
52
76
  `Key finding: ${top ? `${line(top.fact, 130)} (${line(top.where, 60)})` : 'no findings listed'}`,
53
77
  `Unresolved: ${unknowns.length ? line(unknowns.join('; '), 160) : 'none'}`,
54
- `Report: ${ctx.file('report.md')} · Log: ${ctx.file('raw.log')}`,
78
+ ...(retention ? [retention] : []),
79
+ `Report: ${ctx.file('report.md')} · Log: ${readCommand(ctx.runDir)}`,
55
80
  ];
56
81
  }
57
82
 
@@ -81,6 +106,7 @@ function buildReply(ctx) {
81
106
  const files = ctx.carried
82
107
  ? `${paths ? `${paths} · ` : ''}changes were made by an earlier run of this task`
83
108
  : paths || 'worktree untouched';
109
+ const retention = retentionReply(ctx.runDir);
84
110
  return [
85
111
  `OK — ${line(r.summary, 160)}`,
86
112
  `Files: ${touchedPaths.length} changed · ${files}`,
@@ -91,7 +117,8 @@ function buildReply(ctx) {
91
117
  : []),
92
118
  `Verification: ${verify} — ${verdict}`,
93
119
  `Flags: ${flags.length ? `${flags.length} TODO/skip — ${line(flags.slice(0, 3).join(' | '), 140)}` : 'none'}`,
94
- `Report: ${ctx.file('report.md')} · Log: ${ctx.file('raw.log')}`,
120
+ ...(retention ? [retention] : []),
121
+ `Report: ${ctx.file('report.md')} · Log: ${readCommand(ctx.runDir)}`,
95
122
  ];
96
123
  }
97
124
 
@@ -102,24 +129,28 @@ function reviewReply(ctx) {
102
129
  if (counts[f.severity] !== undefined) counts[f.severity] += 1;
103
130
  });
104
131
  const top = (r.findings || []).find((f) => f.severity === 'critical' || f.severity === 'high');
132
+ const retention = retentionReply(ctx.runDir);
105
133
  return [
106
134
  `OK — verdict ${line(r.verdict, 40)}`,
107
135
  `Findings: critical ${counts.critical} · high ${counts.high} · medium ${counts.medium} · low ${counts.low}`,
108
136
  `Top: ${top ? `${top.severity} ${line(top.file, 80)}:${top.line_start} — ${line(top.title, 90)}` : 'no critical or high findings'}`,
109
- `Report: ${ctx.file(path.basename(ctx.resultPath))} · Log: ${ctx.file('raw.log')}`,
137
+ ...(retention ? [retention] : []),
138
+ `Report: ${ctx.file(path.basename(ctx.resultPath))} · Log: ${readCommand(ctx.runDir)}`,
110
139
  ];
111
140
  }
112
141
 
113
142
  export function failReply(ctx, meta) {
143
+ const retention = retentionReply(ctx.runDir);
114
144
  return [
115
145
  `FAIL — ${line(meta.reason, 170)}`,
116
- `Artifacts: raw.log ${meta.log_bytes} B · ${path.basename(ctx.resultPath)} ${meta.result_ok ? 'filled' : 'empty or missing'} · exit=${meta.exit}`,
146
+ `Artifacts: events.jsonl ${meta.events_bytes} B · stderr.log ${meta.stderr_bytes} B · ${path.basename(ctx.resultPath)} ${meta.result_ok ? 'filled' : 'empty or missing'} · exit=${meta.exit}`,
117
147
  // A failed build says what it left behind, exactly as a LIMIT does. "The work was not
118
148
  // done" is not "the tree is clean": a run can write half a change and then declare fail,
119
149
  // and the orchestrator has to know whether there is something to revert before it decides
120
150
  // anything else.
121
151
  ...(ctx.agent === 'codex-build' ? [`Worktree: ${worktreeState(ctx.runDir)}`] : []),
122
- `Log: ${ctx.file('raw.log')}`,
152
+ ...(retention ? [retention] : []),
153
+ `Log: ${readCommand(ctx.runDir)}`,
123
154
  ];
124
155
  }
125
156
 
@@ -141,6 +172,7 @@ function worktreeState(runDir) {
141
172
  }
142
173
 
143
174
  export function limitReply(ctx, meta) {
175
+ const retention = retentionReply(ctx.runDir);
144
176
  const rows = [
145
177
  'LIMIT — ChatGPT quota exhausted, work not completed',
146
178
  `Signal: ${line(meta.reason, 170)}`,
@@ -151,6 +183,7 @@ export function limitReply(ctx, meta) {
151
183
  `Worktree: ${touched.length ? `has unfinished changes (${touched.length}), see git-after.txt` : 'no new changes'}`,
152
184
  );
153
185
  }
154
- rows.push(`Log: ${ctx.file('raw.log')}`);
186
+ if (retention) rows.push(retention);
187
+ rows.push(`Log: ${readCommand(ctx.runDir)}`);
155
188
  return rows;
156
189
  }
@@ -29,6 +29,11 @@ export const pidAlive = (pid) => {
29
29
  * Run state on disk, merged over whatever is already there. A killed runner leaves no
30
30
  * report and no meta.json, and four abandoned folders from one order were indistinguishable
31
31
  * from four runs still working — status.json is what makes that difference visible.
32
+ *
33
+ * It writes status.json and nothing else. Housekeeping facts such as `retention` live here and
34
+ * are read from here; an earlier attempt also appended them to meta.json, which would have made
35
+ * two functions write the same artifact and put the documented artifact order (meta.json before
36
+ * status.json is closed) at the mercy of whoever ran last.
32
37
  */
33
38
  export function writeStatus(runDir, patch) {
34
39
  const current = readJson(path.join(runDir, 'status.json')) || {};
@@ -182,7 +187,8 @@ export function writeFailure(runDir, agent, reason, extraLines = []) {
182
187
  status: 'FAIL',
183
188
  reason: line(reason, 300),
184
189
  result_ok: false,
185
- log_bytes: size(path.join(runDir, 'raw.log')),
190
+ events_bytes: size(path.join(runDir, 'events.jsonl')),
191
+ stderr_bytes: size(path.join(runDir, 'stderr.log')),
186
192
  tokens: null,
187
193
  tokens_reported: false,
188
194
  model: null,
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Explains a current run that never reached either of its two output streams.
3
+ *
4
+ * The existing events file is enough to distinguish this shape: an archived folder has no
5
+ * events stream at all, while a folder with an empty stream and silent stderr proves the CLI
6
+ * never started.
7
+ */
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+ import { readText } from './paths.mjs';
11
+
12
+ export function startupGap(runDir, events) {
13
+ if (!events?.hasStream || events.hasEvents) return null;
14
+ // Existence before emptiness: a stderr.log that is not there is a missing witness, not a
15
+ // silent one, and the two mean opposite things. Reading an absent file as "" would let a run
16
+ // whose evidence was deleted after the fact pass for a run that never started — the damaged
17
+ // -artifacts check below this one exists precisely to name that case instead.
18
+ const stderr = path.join(runDir, 'stderr.log');
19
+ if (!fs.existsSync(stderr) || readText(stderr)) return null;
20
+ return 'run abandoned at startup: events.jsonl has no events and stderr.log is empty, Codex did not run';
21
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Where a run's transport errors live, and whether that evidence can be trusted.
3
+ *
4
+ * Quota exhaustion is the one signal that tells the orchestrator not to retry, so it is read
5
+ * only from structured events the CLI itself writes. Text outside that protocol is diagnostic
6
+ * evidence, not a verdict.
7
+ */
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+ import { readJson } from './paths.mjs';
11
+ import { readEvents } from './events.mjs';
12
+
13
+ const stderrPath = (runDir) => path.join(runDir, 'stderr.log');
14
+ const hasJsonContract = (runDir) => {
15
+ const args = readJson(path.join(runDir, 'worker.json'))?.args;
16
+ return Array.isArray(args) && args.includes('--json');
17
+ };
18
+
19
+ /**
20
+ * Artifacts that contradict each other about which contract the run was written under.
21
+ *
22
+ * A current run whose worker reached the end of runCodex() has an events.jsonl file. One whose
23
+ * own args promise `--json` but lacks that file lost evidence after the fact; calling it an
24
+ * archived run would make a quota refusal indistinguishable from a quoted one. The deadline
25
+ * marker remains a second consistency check because the same worker also creates stderr.log.
26
+ */
27
+ export function transportGap(runDir, events = readEvents(runDir)) {
28
+ if (hasJsonContract(runDir) && !events.hasStream) {
29
+ return 'artifacts disagree: worker.json requests --json, but events.jsonl is missing; the evidence was damaged, so a quota refusal cannot be told apart from a quoted one';
30
+ }
31
+ const status = readJson(path.join(runDir, 'status.json'));
32
+ if (!status || !('stopped_on_deadline' in status)) return null;
33
+ if (fs.existsSync(stderrPath(runDir))) return null;
34
+ return 'artifacts disagree: this run recorded a deadline watch but has no stderr.log, so a quota signal cannot be told apart from a quoted one';
35
+ }
@@ -22,17 +22,12 @@ import {
22
22
  } from './paths.mjs';
23
23
  import { chainBaseline } from './chain.mjs';
24
24
  import { splitRunChanges } from './environment.mjs';
25
+ import { readEvents } from './events.mjs';
25
26
  import { outcomeGap } from './outcome.mjs';
26
-
27
- /**
28
- * Quota exhaustion is a transport error, not a word. Both markers must sit on the same
29
- * line: a run whose review text merely discusses "quota exhaustion" is not a run that
30
- * hit the quota, and reporting LIMIT there tells the orchestrator not to retry when it
31
- * should. "try again later" is deliberately absent — it is a transient-failure phrase,
32
- * not a quota one.
33
- */
34
- const LIMIT_RE = /rate.?limit|usage limit|usage_limit|quota exceeded|quota exhausted|too many requests|\b429\b/i;
35
- const ERROR_RE = /\bERROR\b|error[:=]|stream error|"status"\s*:\s*429|rejected|refused|failed/i;
27
+ import { deadlineReason } from './deadline.mjs';
28
+ import { startupGap } from './startup.mjs';
29
+ import { transportGap } from './transport.mjs';
30
+ import { reasonFrom } from './reason.mjs';
36
31
 
37
32
  // How much prose an answer must carry once coordinates and paths are subtracted. Measured
38
33
  // on the scout run of 2026-07-30 that replied with a table of `file.ts:60-79` rows: every
@@ -42,24 +37,6 @@ const ERROR_RE = /\bERROR\b|error[:=]|stream error|"status"\s*:\s*429|rejected|r
42
37
  const MIN_SUBSTANCE_CHARS = 80;
43
38
  const MIN_SINGLE_SUBSTANCE_CHARS = 200;
44
39
 
45
- /**
46
- * The honest reason for a failure. Codex prints API errors as pretty-printed JSON, so
47
- * the literally-last line is often just `}` — useless in a one-line reply. Prefer the
48
- * error message field, then any error line, then the last line that carries text.
49
- */
50
- const reasonFrom = (log) => {
51
- const messages = [...log.matchAll(/"message"\s*:\s*"((?:[^"\\]|\\.)*)"/g)];
52
- if (messages.length) return line(messages[messages.length - 1][1].replace(/\\"/g, '"'));
53
- const lines = log.split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
54
- const errorLine = [...lines].reverse().find((l) => /error|failed|denied|refused/i.test(l));
55
- return line(errorLine || lines[lines.length - 1] || '');
56
- };
57
-
58
- const limitSignal = (log) => {
59
- const hit = log.split(/\r?\n/).find((l) => LIMIT_RE.test(l) && ERROR_RE.test(l));
60
- return hit ? line(hit) : null;
61
- };
62
-
63
40
  /**
64
41
  * Which touched paths the task never authorised. The scope exists because prose does not
65
42
  * bind: one build run was told in words to keep away from `!Plans/*.md` and edited them
@@ -271,17 +248,18 @@ function branchDuringRun(runDir) {
271
248
  }
272
249
 
273
250
  /**
274
- * Status comes from artifacts, never from intent. An abandoned run leaves raw.log at
275
- * zero bytes, and that is a FAIL with its own reason — not a retry hint. An empty
276
- * result with a quota signal in the log is LIMIT; without one it is FAIL.
251
+ * Status comes from artifacts, never from intent. A current run with an events stream but no
252
+ * events and silent stderr is abandoned at startup; an empty result with no structured
253
+ * transport error is FAIL, because diagnostic text cannot turn a quoted limit into LIMIT.
277
254
  */
278
- export function resolveStatus({ log, logBytes, resultOk, exit, agent, result, runDir }) {
279
- if (!logBytes) {
280
- return {
281
- status: 'FAIL',
282
- reason: 'run abandoned at startup: raw.log is empty, Codex did not run',
283
- };
284
- }
255
+ export function resolveStatus({ resultOk, exit, agent, result, runDir, events }) {
256
+ const eventData = events ?? readEvents(runDir);
257
+ // First, as the empty raw.log check was before it: a run that never started cannot be graded
258
+ // for what happened in its window. Below this line sit accusations about the run's conduct —
259
+ // a commit, a moved branch — and HEAD moving while Codex was absent is somebody else's doing.
260
+ // Blaming a run that did not exist is the same class of lie every other check here prevents.
261
+ const startup = startupGap(runDir, eventData);
262
+ if (startup) return { status: 'FAIL', reason: startup };
285
263
  // Ahead of everything else, including LIMIT: a commit under an explicit ban is a broken
286
264
  // contract, not a grade for the work. Whatever else the run produced, the orchestrator has
287
265
  // to learn first that history moved under it.
@@ -291,13 +269,33 @@ export function resolveStatus({ log, logBytes, resultOk, exit, agent, result, ru
291
269
  const branched = branchDuringRun(runDir);
292
270
  if (branched) return { status: 'FAIL', reason: branched };
293
271
  }
272
+ const deadline = deadlineReason(runDir);
273
+ if (deadline) return { status: 'FAIL', reason: deadline };
274
+ // Damaged transport evidence is not archived transport evidence. Checked before LIMIT, since
275
+ // the fallback it guards is what LIMIT would otherwise use.
276
+ const transport = transportGap(runDir, eventData);
277
+ if (transport) return { status: 'FAIL', reason: transport };
278
+ // Only a run with nothing to show is judged by its transport errors. The CLI prints an error
279
+ // event for a dropped stream and then retries it, so a run that recovered, filled its result
280
+ // and exited zero did the job — turning that survived error into a verdict would fail honest
281
+ // work, the mirror image of the false LIMIT this whole module exists to remove.
282
+ const transportError =
283
+ eventData.hasEvents && (!resultOk || exit !== 0) ? eventData.transport_error : null;
284
+ if (transportError) {
285
+ // This branch already knows why the run died: the CLI said so itself, with a status. Letting
286
+ // the ordered reason speak here would answer a transport question with the model's older
287
+ // complaint about the task — a LIMIT that never mentions quota is the same "verdict says the
288
+ // wrong thing" defect this module exists to remove.
289
+ return {
290
+ status: transportError.quota ? 'LIMIT' : 'FAIL',
291
+ reason: transportError.reason,
292
+ };
293
+ }
294
294
  if (!resultOk) {
295
- const limit = limitSignal(log);
296
- if (limit) return { status: 'LIMIT', reason: limit };
297
- return { status: 'FAIL', reason: reasonFrom(log) || `result is empty, exit=${exit}` };
295
+ return { status: 'FAIL', reason: reasonFrom(runDir, eventData) || `result is empty, exit=${exit}` };
298
296
  }
299
297
  if (exit !== 0) {
300
- return { status: 'FAIL', reason: `result exists, but exit=${exit}: ${reasonFrom(log)}` };
298
+ return { status: 'FAIL', reason: `result exists, but exit=${exit}: ${reasonFrom(runDir, eventData)}` };
301
299
  }
302
300
  // A red verification is a failed job, not an OK with a footnote. The orchestrator
303
301
  // reads the first word; burying "fail" in line three is how a broken build passes.
@@ -11,6 +11,15 @@ const PLACEHOLDER_VALUES = new Set(['todo', 'tbd', 'label', 'none', 'order id',
11
11
 
12
12
  const freezeEntries = (entries) => Object.freeze(entries.map((entry) => Object.freeze(entry)));
13
13
 
14
+ export const CONTINUATION_INPUT = Object.freeze({
15
+ label: 'continue',
16
+ source: 'the orchestrator',
17
+ explanation:
18
+ 'The run folder this pass is ordered to continue, followed by why the orchestrator is spending another pass. A continuation is assigned by the orchestrator; after a verdict, the dispatcher returns it and stops.',
19
+ example: '2026-08-05_092913_plan14-build — LIMIT at step 3, tests unwritten',
20
+ conditional: 'when --continue is passed',
21
+ });
22
+
14
23
  export const REQUIRED_INPUTS = Object.freeze({
15
24
  'codex-scout': freezeEntries([
16
25
  {
@@ -19,6 +28,7 @@ export const REQUIRED_INPUTS = Object.freeze({
19
28
  explanation: 'The label this order is known by. Repeating a call with the same label joins the run already in flight and costs no quota; a different piece of work needs a new label, never a reused one.',
20
29
  example: 'plan-13-scout-20260804',
21
30
  },
31
+ CONTINUATION_INPUT,
22
32
  ]),
23
33
  'codex-build': freezeEntries([
24
34
  {
@@ -33,6 +43,7 @@ export const REQUIRED_INPUTS = Object.freeze({
33
43
  explanation: 'Comma-separated globs relative to the repository root, listing every file the run may touch — including each caller of what changes, not only the file being edited. Anything outside the list fails the run.',
34
44
  example: 'src/runner/**,tests/runner/**',
35
45
  },
46
+ CONTINUATION_INPUT,
36
47
  ]),
37
48
  'codex-review': freezeEntries([
38
49
  {
@@ -41,6 +52,7 @@ export const REQUIRED_INPUTS = Object.freeze({
41
52
  explanation: 'The label this order is known by. Repeating a call with the same label joins the run already in flight and costs no quota; a different piece of work needs a new label, never a reused one.',
42
53
  example: 'plan-13-review-20260804',
43
54
  },
55
+ CONTINUATION_INPUT,
44
56
  ]),
45
57
  });
46
58
 
@@ -51,14 +63,14 @@ function cleanValue(value) {
51
63
  return value.trim().replace(/^([`'\"])(.*)\1$/, '$2').trim();
52
64
  }
53
65
 
54
- function isPlaceholder(value) {
66
+ export function isPlaceholder(value) {
55
67
  const cleaned = cleanValue(value);
56
68
  if (!cleaned) return true;
57
69
  if (cleaned.startsWith('<') && cleaned.endsWith('>')) return true;
58
70
  return PLACEHOLDER_VALUES.has(cleaned.replace(/[.,;:]+$/, '').trim().toLowerCase());
59
71
  }
60
72
 
61
- function extractValue(promptText, label) {
73
+ export function extractValue(promptText, label) {
62
74
  const labelPattern = escapeRegExp(label).replaceAll('\\ ', '\\s+');
63
75
  const flag = `--${label.replaceAll(/\s+/g, '-')}`;
64
76
  const direct = new RegExp(
@@ -77,6 +89,23 @@ function extractValue(promptText, label) {
77
89
  return cleanValue(flagMatch[1] ?? flagMatch[2] ?? flagMatch[3]);
78
90
  }
79
91
 
92
+ /** Keeps the 2026-08-05 continuation incident's run and reason in the shared input parser. */
93
+ export function parseContinuationGrant(promptText) {
94
+ const prompt = typeof promptText === 'string' ? promptText : '';
95
+ const value = extractValue(prompt, CONTINUATION_INPUT.label);
96
+ if (isPlaceholder(value)) return null;
97
+
98
+ for (const separator of [/\s+—\s+/, /\s+-\s+/, /\s*:\s*/]) {
99
+ const match = value.match(new RegExp(`^(.+?)${separator.source}(.+)$`));
100
+ if (!match) continue;
101
+ const run = cleanValue(match[1]);
102
+ const reason = cleanValue(match[2]);
103
+ if (isPlaceholder(run) || isPlaceholder(reason)) return null;
104
+ return { run, reason };
105
+ }
106
+ return null;
107
+ }
108
+
80
109
  /** Returns the immutable input entries for one dispatcher type. */
81
110
  export function requiredInputsFor(agentType) {
82
111
  return REQUIRED_INPUTS[agentType] || [];
@@ -85,20 +114,34 @@ export function requiredInputsFor(agentType) {
85
114
  /** Returns required entries whose value is absent or is still an obvious template placeholder. */
86
115
  export function missingInputs(agentType, promptText) {
87
116
  const prompt = typeof promptText === 'string' ? promptText : '';
88
- return requiredInputsFor(agentType).filter((entry) => isPlaceholder(extractValue(prompt, entry.label)));
117
+ return requiredInputsFor(agentType).filter(
118
+ (entry) => !entry.conditional && isPlaceholder(extractValue(prompt, entry.label)),
119
+ );
89
120
  }
90
121
 
91
122
  /** Renders the compact contract the orchestrator sees while choosing a dispatcher. */
92
123
  export function renderRequiredInputSummary(agentType) {
93
124
  const entries = requiredInputsFor(agentType);
94
125
  if (!entries.length) return '';
95
- const labels = entries.map((entry) => `\`${entry.label}\``);
96
- return `Requires ${entries[0].source}-provided ${labels.join(' and ')}.`;
126
+ const labels = entries.map((entry) => {
127
+ const label = `\`${entry.label}\``;
128
+ return entry.conditional ? `${label} (${entry.conditional})` : label;
129
+ });
130
+ // Commas until the last pair: the list grew to three entries when the continuation grant
131
+ // joined it, and "a and b and c" reads as a stutter in the description the orchestrator
132
+ // sees while choosing a dispatcher.
133
+ const rendered = labels.length > 1
134
+ ? `${labels.slice(0, -1).join(', ')} and ${labels[labels.length - 1]}`
135
+ : labels[0];
136
+ return `Requires ${entries[0].source}-provided ${rendered}.`;
97
137
  }
98
138
 
99
139
  /** Renders the same contract for pass 2 agent instructions. */
100
140
  export function renderRequiredInputs(agentType) {
101
141
  return requiredInputsFor(agentType)
102
- .map((entry) => `- ${entry.label}: ${entry.explanation} Example: \`${entry.example}\`.`)
142
+ .map((entry) => {
143
+ const condition = entry.conditional ? ` Condition: ${entry.conditional}.` : '';
144
+ return `- ${entry.label}: ${entry.explanation} Example: \`${entry.example}\`.${condition}`;
145
+ })
103
146
  .join('\n');
104
147
  }
@@ -0,0 +1,120 @@
1
+ /** Owns the transport list and age decision shared by automatic and manual cleanup. */
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { liveRuns, normalizePath } from './hooks/live-runs.mjs';
5
+
6
+ // Plan_17 step 3 found one order's copied list and age default diverging on the same day. Keeping
7
+ // the transport boundary here prevents automatic cleanup from eating accounting files.
8
+ export const TRANSPORT_FILES = Object.freeze(['events.jsonl', 'stderr.log', 'raw.log']);
9
+
10
+ function ageDate(name) {
11
+ const match = /^(\d{4})-(\d{2})-(\d{2})_(\d{2})(\d{2})(\d{2})(?:_|$)/.exec(name);
12
+ if (!match) return null;
13
+ const [, year, month, day, hour, minute, second] = match;
14
+ const timestamp = Date.UTC(
15
+ Number(year), Number(month) - 1, Number(day), Number(hour), Number(minute), Number(second),
16
+ );
17
+ const date = new Date(timestamp);
18
+ if (date.getUTCFullYear() !== Number(year)
19
+ || date.getUTCMonth() !== Number(month) - 1
20
+ || date.getUTCDate() !== Number(day)
21
+ || date.getUTCHours() !== Number(hour)
22
+ || date.getUTCMinutes() !== Number(minute)
23
+ || date.getUTCSeconds() !== Number(second)) return null;
24
+ return timestamp;
25
+ }
26
+
27
+ function nowTimestamp(value) {
28
+ if (value instanceof Date) return value.getTime();
29
+ if (typeof value === 'number' && Number.isFinite(value)) return value;
30
+ const parsed = Date.parse(value ?? '');
31
+ return Number.isNaN(parsed) ? Date.now() : parsed;
32
+ }
33
+
34
+ function ageCutoff(olderThan, now) {
35
+ if (!olderThan) return null;
36
+ if (olderThan.kind === 'duration') {
37
+ const unit = olderThan.unit === 'h' ? 60 * 60 * 1000 : 24 * 60 * 60 * 1000;
38
+ return now - olderThan.amount * unit;
39
+ }
40
+ return Date.parse(`${olderThan.date}T00:00:00.000Z`);
41
+ }
42
+
43
+ /** Returns whether a run is older than a parsed threshold, using only its folder name. */
44
+ export function runIsOlderThan(runName, olderThan, now = Date.now()) {
45
+ const timestamp = ageDate(runName);
46
+ if (timestamp === null || !olderThan) return false;
47
+ return timestamp < ageCutoff(olderThan, nowTimestamp(now));
48
+ }
49
+
50
+ /**
51
+ * Removes only regular transport files from old, non-live runs.
52
+ *
53
+ * Plan_17 step 4 makes cleanup deliberately best effort: a full disk must not stop a new run, and
54
+ * deleting one named file cannot justify recursive removal of a run folder or accounting artifacts.
55
+ */
56
+ export function cleanupRetention(runsDir, config, options = {}) {
57
+ // Do not inspect days when disabled. A stale or malformed day value must not re-enable cleanup.
58
+ if (!config?.enabled) return null;
59
+ const days = config.days;
60
+ if (typeof days !== 'number' || !Number.isFinite(days) || days <= 0) return null;
61
+
62
+ const filesystem = options.fs || fs;
63
+ const now = options.now ?? Date.now();
64
+ let entries;
65
+ try {
66
+ entries = filesystem.readdirSync(runsDir, { withFileTypes: true });
67
+ } catch {
68
+ return null;
69
+ }
70
+
71
+ let live = new Set();
72
+ try {
73
+ // Normalized like every other path comparison in the package: a case difference between the
74
+ // scan and the probe would make a live run look like a stale one, and this deletes files.
75
+ live = new Set(liveRuns(runsDir).map(({ dir }) => normalizePath(dir)));
76
+ } catch {
77
+ // The launcher wraps the whole pass too; when the shared probe cannot answer, retain every
78
+ // run rather than repeating the abandoned-run incident with a live folder as a target.
79
+ return null;
80
+ }
81
+
82
+ const removedRuns = new Set();
83
+ let bytesFreed = 0;
84
+ for (const entry of entries) {
85
+ let isDirectory;
86
+ try {
87
+ isDirectory = entry.isDirectory();
88
+ } catch {
89
+ continue;
90
+ }
91
+ if (!isDirectory) continue;
92
+
93
+ const runDir = path.join(runsDir, entry.name);
94
+ if (live.has(normalizePath(runDir)) || !runIsOlderThan(entry.name, {
95
+ kind: 'duration',
96
+ amount: days,
97
+ unit: 'd',
98
+ }, now)) continue;
99
+
100
+ for (const filename of TRANSPORT_FILES) {
101
+ const target = path.join(runDir, filename);
102
+ let stat;
103
+ try {
104
+ stat = filesystem.lstatSync(target);
105
+ } catch {
106
+ continue;
107
+ }
108
+ if (!stat.isFile()) continue;
109
+ try {
110
+ filesystem.unlinkSync(target);
111
+ } catch {
112
+ continue;
113
+ }
114
+ removedRuns.add(entry.name);
115
+ if (Number.isFinite(stat.size) && stat.size > 0) bytesFreed += stat.size;
116
+ }
117
+ }
118
+
119
+ return removedRuns.size ? { bytes_freed: bytesFreed, runs: removedRuns.size, days } : null;
120
+ }
package/src/run-codex.mjs CHANGED
@@ -29,7 +29,7 @@
29
29
  * tree and writes the verdict.
30
30
  *
31
31
  * The split exists because the caller dies long before a 20-25 minute run does. Run
32
- * `2026-07-31_114736_*` has no raw.log at all while 11+ files were written into the tree: the
32
+ * `2026-07-31_114736_*` has no events.jsonl at all while 11+ files were written into the tree: the
33
33
  * dispatcher's Bash call hit its two-minute timeout, node was killed, spawnSync's buffered
34
34
  * output died with it — and Codex kept going, unwatched and unrecorded. Killing that orphan
35
35
  * is not the fix either: its edits were the work, and later runs finished on top of them. So
@@ -84,9 +84,9 @@ if (invokedDirectly) {
84
84
  const { dir: currentRun, agent: currentAgent } = getRun();
85
85
  if (currentRun) {
86
86
  try {
87
- fs.appendFileSync(path.join(currentRun, 'raw.log'), `\nrun-codex crash: ${err.stack}\n`);
87
+ fs.appendFileSync(path.join(currentRun, 'stderr.log'), `\nrun-codex crash: ${err.stack}\n`);
88
88
  const { reply } = writeFailure(currentRun, currentAgent, `Codex runner crashed: ${err.message}`, [
89
- `Log: ${path.join(currentRun, 'raw.log')}`,
89
+ `Log: codex-bridge read ${currentRun}`,
90
90
  ]);
91
91
  emitReply(reply);
92
92
  process.exit(1);
@@ -1,4 +1,8 @@
1
1
  {
2
2
  "hooks": false,
3
- "plugins": false
3
+ "plugins": false,
4
+ "retention": {
5
+ "enabled": true,
6
+ "days": 30
7
+ }
4
8
  }