levi-gear 0.4.0 → 0.5.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.
@@ -1,35 +1,23 @@
1
1
  #!/usr/bin/env node
2
- // Quota guard helper installed with every levi skill. It reads how much of the 5-hour usage
3
- // window is used, and (on Codex) arms a crontab job that resumes an interrupted run once the
4
- // quota is back. It never runs a levi workflow itself.
2
+ // Quota guard helper installed with every levi skill. It reads how much of the Claude Code
3
+ // 5-hour usage window is used. It never runs a levi workflow itself.
5
4
  //
6
- // check --tool claude|codex [--threshold 95] print the 5-hour usage as JSON
7
- // record [--passthrough] statusline hook: save Claude Code's usage (JSON on stdin)
8
- // cron-arm --session <id> --project <dir> [--every 2] [--threshold 95] [-- <codex exec resume flags>]
9
- // cron-disarm --session <id>
10
- // cron-fire --session <id> --project <dir> [--threshold 95] [-- <flags>] called by the crontab line
5
+ // check [--threshold 95] print the 5-hour usage as JSON
6
+ // record [--passthrough] statusline hook: save Claude Code's usage (JSON on stdin)
11
7
 
12
8
  import fs from 'node:fs';
13
9
  import os from 'node:os';
14
10
  import path from 'node:path';
15
- import { spawnSync } from 'node:child_process';
16
- import { fileURLToPath } from 'node:url';
17
11
 
18
12
  const THRESHOLD = 95;
19
- const EVERY_HOURS = 2;
20
- const FIVE_HOURS = 300;
21
13
  const STALE_MS = 30 * 60 * 1000;
22
- const TAIL_BYTES = 512 * 1024;
23
- const RESUME_PROMPT = 'I ran out of quota a moment ago and the run was interrupted. Please continue the process or workflow you were running.';
24
14
 
25
- const claudeFile = () => path.join(process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude'), 'levi-quota.json');
26
- const codexSessions = () => path.join(process.env.CODEX_HOME || path.join(os.homedir(), '.codex'), 'sessions');
15
+ const usageFile = () => path.join(process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude'), 'levi-quota.json');
27
16
 
28
- function result(tool, fields) {
29
- const threshold = fields.threshold;
17
+ function result(fields) {
30
18
  const used = fields.usedPercent;
31
19
  const known = typeof used === 'number';
32
- return { tool, status: known ? 'ok' : 'unknown', ...fields, atThreshold: known && used >= threshold };
20
+ return { status: known ? 'ok' : 'unknown', ...fields, atThreshold: known && used >= fields.threshold };
33
21
  }
34
22
 
35
23
  // A window whose reset time has passed holds no usage any more.
@@ -39,54 +27,12 @@ function window(used, resetsAtSeconds, now = Date.now()) {
39
27
  return { usedPercent: passed ? 0 : used, resetsAt: resetsAtSeconds ? new Date(resetsAtSeconds * 1000).toISOString() : null };
40
28
  }
41
29
 
42
- function checkClaude(threshold) {
43
- const file = claudeFile();
44
- if (!fs.existsSync(file)) return result('claude', { threshold, source: file, reason: 'the statusline bridge is not set up (no usage file)' });
30
+ function check(threshold) {
31
+ const file = usageFile();
32
+ if (!fs.existsSync(file)) return result({ threshold, source: file, reason: 'the statusline bridge is not set up (no usage file)' });
45
33
  const saved = JSON.parse(fs.readFileSync(file, 'utf8'));
46
- if (Date.now() - saved.recordedAt > STALE_MS) return result('claude', { threshold, source: file, reason: 'the usage file is stale' });
47
- return result('claude', { threshold, source: file, ...window(saved.usedPercent, saved.resetsAt) });
48
- }
49
-
50
- function newestRollout(dir) {
51
- if (!fs.existsSync(dir)) return null;
52
- const files = fs.readdirSync(dir, { recursive: true }).filter((f) => /rollout-.*\.jsonl$/.test(f)).sort();
53
- return files.length ? path.join(dir, files[files.length - 1]) : null;
54
- }
55
-
56
- function lastRateLimits(file) {
57
- const size = fs.statSync(file).size;
58
- const fd = fs.openSync(file, 'r');
59
- const buffer = Buffer.alloc(Math.min(size, TAIL_BYTES));
60
- fs.readSync(fd, buffer, 0, buffer.length, size - buffer.length);
61
- fs.closeSync(fd);
62
- const lines = buffer.toString('utf8').split('\n').reverse();
63
- for (const line of lines) {
64
- if (!line.includes('"rate_limits"')) continue;
65
- try {
66
- const event = JSON.parse(line);
67
- const limits = (event.payload && event.payload.rate_limits) || event.rate_limits;
68
- if (limits && typeof limits === 'object') return limits;
69
- } catch {
70
- // The first line of the tail may be cut in half; skip it.
71
- }
72
- }
73
- return null;
74
- }
75
-
76
- function checkCodex(threshold) {
77
- const file = newestRollout(codexSessions());
78
- if (!file) return result('codex', { threshold, source: codexSessions(), reason: 'no Codex session file found' });
79
- const sessionId = process.env.CODEX_THREAD_ID || (file.match(/([0-9a-f-]{36})\.jsonl$/) || [])[1] || null;
80
- const limits = lastRateLimits(file);
81
- const fiveHour = limits && [limits.primary, limits.secondary].find((w) => w && w.window_minutes === FIVE_HOURS);
82
- if (!fiveHour) return result('codex', { threshold, source: file, sessionId, reason: 'no 5-hour rate limit recorded yet' });
83
- return result('codex', { threshold, source: file, sessionId, ...window(fiveHour.used_percent, fiveHour.resets_at) });
84
- }
85
-
86
- function check(tool, threshold) {
87
- if (tool === 'claude') return checkClaude(threshold);
88
- if (tool === 'codex') return checkCodex(threshold);
89
- return result(tool, { threshold, reason: `no way to read the quota of "${tool}"` });
34
+ if (Date.now() - saved.recordedAt > STALE_MS) return result({ threshold, source: file, reason: 'the usage file is stale' });
35
+ return result({ threshold, source: file, ...window(saved.usedPercent, saved.resetsAt) });
90
36
  }
91
37
 
92
38
  // Statusline hook for Claude Code: the only place it shows the usage is the JSON it pipes in.
@@ -94,7 +40,7 @@ function record(passthrough) {
94
40
  const input = fs.readFileSync(0, 'utf8');
95
41
  try {
96
42
  const five = JSON.parse(input).rate_limits.five_hour;
97
- fs.writeFileSync(claudeFile(), JSON.stringify({ recordedAt: Date.now(), usedPercent: five.used_percentage, resetsAt: five.resets_at }) + '\n');
43
+ fs.writeFileSync(usageFile(), JSON.stringify({ recordedAt: Date.now(), usedPercent: five.used_percentage, resetsAt: five.resets_at }) + '\n');
98
44
  if (!passthrough) process.stdout.write(`5h ${Math.round(five.used_percentage)}%`);
99
45
  } catch {
100
46
  if (!passthrough) process.stdout.write('5h ?');
@@ -102,89 +48,22 @@ function record(passthrough) {
102
48
  if (passthrough) process.stdout.write(input);
103
49
  }
104
50
 
105
- // ---- crontab job (Codex) ----
106
-
107
- const crontab = () => process.env.LEVI_CRONTAB || 'crontab';
108
- const marker = (session) => `# levi-quota-resume ${session}`;
109
- const quote = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`;
110
-
111
- function readCrontab() {
112
- const out = spawnSync(crontab(), ['-l'], { encoding: 'utf8' });
113
- return out.status === 0 ? out.stdout.split('\n').filter((l) => l.trim()) : [];
114
- }
115
-
116
- function writeCrontab(lines) {
117
- const out = spawnSync(crontab(), ['-'], { input: lines.join('\n') + (lines.length ? '\n' : ''), encoding: 'utf8' });
118
- if (out.status !== 0) throw new Error(`crontab failed: ${out.stderr || out.stdout}`);
119
- }
120
-
121
- const withoutJob = (lines, session) => lines.filter((l) => !l.endsWith(marker(session)));
122
-
123
- function which(name) {
124
- for (const dir of (process.env.PATH || '').split(path.delimiter)) {
125
- const file = path.join(dir, name);
126
- if (fs.existsSync(file)) return file;
127
- }
128
- return null;
129
- }
130
-
131
- function arm({ session, project, every, threshold, flags }) {
132
- const codex = which('codex');
133
- if (!codex) throw new Error('codex is not on PATH, so the resume job cannot call it');
134
- const self = fileURLToPath(import.meta.url);
135
- const log = path.join(os.tmpdir(), `levi-quota-resume-${session}.log`);
136
- const command = [process.execPath, self, 'cron-fire', '--session', session, '--project', project, '--threshold', threshold, '--codex', codex, '--', ...flags]
137
- .map(quote)
138
- .join(' ');
139
- // 7 minutes past, so that jobs do not all start on the hour. "%" is special inside a crontab line.
140
- const line = `7 */${every} * * * ${command} >> ${quote(log)} 2>&1 ${marker(session)}`.replace(/%/g, '\\%');
141
- writeCrontab([...withoutJob(readCrontab(), session), line]);
142
- const daemon = spawnSync('pgrep', ['-x', 'cron']).status === 0 || spawnSync('pgrep', ['-x', 'crond']).status === 0;
143
- return { armed: true, session, every, log, cronRunning: daemon, warning: daemon ? null : 'no cron daemon is running; start it (on WSL: enable systemd or run `sudo service cron start`) or the job will never fire' };
144
- }
145
-
146
- function disarm(session) {
147
- writeCrontab(withoutJob(readCrontab(), session));
148
- return { armed: false, session };
149
- }
150
-
151
- // Called by cron. While the quota is still used up it does nothing; otherwise it removes its
152
- // own job first (the resumed run re-arms one if it runs low again), then resumes the session.
153
- function fire({ session, project, threshold, flags, codex }) {
154
- const state = check('codex', threshold);
155
- if (state.atThreshold) return { fired: false, reason: 'quota still used up', state };
156
- disarm(session);
157
- const run = spawnSync(codex || 'codex', ['exec', 'resume', ...flags, session, RESUME_PROMPT], { cwd: project, stdio: 'inherit' });
158
- if (run.status !== 0) arm({ session, project, every: EVERY_HOURS, threshold, flags });
159
- return { fired: true, exitCode: run.status };
160
- }
161
-
162
- // ---- command line ----
163
-
164
51
  function parseArgs(argv) {
165
- const split = argv.indexOf('--');
166
- const flags = split === -1 ? [] : argv.slice(split + 1);
167
52
  const options = {};
168
- const own = split === -1 ? argv : argv.slice(0, split);
169
- for (let i = 0; i < own.length; i++) {
170
- if (!own[i].startsWith('--')) continue;
171
- const next = own[i + 1];
172
- options[own[i].slice(2)] = next === undefined || next.startsWith('--') ? true : (i++, next);
53
+ for (let i = 0; i < argv.length; i++) {
54
+ if (!argv[i].startsWith('--')) continue;
55
+ const next = argv[i + 1];
56
+ options[argv[i].slice(2)] = next === undefined || next.startsWith('--') ? true : (i++, next);
173
57
  }
174
- return { options, flags };
58
+ return options;
175
59
  }
176
60
 
177
61
  function main() {
178
62
  const [command, ...rest] = process.argv.slice(2);
179
- const { options, flags } = parseArgs(rest);
180
- const threshold = Number(options.threshold || THRESHOLD);
181
- const job = { session: options.session, project: path.resolve(options.project || '.'), every: Number(options.every || EVERY_HOURS), threshold, flags, codex: options.codex };
63
+ const options = parseArgs(rest);
182
64
  if (command === 'record') return record(Boolean(options.passthrough));
183
- if (command === 'check') return console.log(JSON.stringify(check(options.tool, threshold), null, 2));
184
- if (!['cron-arm', 'cron-disarm', 'cron-fire'].includes(command)) throw new Error('usage: quota-check.mjs check|record|cron-arm|cron-disarm|cron-fire ...');
185
- if (!job.session) throw new Error('--session is required');
186
- const actions = { 'cron-arm': () => arm(job), 'cron-disarm': () => disarm(job.session), 'cron-fire': () => fire(job) };
187
- console.log(JSON.stringify(actions[command](), null, 2));
65
+ if (command === 'check') return console.log(JSON.stringify(check(Number(options.threshold || THRESHOLD)), null, 2));
66
+ throw new Error('usage: quota-check.mjs check|record ...');
188
67
  }
189
68
 
190
69
  try {
@@ -1,6 +1,6 @@
1
1
  ## Run rules
2
2
 
3
- These rules apply to every levi usecase, in every tool. Where they disagree with a step above about asking the user, they win. The user is often away from the keyboard: a run that stops half-way to ask something stays stopped.
3
+ These rules apply to every levi usecase. Where they disagree with a step above about asking the user, they win. The user is often away from the keyboard: a run that stops half-way to ask something stays stopped.
4
4
 
5
5
  ### Ask first, then run alone
6
6
 
@@ -21,29 +21,22 @@ When the work yields several acceptable options and picking one can be undone ch
21
21
 
22
22
  ### Quota guard
23
23
 
24
- Applies to every run with more than one stage. You are on Claude Code, Codex or another tool; the steps differ only where marked. Script paths are relative to this skill's folder.
25
-
26
- 1. At every stage boundary (after a stage, before dispatching the next agents, before each build round) run `node scripts/quota-check.mjs check --tool <claude|codex>` from this skill's folder and read its JSON. `atThreshold` means 95% or more of the 5-hour window is used.
27
- 2. **Usage unknown** (`status: unknown`: Claude Code without the statusline bridge, API-key billing, Copilot): arm the resume job once, right after the opening questions are answered, and keep it until the run ends.
28
- 3. **At the threshold:** finish the step in progress, make sure the checkpoint is written (Codex: `run.json`; the work folder holds the rest), write the handoff report (below), and arm the resume job if it is not armed. Then keep working; the job matters only if the limit really interrupts the run. The report is always the single file `docs/breakpoints/handoff.md`; each time the threshold is reached it is overwritten whole, never appended to and never written anywhere else.
29
- 4. **Arming** the job, with this exact prompt: `I ran out of quota a moment ago and the run was interrupted. Please continue the process or workflow you were running.`
30
- - *Claude Code:* `CronList` first, to avoid a duplicate; then `CronCreate` (load it with `ToolSearch` if it is deferred), recurring, cron `7 */2 * * *`, with that prompt.
31
- - *Codex, when this session has a scheduled-task tool* (the Codex app lists such tasks under "Scheduled"): list the existing scheduled tasks first, to avoid a duplicate, then create one that repeats every 2 hours with that prompt, attached to this thread.
32
- - *Codex, without such a tool:* `node scripts/quota-check.mjs cron-arm --session <sessionId from check> --project <project root> -- <the approval and sandbox flags of this session, for example --full-auto>`. It writes a crontab line every 2 hours; the line does nothing while the quota is used up, removes itself before it resumes the session, and puts itself back if the resume fails. Pass on its `warning` to the user.
33
- - *No way to arm* (no scheduler tool, Copilot): tell the user in your next message that the run will not resume on its own, and go on.
34
- **Handoff report.** Exactly one file, `docs/breakpoints/handoff.md` (create the folder if missing). It is overwritten whole every time it is written: the previous content belongs to an earlier interruption and is replaced, except that unfinished items from it that are still unfinished must be carried into the new one. It must be enough on its own: the next session may be this same session, or another agent on another coding platform, and it will read only this file, with no chat history, no skills and no scheduler. So write it from scratch for a reader who knows nothing, in the user's language, with only what is true now, no filler, no references to "above" or "as discussed", and every path relative to the project root. Sections, in this order:
24
+ Applies to every run with more than one stage. Script paths are relative to this skill's folder.
25
+
26
+ 1. At every stage boundary (after a stage, before dispatching the next agents, before each build round) run `node scripts/quota-check.mjs check` from this skill's folder and read its JSON. `atThreshold` means 95% or more of the 5-hour window is used.
27
+ 2. **Usage unknown** (`status: unknown`: no statusline bridge, or API-key billing): arm the resume job once, right after the opening questions are answered, and keep it until the run ends.
28
+ 3. **At the threshold:** finish the step in progress, make sure the work folder holds everything finished so far, write the handoff report (below), and arm the resume job if it is not armed. Then keep working; the job matters only if the limit really interrupts the run. The report is always the single file `docs/breakpoints/handoff.md`; each time the threshold is reached it is overwritten whole, never appended to and never written anywhere else.
29
+ 4. **Arming** the job, with this exact prompt: `I ran out of quota a moment ago and the run was interrupted. Please continue the process or workflow you were running.` Run `CronList` first, to avoid a duplicate; then `CronCreate` (load it with `ToolSearch` if it is deferred), recurring, cron `7 */2 * * *`, with that prompt. If `CronCreate` is not available, tell the user in your next message that the run will not resume on its own, and go on.
30
+ **Handoff report.** Exactly one file, `docs/breakpoints/handoff.md` (create the folder if missing). It is overwritten whole every time it is written: the previous content belongs to an earlier interruption and is replaced, except that unfinished items from it that are still unfinished must be carried into the new one. It must be enough on its own: the next session may be this same session, or another agent, and it will read only this file, with no chat history, no skills and no scheduler. So write it from scratch for a reader who knows nothing, in the user's language, with only what is true now, no filler, no references to "above" or "as discussed", and every path relative to the project root. Sections, in this order:
35
31
  - *Status line:* the first line, `Status: interrupted | complete`, then the date, time and the usage reading (`usedPercent`, `resetsAt`).
36
32
  - *Goal and request:* the original request in the user's words, the usecase and its arguments, and the answers given in the opening questions.
37
- - *Project context:* what the project is, the stack, the branch, how to build and test it, and the files and folders an agent must read first (specs, plans, designs, `AGENTS.md`/`CLAUDE.md`, the work folder).
33
+ - *Project context:* what the project is, the stack, the branch, how to build and test it, and the files and folders an agent must read first (specs, plans, designs, `CLAUDE.md`, the work folder).
38
34
  - *Progress:* a stage table with status `done`, `in progress` or `not started`, each with a one-line result; for `in progress`, exactly where it stopped and what remains in it.
39
35
  - *Done:* the deliverables made so far (path, what it is, whether it is verified), decisions taken and why, and the commands run with their result (tests, builds, checks).
40
36
  - *Next steps:* the ordered list of what is left, concrete enough to execute, and the first action to take. Say how to skip finished work.
41
- - *State of the work:* files created or changed and not yet committed, anything half-written or inconsistent, and where checkpoints live (`run.json`, `choices/`, other work-folder files).
37
+ - *State of the work:* files created or changed and not yet committed, anything half-written or inconsistent, and where checkpoints live (`choices/`, other work-folder files).
42
38
  - *Open items:* parked questions with the assumption used meanwhile, known problems, risks, and the choices made so far (link to `choices/`).
43
- - *How to continue:* commands to verify the current state, and the continuation steps as plain instructions that do not depend on any one tool.
39
+ - *How to continue:* commands to verify the current state, and the continuation steps as plain instructions.
44
40
  Never put secrets or credentials in it. Mention the path in your next message to the user.
45
- 5. **When that prompt arrives, the job has fired and you are the resumed run.** Find what was interrupted (Codex: a `docs/levi/*/run.json` that is not complete; Claude Code: your own context and the work folder; for a Workflow run, stop the old run and continue it with `resumeFromRunId`) and continue from the recorded stage without repeating finished stages; read `docs/breakpoints/handoff.md` first when it exists. If nothing was interrupted, delete the job and say there is nothing to resume.
46
- - *Claude Code:* run `check`. When usage is known and below the threshold, delete the job (`CronList`, then `CronDelete` the one with this prompt); when it is at the threshold or unknown, keep it.
47
- - *Codex with a scheduled-task tool:* the same as Claude Code: delete the task when usage is known and below the threshold.
48
- - *Codex with the crontab job:* nothing to delete; the crontab line already removed itself.
49
- 6. **When the run ends** (done, blocked or stalled), if `docs/breakpoints/handoff.md` exists, overwrite it with `Status: complete` and what is left (nothing, or the parked items) and name the file in the final report, then remove the job: Claude Code `CronDelete`; Codex delete the scheduled task (when the tool cannot delete, name the task in the final report so the user removes it from the Scheduled list; a firing that finds nothing interrupted only says so), or for the crontab job run `node scripts/quota-check.mjs cron-disarm --session <sessionId>`.
41
+ 5. **When that prompt arrives, the job has fired and you are the resumed run.** Find what was interrupted from your own context and the work folder (for a Workflow run, stop the old run and continue it with `resumeFromRunId`) and continue from the recorded stage without repeating finished stages; read `docs/breakpoints/handoff.md` first when it exists. If nothing was interrupted, delete the job and say there is nothing to resume. Run `check`: when usage is known and below the threshold, delete the job (`CronList`, then `CronDelete` the one with this prompt); when it is at the threshold or unknown, keep it.
42
+ 6. **When the run ends** (done, blocked or stalled), if `docs/breakpoints/handoff.md` exists, overwrite it with `Status: complete` and what is left (nothing, or the parked items) and name the file in the final report, then remove the job with `CronDelete`.
@@ -27,10 +27,6 @@ This usecase plans; it does not write specs. Never create or edit anything under
27
27
 
28
28
  `<slug>` is a short kebab-case name for the problem, in English (for example `export-orders-csv`). Create folders as needed. Pass each agent the exact paths it should read and write. When the run finishes, only the plan is left behind (and the spec, untouched, if the project had one).
29
29
 
30
- ## Codex runner
31
-
32
- On Codex, use [`references/codex-runner.md`](references/codex-runner.md). It records the planning stage in `docs/levi/<slug>/run.json`, so a stopped run resumes from its artifact checkpoint rather than from conversation memory.
33
-
34
30
  ## Steps
35
31
 
36
32
  1. **Intake.** The request is the problem. If it is empty, ask what to brainstorm and stop. Derive the slug and a plain-language problem name.
@@ -29,10 +29,6 @@ skill-guide: references/review-guide.md
29
29
 
30
30
  Nothing is written into the project. The review is given in the conversation.
31
31
 
32
- ## Codex runner
33
-
34
- On Codex, use [`references/codex-runner.md`](references/codex-runner.md). This workflow is deliberately stateless: its single read-only review dispatch is safe to restart after an interruption.
35
-
36
32
  ## Steps
37
33
 
38
34
  1. **Target.** Work out what to review from the request:
@@ -12,7 +12,7 @@ Build a feature the spec-driven way: **the spec decides, the tests and scenarios
12
12
  The work has two halves:
13
13
 
14
14
  - **Prepare** (steps 1 to 5), here in the conversation, because it needs the user: the spec, the brainstorming plan and the designs. It reuses the `spec-writing`, `brainstorming` and `design` usecases.
15
- - **Implement** (step 6), without the user: tests, scenarios, code, end-to-end runs and code review. Every agent call is a fresh, independent subagent that sees only the files it is given, never the conversation or another agent's reasoning. Claude Code runs `workflow.js`; Codex uses the durable runner in [`references/codex-runner.md`](references/codex-runner.md).
15
+ - **Implement** (step 6), without the user: tests, scenarios, code, end-to-end runs and code review. Every agent call is a fresh, independent subagent that sees only the files it is given, never the conversation or another agent's reasoning. Claude Code runs `workflow.js`.
16
16
 
17
17
  ## The rules that never bend
18
18
 
@@ -68,13 +68,12 @@ The work has two halves:
68
68
  ```
69
69
 
70
70
  The script runs the steps under [Implementation](#implementation) below and returns a result with a `status`. Follow its progress with the user only when they ask.
71
- - *On Codex:* follow [`references/codex-runner.md`](references/codex-runner.md). It persists the stage in `docs/levi/<slug>/run.json`, so a stopped run resumes from the recorded stage rather than restarting. Run the steps under [Implementation](#implementation) through that runner, each agent call as a new named subagent call that gets only the paths and instructions written there.
72
- - *Other tools without a Workflow tool:* run the steps under [Implementation](#implementation) yourself, in order, each agent call as a new subagent call that gets only the paths and instructions written there.
71
+ - *Without a Workflow tool:* run the steps under [Implementation](#implementation) yourself, in order, each agent call as a new subagent call that gets only the paths and instructions written there.
73
72
  7. **Act on the result.**
74
73
  - `done`: go to step 8.
75
74
  - `spec_questions`: the spec is silent or unclear on a point the tests depend on. Ask the user the questions in one round, run the `spec-writing` flow in update mode with the answers, then run step 6 again from the start.
76
75
  - `blocked`: something outside the code stops the work (the app cannot start, a service or a credential is missing, an agent could not finish). Tell the user the stage and the detail, and what they need to provide. Keep `docs/levi/<slug>/`. Run step 6 again when they say to.
77
- - `stalled`: the build rounds ran out (10 by default) and something still fails. Tell the user what failed last. On Claude Code, continue in the same session with `resumeFromRunId` and a higher `maxRounds`; on Codex, keep `run.json` and resume its active `build` stage after the user asks to continue. Tests and test cases still do not change.
76
+ - `stalled`: the build rounds ran out (10 by default) and something still fails. Tell the user what failed last. Continue in the same session with `resumeFromRunId` and a higher `maxRounds`. Tests and test cases still do not change.
78
77
  8. **Clean up.** Delete `docs/levi/<slug>/` (`tasks.md`, `review.md`, `locked/`), then `docs/levi` if it is empty. Keep everything else: spec, plan, designs, tests, test cases with their results, code.
79
78
  9. **Report.** Tell the user: the spec, plan and designs used (and which were created in this run); the test files and the command that runs them; the test case files with their result (for example `12/12 PASS`); how many build rounds it took; the review outcome and the suggestions left open; the files changed (from `git status`); and that nothing was committed.
80
79
 
@@ -33,10 +33,6 @@ A design is built from what the user gave: the text, the images, the frames of t
33
33
 
34
34
  `<slug>` is a short kebab-case name for what is designed, in English (for example `login-screen`). Create folders as needed. Pass the designer the exact paths it should read and write. The files the user uploaded are the user's: never move, edit or delete them.
35
35
 
36
- ## Codex runner
37
-
38
- On Codex, use [`references/codex-runner.md`](references/codex-runner.md). It checkpoints reference preparation, drawing and validation in `docs/levi/<slug>/run.json` so a stopped run resumes safely.
39
-
40
36
  ## Steps
41
37
 
42
38
  1. **Intake.** The request is the text plus the attachments. If there is neither text nor an attachment, ask what to design and stop. Derive the slug. List every image and video with its file path. Note the user's intent for each: recreate it, take its style, or extract its flow.
@@ -14,7 +14,7 @@ Fix a bug with the team: `levi-developer` clarifies, investigates and fixes, `le
14
14
  The work has two halves:
15
15
 
16
16
  - **Clarify** (steps 1 to 5), here in the conversation, because it needs the user. The developer lists what is unclear and the user confirms it.
17
- - **Fix** (step 6), without the user. Claude Code runs `workflow.js`; Codex uses the durable runner in [`references/codex-runner.md`](references/codex-runner.md). Every agent call is a fresh subagent that sees only the files it is given, and the developer and QA work at the same time without reading each other's work.
17
+ - **Fix** (step 6), without the user. Claude Code runs `workflow.js`. Every agent call is a fresh subagent that sees only the files it is given, and the developer and QA work at the same time without reading each other's work.
18
18
 
19
19
  ## The rules that never bend
20
20
 
@@ -67,15 +67,14 @@ The work has two halves:
67
67
  ```
68
68
 
69
69
  Set `allMerged` to false when step 2 found unmerged work.
70
- - *On Codex:* follow [`references/codex-runner.md`](references/codex-runner.md), which persists `docs/levi/<slug>/run.json`, then run the steps under [Workflow](#workflow) through that runner.
71
- - *Other tools without a Workflow tool:* run the steps under [Workflow](#workflow) below yourself, in order, each agent call as a new subagent call that gets only the paths and instructions written there.
70
+ - *Without a Workflow tool:* run the steps under [Workflow](#workflow) below yourself, in order, each agent call as a new subagent call that gets only the paths and instructions written there.
72
71
  7. **Act on the result.**
73
72
  - `done`: go to step 8.
74
73
  - `questions`: an agent found a point that is still open. Ask the user, append the answers to `confirmed.md`, and run step 6 again.
75
74
  - `not_a_bug`: the developer found that the code does what the spec and the confirmed points expect. Tell the user why, clean up (step 8) and stop.
76
75
  - `unmerged`: the root cause is in code that is not merged into the base branch. Tell the user it is a revision of unmerged work, not a bug, with the root cause and its locations. Clean up and stop. The code was not changed.
77
76
  - `blocked`: something outside the code stops the work (the app cannot start, a service or credential is missing, no test could be made to fail on the bug). Tell the user the stage, the detail and what they need to provide. Keep `docs/levi/<slug>/` and run step 6 again when they say to.
78
- - `stalled`: the rounds ran out (10 by default) and something still fails. Tell the user what failed last. On Claude Code, continue in the same session with `resumeFromRunId` and a higher `maxRounds`; on Codex, keep `run.json` and resume the active `build` stage when the user asks to continue. Tests and test cases still do not change.
77
+ - `stalled`: the rounds ran out (10 by default) and something still fails. Tell the user what failed last. Continue in the same session with `resumeFromRunId` and a higher `maxRounds`. Tests and test cases still do not change.
79
78
  8. **Clean up.** Delete `docs/levi/<slug>/`, then `docs/levi` if it is empty. Keep everything else.
80
79
  9. **Report.** Tell the user: the root cause and where it was; the tests that cover the bug (written now, or existing ones) and the command that runs them; the test case files with their result (for example `4/4 PASS`); how many rounds it took; the review outcome and the suggestions left open; the files changed (from `git status`); and that nothing was committed.
81
80
 
@@ -26,7 +26,6 @@ skill-guide: references/test-case-guide.md
26
26
  | `docs/tests/<base>.xlsx` | QA | **Deliverable**: one sheet, one row per case, columns `ID, Title, Category, Priority, Preconditions, Steps, Expected Result, Notes` |
27
27
  | `docs/levi/test-cases/<FeatureID>-analysis.md` | QA | Scratch: spec items, coverage plan, ambiguities, readiness |
28
28
  | `docs/levi/test-cases/<FeatureID>.json` | QA | Scratch: the cases the two deliverables are rendered from |
29
- | `docs/levi/test-cases/selection.md` | Workflow | Scratch: the confirmed feature list, output bases and overwrite choices for a resumable Codex run |
30
29
  | `references/test-case-guide.md` | - | How QA analyzes the spec and writes the cases |
31
30
  | `scripts/render-test-cases.mjs` | - | Checks the cases and renders both deliverables from them, so they always agree. The cases are also embedded in the `.md`, so QA can change them later |
32
31
 
@@ -41,10 +40,6 @@ A feature is one spec file, or one folder of spec files, under `docs/specs/` (se
41
40
  | Output `<base>` | `<FeatureID>-<slug>` when the spec has a code (`F001-login`); `<slug>-test-cases` when it has none (`export-orders-csv-test-cases`) |
42
41
  | Case ID | `TC-<FeatureID>-<3 digits>`, for example `TC-F001-001` |
43
42
 
44
- ## Codex runner
45
-
46
- On Codex, use [`references/codex-runner.md`](references/codex-runner.md). It checkpoints selection, per-feature QA work and verification in `docs/levi/test-cases/run.json` so a stopped run does not silently regenerate finished outputs.
47
-
48
43
  ## Steps
49
44
 
50
45
  1. **Intake.** From the request, take the feature codes (`F001`, `F002`, ...) and the spec files or folders it names. Anything else in it (a focus such as "only permissions") is passed to QA as written.
@@ -22,10 +22,6 @@ A spec is a promise to the rest of the team: **a line goes into the spec only wh
22
22
 
23
23
  `<slug>` is a short kebab-case name for the subject, in English (for example `export-orders-csv`). Create folders as needed. Pass the PM the exact paths it should read and write. Only the PM touches either file.
24
24
 
25
- ## Codex runner
26
-
27
- On Codex, use [`references/codex-runner.md`](references/codex-runner.md). It persists question rounds and the selected output in `docs/levi/<slug>/run.json`, allowing the run to continue after an interruption.
28
-
29
25
  ## Steps
30
26
 
31
27
  1. **Intake.** The request is the subject. If it is empty, ask what the spec is about and stop. Derive the slug. Note every file or link the user mentioned: they are sources.
@@ -1,156 +0,0 @@
1
- #!/usr/bin/env node
2
- // Durable, tool-neutral checkpoint helper installed with every Codex levi skill.
3
- // It deliberately does not run agents: the Codex skill remains responsible for
4
- // dispatching the right role, while this file makes a stopped run resumable.
5
-
6
- import fs from 'node:fs';
7
- import path from 'node:path';
8
-
9
- const [command, workDir, ...args] = process.argv.slice(2);
10
- const stateFile = workDir && path.join(workDir, 'run.json');
11
-
12
- function die(message) {
13
- console.error(message);
14
- process.exitCode = 2;
15
- }
16
-
17
- function read() {
18
- if (!stateFile || !fs.existsSync(stateFile)) throw new Error(`no run state at ${stateFile || '<workdir>'}`);
19
- return JSON.parse(fs.readFileSync(stateFile, 'utf8'));
20
- }
21
-
22
- function write(state) {
23
- fs.mkdirSync(workDir, { recursive: true });
24
- state.updatedAt = new Date().toISOString();
25
- const temporary = `${stateFile}.${process.pid}.tmp`;
26
- fs.writeFileSync(temporary, JSON.stringify(state, null, 2) + '\n');
27
- try {
28
- fs.renameSync(temporary, stateFile);
29
- } catch (error) {
30
- // Some Windows filesystems do not replace an existing destination on rename.
31
- // The completed temporary file is still safer than writing JSON in place.
32
- if (!['EEXIST', 'EPERM'].includes(error.code)) throw error;
33
- fs.copyFileSync(temporary, stateFile);
34
- fs.unlinkSync(temporary);
35
- }
36
- }
37
-
38
- function print(value) {
39
- console.log(JSON.stringify(value, null, 2));
40
- }
41
-
42
- function stage(state, name) {
43
- const found = state.stages.find((item) => item.name === name);
44
- if (!found) throw new Error(`unknown stage "${name}"; expected one of: ${state.stages.map((item) => item.name).join(', ')}`);
45
- return found;
46
- }
47
-
48
- function previousStagesComplete(state, current) {
49
- const index = state.stages.indexOf(current);
50
- return state.stages.slice(0, index).every((item) => item.status === 'complete');
51
- }
52
-
53
- function record(state, type, details = {}) {
54
- state.history.push({ at: new Date().toISOString(), type, ...details });
55
- }
56
-
57
- function update(commandName, callback) {
58
- const state = read();
59
- callback(state);
60
- write(state);
61
- print({ command: commandName, state: state.status, currentStage: state.currentStage, file: stateFile });
62
- }
63
-
64
- try {
65
- if (command === 'init') {
66
- const [usecase, slug, ...stageNames] = args;
67
- if (!usecase || !slug || !stageNames.length) throw new Error('usage: init <workdir> <usecase> <slug> <stage>...');
68
- if (new Set(stageNames).size !== stageNames.length) throw new Error('stage names must be unique');
69
- if (fs.existsSync(stateFile)) throw new Error(`run state already exists at ${stateFile}; use status or resume instead`);
70
- const now = new Date().toISOString();
71
- const state = {
72
- version: 1,
73
- runtime: 'codex',
74
- usecase,
75
- slug,
76
- status: 'running',
77
- currentStage: stageNames[0],
78
- createdAt: now,
79
- updatedAt: now,
80
- stages: stageNames.map((name) => ({ name, status: 'pending', attempts: 0, artifacts: [] })),
81
- history: [{ at: now, type: 'initialized' }],
82
- };
83
- write(state);
84
- print({ command: 'init', state: state.status, currentStage: state.currentStage, file: stateFile });
85
- } else if (command === 'status') {
86
- const state = read();
87
- print({ state: state.status, currentStage: state.currentStage, stages: state.stages, history: state.history, file: stateFile });
88
- } else if (command === 'begin') {
89
- const [name] = args;
90
- update(command, (state) => {
91
- if (state.status !== 'running') throw new Error(`cannot begin while run is ${state.status}; use resume first`);
92
- const current = stage(state, name);
93
- if (state.currentStage !== name) throw new Error(`cannot begin ${name}; current stage is ${state.currentStage}`);
94
- if (!previousStagesComplete(state, current)) throw new Error(`cannot begin ${name}; an earlier stage is incomplete`);
95
- if (current.status === 'complete') throw new Error(`${name} is already complete`);
96
- current.status = 'active';
97
- current.attempts += 1;
98
- record(state, 'began', { stage: name, attempt: current.attempts });
99
- });
100
- } else if (command === 'complete') {
101
- const [name, ...artifacts] = args;
102
- update(command, (state) => {
103
- if (state.status !== 'running') throw new Error(`cannot complete while run is ${state.status}`);
104
- const current = stage(state, name);
105
- if (state.currentStage !== name) throw new Error(`cannot complete ${name}; current stage is ${state.currentStage}`);
106
- if (!['active', 'pending'].includes(current.status)) throw new Error(`${name} is ${current.status}, not active`);
107
- const missing = artifacts.filter((artifact) => !fs.existsSync(artifact));
108
- if (missing.length) throw new Error(`cannot complete ${name}; missing artifact(s): ${missing.join(', ')}`);
109
- current.status = 'complete';
110
- current.completedAt = new Date().toISOString();
111
- current.artifacts = [...new Set([...current.artifacts, ...artifacts])];
112
- const next = state.stages[state.stages.indexOf(current) + 1];
113
- state.currentStage = next ? next.name : null;
114
- state.status = next ? 'running' : 'done';
115
- record(state, 'completed', { stage: name, artifacts });
116
- });
117
- } else if (command === 'finish') {
118
- const [name, ...artifacts] = args;
119
- update(command, (state) => {
120
- const current = stage(state, name);
121
- if (state.currentStage !== name) throw new Error(`cannot finish at ${name}; current stage is ${state.currentStage}`);
122
- const missing = artifacts.filter((artifact) => !fs.existsSync(artifact));
123
- if (missing.length) throw new Error(`cannot finish at ${name}; missing artifact(s): ${missing.join(', ')}`);
124
- current.status = 'complete';
125
- current.completedAt = new Date().toISOString();
126
- current.artifacts = [...new Set([...current.artifacts, ...artifacts])];
127
- for (const later of state.stages.slice(state.stages.indexOf(current) + 1)) later.status = 'skipped';
128
- state.currentStage = null;
129
- state.status = 'done';
130
- record(state, 'finished', { stage: name, artifacts });
131
- });
132
- } else if (command === 'wait' || command === 'block') {
133
- const [name, ...message] = args;
134
- update(command, (state) => {
135
- const current = stage(state, name);
136
- if (state.currentStage !== name) throw new Error(`cannot mark ${name}; current stage is ${state.currentStage}`);
137
- current.status = command === 'wait' ? 'waiting_user' : 'blocked';
138
- current.message = message.join(' ').trim();
139
- state.status = current.status;
140
- record(state, command, { stage: name, message: current.message });
141
- });
142
- } else if (command === 'resume') {
143
- update(command, (state) => {
144
- if (!['waiting_user', 'blocked'].includes(state.status)) throw new Error(`cannot resume while run is ${state.status}`);
145
- const current = stage(state, state.currentStage);
146
- current.status = 'active';
147
- delete current.message;
148
- state.status = 'running';
149
- record(state, 'resumed', { stage: current.name });
150
- });
151
- } else {
152
- die('usage: codex-run-state.mjs <init|status|begin|complete|finish|wait|block|resume> <workdir> ...');
153
- }
154
- } catch (error) {
155
- die(error.message);
156
- }
@@ -1,28 +0,0 @@
1
- # Codex runner
2
-
3
- Run this workflow from the project root with a durable checkpoint. Do not reconstruct a stopped planning run from chat history.
4
-
5
- ```bash
6
- node <this skill folder>/scripts/codex-run-state.mjs status docs/levi/<slug>
7
- node <this skill folder>/scripts/codex-run-state.mjs init docs/levi/<slug> brainstorming <slug> frame explore decide finalize plan review verify
8
- ```
9
-
10
- ```bash
11
- node <this skill folder>/scripts/codex-run-state.mjs begin docs/levi/<slug> <stage>
12
- node <this skill folder>/scripts/codex-run-state.mjs complete docs/levi/<slug> <stage> <artifact>...
13
- node <this skill folder>/scripts/codex-run-state.mjs wait docs/levi/<slug> <stage> "<questions>"
14
- node <this skill folder>/scripts/codex-run-state.mjs block docs/levi/<slug> <stage> "<blocker>"
15
- node <this skill folder>/scripts/codex-run-state.mjs resume docs/levi/<slug>
16
- ```
17
-
18
- Create the state after intake has derived the slug. On every new or resumed turn, read `status` first. Call `begin` for the current stage and `complete` only when its required artifact exists. Use `wait` for the single consolidated user-question round, `block` for a dependency outside the project, and `resume` once resolved. Completed stages are never repeated.
19
-
20
- - `frame`: find the optional read-only spec and have `levi-pm` write `brief.md` when no spec exists.
21
- - `explore`: `levi-teamlead` writes `architecture.md` from the basis.
22
- - `decide`: collect the PM/teamlead questions and the overwrite choice. Mark this stage `wait` before asking the user; after the answer, `resume` and complete it. Do not ask later unless blocked.
23
- - `finalize`: dispatch the PM and teamlead with the confirmed choices; when the problem holds several features, the PM writes `phases.md` first and the teamlead plans from it. Complete only when `tasks.md` exists (and `phases.md`, for several features) and, when no spec was available, `brief.md` has been updated.
24
- - `plan`: `levi-pm` writes `docs/brainstorming/<slug>.md`; if it finds a coverage gap, return only the missing tasks to the teamlead and keep this stage active.
25
- - `review`: when the plan has more than ten tasks, run the independent teamlead then PM review exactly once. Complete with the final plan; otherwise complete the skipped stage without an artifact.
26
- - `verify`: check totals and agents in the final plan, then complete with that plan. Only after this stage is complete may cleanup remove the checkpoint and scratch files.
27
-
28
- Use the named Levi role agents; the coordinator alone changes `run.json`. The final plan is the only deliverable after cleanup.
@@ -1,5 +0,0 @@
1
- # Codex runner
2
-
3
- This is the one Codex usecase that deliberately has no `run.json`: every dispatch is read-only and creates no project artifacts. Resolve the target and pull-request access checks first, size the change, then dispatch the installed named teamlead agent: once with the exact review prompt in `SKILL.md` for 100 or fewer reviewable files, or as `large-changes.md` says (a split, the slice reviews at the same time, then a merge) for more.
4
-
5
- If the turn is interrupted before the review is returned, rerun the same read-only target check, sizing and dispatches. Do not write a checkpoint, comment on the pull request, or modify the working tree. Once the review is returned, relay it unchanged.