levi-gear 0.4.0 → 0.6.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/README.md +31 -35
  2. package/docs/README.md +39 -0
  3. package/docs/authoring-usecases.md +123 -0
  4. package/docs/cli.md +99 -0
  5. package/docs/codex.md +23 -0
  6. package/docs/configuration.md +81 -0
  7. package/docs/contributing.md +46 -0
  8. package/docs/customization.md +45 -0
  9. package/docs/installation.md +82 -0
  10. package/docs/introduction.md +49 -0
  11. package/docs/team.md +143 -0
  12. package/docs/troubleshooting.md +63 -0
  13. package/docs/unattended-runs.md +49 -0
  14. package/docs/updating.md +109 -0
  15. package/docs/usage.md +62 -0
  16. package/docs/usecases.md +460 -0
  17. package/package.json +4 -3
  18. package/src/cli.js +3 -3
  19. package/src/commands/init.js +20 -25
  20. package/src/commands/list.js +3 -5
  21. package/src/commands/status.js +1 -1
  22. package/src/commands/update.js +4 -4
  23. package/src/lib/agents.js +1 -1
  24. package/src/lib/desired-state.js +62 -31
  25. package/src/lib/sync.js +3 -3
  26. package/src/lib/tools.js +10 -81
  27. package/src/runtime/codex-checkpoint.mjs +48 -0
  28. package/src/runtime/quota-check.mjs +21 -142
  29. package/usecases/_run-rules.md +13 -20
  30. package/usecases/brainstorming/SKILL.md +0 -4
  31. package/usecases/code-review/SKILL.md +0 -4
  32. package/usecases/create-feature/SKILL.md +3 -4
  33. package/usecases/create-feature/scripts/lock-tests.mjs +21 -8
  34. package/usecases/design/SKILL.md +0 -4
  35. package/usecases/fix-bug/SKILL.md +3 -4
  36. package/usecases/generate-test-scenarios/SKILL.md +0 -5
  37. package/usecases/spec-writing/SKILL.md +0 -4
  38. package/src/runtime/codex-run-state.mjs +0 -156
  39. package/usecases/brainstorming/references/codex-runner.md +0 -28
  40. package/usecases/code-review/references/codex-runner.md +0 -5
  41. package/usecases/create-feature/references/codex-runner.md +0 -57
  42. package/usecases/design/references/codex-runner.md +0 -27
  43. package/usecases/fix-bug/references/codex-runner.md +0 -32
  44. package/usecases/generate-test-scenarios/references/codex-runner.md +0 -32
  45. package/usecases/spec-writing/references/codex-runner.md +0 -25
@@ -1,14 +1,14 @@
1
1
  const fs = require('fs');
2
2
  const path = require('path');
3
3
  const { ROUTER_NAME, skillName } = require('./usecases');
4
- const { CODEX_SKILL_DIR, CODEX_POLICY, skillDirs, skillDirFor, AGENT_TARGETS } = require('./tools');
4
+ const { SKILL_DIR, AGENT_DIR, renderAgent } = require('./tools');
5
5
  const { joinSections } = require('./agents');
6
6
  const { withRoleSkills } = require('./role-skills');
7
7
  const { setField } = require('./frontmatter');
8
8
  const { renderRouter } = require('./router');
9
9
 
10
- const CODEX_RUN_STATE = path.join(__dirname, '..', 'runtime', 'codex-run-state.mjs');
11
10
  const QUOTA_CHECK = path.join(__dirname, '..', 'runtime', 'quota-check.mjs');
11
+ const CODEX_CHECKPOINT = path.join(__dirname, '..', 'runtime', 'codex-checkpoint.mjs');
12
12
 
13
13
  // Group keys say which part of the kit a file belongs to; they decide where its hash is
14
14
  // recorded in .levi.json.
@@ -28,41 +28,27 @@ function put(out, rel, content, group) {
28
28
  out.set(rel, { content: Buffer.from(content), group });
29
29
  }
30
30
 
31
- // Every levi skill runs only when the user invokes it: Claude Code and Copilot read the
32
- // frontmatter flag, Codex reads agents/openai.yaml (only written where Codex looks).
33
- function addSkill(out, usecase, dir, runRules) {
34
- const root = path.posix.join(dir, skillName(usecase.id));
31
+ // Every levi skill runs only when the user invokes it, which the frontmatter flag enforces.
32
+ function addSkill(out, usecase, runRules) {
33
+ const root = path.posix.join(SKILL_DIR, skillName(usecase.id));
35
34
  for (const rel of walk(usecase.dir, true)) {
36
35
  let content = fs.readFileSync(path.join(usecase.dir, rel));
37
36
  if (rel === 'SKILL.md') content = joinSections(setField(content.toString('utf8'), 'disable-model-invocation', 'true'), runRules);
38
37
  put(out, path.posix.join(root, rel), content, usecaseGroup(usecase.id));
39
38
  }
40
- // The quota guard in the run rules calls this helper, in every tool.
39
+ // The quota guard in the run rules calls this helper.
41
40
  put(out, path.posix.join(root, 'scripts/quota-check.mjs'), fs.readFileSync(QUOTA_CHECK), usecaseGroup(usecase.id));
42
- if (dir === CODEX_SKILL_DIR) {
43
- put(out, path.posix.join(root, 'agents/openai.yaml'), CODEX_POLICY, usecaseGroup(usecase.id));
44
- // The source skills remain portable Markdown. Codex gets this small durable-state
45
- // helper so its dedicated runners can resume an interrupted run from files.
46
- put(out, path.posix.join(root, 'scripts/codex-run-state.mjs'), fs.readFileSync(CODEX_RUN_STATE), usecaseGroup(usecase.id));
47
- }
48
41
  }
49
42
 
50
- // `prepare` adapts an agent to one tool before it is rendered (team agents get their role skills).
51
- function addAgents(out, agents, tools, group, prepare = (agent) => agent) {
52
- for (const tool of tools) {
53
- const target = AGENT_TARGETS[tool];
54
- for (const agent of agents) put(out, path.posix.join(target.dir, agent.name + target.ext), target.render(prepare(agent, tool)), group);
55
- }
43
+ // `prepare` adapts an agent before it is rendered (team agents get their role skills).
44
+ function addAgents(out, agents, group, prepare = (agent) => agent) {
45
+ for (const agent of agents) put(out, path.posix.join(AGENT_DIR, `${agent.name}.md`), renderAgent(prepare(agent)), group);
56
46
  }
57
47
 
58
48
  // The `levi` entry point is generated from whatever usecases are installed.
59
- function addRouter(out, usecases, team, tools) {
49
+ function addRouter(out, usecases, team) {
60
50
  if (!usecases.length) return;
61
- for (const dir of skillDirs(tools)) {
62
- const root = path.posix.join(dir, ROUTER_NAME);
63
- put(out, path.posix.join(root, 'SKILL.md'), renderRouter(dir, usecases, team), 'router');
64
- if (dir === CODEX_SKILL_DIR) put(out, path.posix.join(root, 'agents/openai.yaml'), CODEX_POLICY, 'router');
65
- }
51
+ put(out, path.posix.join(SKILL_DIR, ROUTER_NAME, 'SKILL.md'), renderRouter(SKILL_DIR, usecases, team), 'router');
66
52
  }
67
53
 
68
54
  // `ids` plus every usecase they require, directly or not, each once.
@@ -77,10 +63,10 @@ function withRequired(byId, ids) {
77
63
  return all;
78
64
  }
79
65
 
80
- // The files a clean install of `ids` (and what they require) for `tools` would contain: Map of
66
+ // The files a clean install of `ids` (and what they require) would contain: Map of
81
67
  // project-relative path to { content, group }. Nothing is written here. Usecases that are a team
82
68
  // role's skill are always installed, since the team always is and its agents rely on them.
83
- function build(kit, ids, tools) {
69
+ function build(kit, ids, targets = ['claude']) {
84
70
  const byId = new Map(kit.usecases.map((u) => [u.id, u]));
85
71
  const out = new Map();
86
72
  const missing = [];
@@ -93,12 +79,57 @@ function build(kit, ids, tools) {
93
79
  }
94
80
  const usecase = byId.get(id);
95
81
  present.push(usecase);
96
- for (const dir of skillDirs(tools)) addSkill(out, usecase, dir, kit.runRules);
97
- addAgents(out, usecase.agents, tools, usecaseGroup(id));
82
+ if (targets.includes('claude')) {
83
+ addSkill(out, usecase, kit.runRules);
84
+ addAgents(out, usecase.agents, usecaseGroup(id));
85
+ }
86
+ if (targets.includes('codex')) {
87
+ const root = `.agents/skills/${skillName(id)}`;
88
+ for (const rel of walk(usecase.dir, true)) {
89
+ if (rel === 'workflow.js') continue; // Claude's Workflow runtime is not used by Codex.
90
+ let content = fs.readFileSync(path.join(usecase.dir, rel));
91
+ if (rel === 'SKILL.md') {
92
+ let skill = content.toString('utf8');
93
+ skill = skill.replace('On Claude Code the implementation runs as a Workflow of independent subagents. ', '');
94
+ skill = skill.replace(/ - \*With a Workflow tool \(Claude Code\):\*[\s\S]*? - \*Without a Workflow tool:\* /, ' - ');
95
+ skill = skill.replace(/Continue in the same session with `resumeFromRunId` and a higher `maxRounds`\./g, 'Continue from the saved work folder and increase the round limit.');
96
+ skill = skill.replace(/Claude Code runs `workflow\.js`\./g, 'Run the documented steps with fresh Codex subagents.');
97
+ skill = skill.replace(/The steps (?:the Workflow|`workflow\.js`) runs, and the ones you run when there is no Workflow tool\./g, 'Run the following steps in order.');
98
+ const rules = kit.runRules.split('### Quota guard')[0];
99
+ content = joinSections(skill, rules, `### Codex checkpoint and recovery\n\nBefore doing work, create a unique run folder docs/levi-runs/<slug>-<unique-id>/ and use scripts/codex-checkpoint.mjs from this skill directory. Prepare a JSON file with {"usecase":"${id}","request":"<user request>"}, then run \`node <skill-dir>/scripts/codex-checkpoint.mjs init <run-folder>/checkpoint.json < <json-file>\`. Do not include secrets. Record the checkpoint path for the user.\n\nBefore starting each numbered stage, and after each stage or build/review round, prepare JSON with status (running, blocked, waiting_user, or complete), stage, summary, and next (the exact next action, including artifact and lock paths), then run \`node <skill-dir>/scripts/codex-checkpoint.mjs save <run-folder>/checkpoint.json < <json-file>\`. Never mark a stage complete before validating its artifacts. Preserve work, test locks and checkpoint when interrupted, blocked or waiting. On an explicit request to resume, read the checkpoint, the work folder and current git state, verify the locked tests before making changes, and continue at the recorded action without repeating completed stages. If the state is ambiguous, report it and ask rather than guessing. Only mark complete after all gates and reports succeed. Remove temporary JSON input files; keep the checkpoint. If required subagents or tools are unavailable, record blocked and report it. Automatic quota resume is not available through this skill; report this limitation.`);
100
+ }
101
+ if (rel === 'SKILL.md') content = content.replace('status (running, blocked, waiting_user, or complete)', 'status (running, interrupted, blocked, waiting_user, or complete)').replace('Automatic quota resume is not available through this skill; report this limitation.', '');
102
+ if (rel === 'SKILL.md' && id === 'code-review') {
103
+ content = content.replace('docs/levi-runs/<slug>-<unique-id>/', 'a unique directory in the operating system temporary directory, outside the project');
104
+ }
105
+ if (rel === 'SKILL.md') content += '\nA running stage is not evidence that its subagent completed. On resume, first establish that the previous coordinator is no longer active. If an earlier run stopped with status running, record status interrupted; report that the cause is unknown unless there is direct evidence. Check whether every required artifact exists and was validated. If not, rerun that stage with the appropriate fresh subagent before advancing, while preserving existing user files and test locks. Never infer success from a scheduled next action. Before dispatching a subagent, checkpoint that the stage is in progress and name the subagent and its expected artifacts; only checkpoint the next stage after it finishes and its results are validated. While waiting, check the agent status with the available collaboration tools, distinguish still running from failed, and report meaningful progress. If an agent fails or cannot complete, save the error and the recovery action as blocked; do not assume success. Never start a second coordinator while the original is still active.\n';
106
+ if (rel === 'SKILL.md') content += '\nWhen cleaning up workflow-owned binary files such as XLSX snapshots, use a filesystem command appropriate for the platform; text patch tools cannot delete binary files. Delete only paths the workflow owns and only after the relevant gates have passed.\n';
107
+ put(out, `${root}/${rel}`, content, usecaseGroup(id));
108
+ }
109
+ put(out, `${root}/agents/openai.yaml`, 'policy:\n allow_implicit_invocation: false\n', usecaseGroup(id));
110
+ put(out, `${root}/scripts/codex-checkpoint.mjs`, fs.readFileSync(CODEX_CHECKPOINT), usecaseGroup(id));
111
+ for (const agent of usecase.agents) put(out, `.codex/agents/${agent.name}.toml`, codexAgent(agent), usecaseGroup(id));
112
+ }
113
+ }
114
+ if (targets.includes('claude')) {
115
+ addRouter(out, present, kit.team);
116
+ addAgents(out, kit.team, 'team', (agent) => withRoleSkills(agent, present, SKILL_DIR));
117
+ }
118
+ if (targets.includes('codex')) {
119
+ if (present.length) {
120
+ const router = renderRouter('.agents/skills', present, kit.team)
121
+ .replaceAll('/levi-<usecase>', '$levi-<usecase>')
122
+ .replace('## Steps\n', `## Resume\n\nWhen the user asks to resume a levi run, locate its checkpoint under docs/levi-runs/ or use the checkpoint path supplied by the user. If several incomplete runs match, ask which one; do not guess. Read the checkpoint and select the usecase named in it. Read that skill and follow its Codex checkpoint and recovery instructions. Do not start a new run or perform intake again. If the checkpoint is complete, say so and stop. Code-review checkpoints are outside the project; require the user to supply their path.\n\n## Steps\n`);
123
+ put(out, '.agents/skills/levi/SKILL.md', router, 'router');
124
+ put(out, '.agents/skills/levi/agents/openai.yaml', 'policy:\n allow_implicit_invocation: false\n', 'router');
125
+ }
126
+ for (const agent of kit.team) put(out, `.codex/agents/${agent.name}.toml`, codexAgent(withRoleSkills(agent, present, '.agents/skills')), 'team');
98
127
  }
99
- addRouter(out, present, kit.team, tools);
100
- addAgents(out, kit.team, tools, 'team', (agent, tool) => withRoleSkills(agent, present, skillDirFor(tool, tools)));
101
128
  return { files: out, missing, ids: present.map((u) => u.id) };
102
129
  }
103
130
 
131
+ function codexAgent(agent) {
132
+ return `name = ${JSON.stringify(agent.name)}\ndescription = ${JSON.stringify(`${agent.description} Only use when a levi workflow delegates to this agent.`)}\ndeveloper_instructions = ${JSON.stringify(agent.body.trim())}\n`;
133
+ }
134
+
104
135
  module.exports = { build, usecaseGroup };
package/src/lib/sync.js CHANGED
@@ -98,10 +98,10 @@ function recordFiles(actions, ids) {
98
98
  return config;
99
99
  }
100
100
 
101
- // Brings the project in line with the kit for `ids` and `tools`, touching only files the user
101
+ // Brings the project in line with the kit for `ids`, touching only files the user
102
102
  // has not changed. `previous` is the stored config. With dryRun nothing is written.
103
- function sync(projectDir, ids, tools, previous, { force = false, dryRun = false } = {}) {
104
- const desired = build(loadKit(), ids, tools);
103
+ function sync(projectDir, ids, previous, { force = false, dryRun = false } = {}) {
104
+ const desired = build(loadKit(), ids, previous.targets || ['claude']);
105
105
  const actions = plan(projectDir, desired, trackedFiles(previous), force);
106
106
  if (!dryRun) apply(projectDir, actions);
107
107
  return { actions, missing: desired.missing, ...recordFiles(actions, desired.ids) };
package/src/lib/tools.js CHANGED
@@ -1,30 +1,6 @@
1
- const TOOLS = ['claude', 'codex', 'copilot'];
2
-
3
- // `invoke` is the character that starts an explicit skill call in each tool.
4
- const TOOL_INFO = {
5
- claude: { label: 'Claude Code', invoke: '/' },
6
- codex: { label: 'Codex', invoke: '$' },
7
- copilot: { label: 'Copilot', invoke: '/' },
8
- };
9
-
10
- // Claude Code reads only .claude/skills; Codex reads .agents/skills; Copilot reads both
11
- // of those, so it only needs its own copy when Claude is not selected.
12
- function skillDirs(tools) {
13
- const dirs = new Set();
14
- if (tools.includes('claude')) dirs.add('.claude/skills');
15
- if (tools.includes('codex')) dirs.add('.agents/skills');
16
- if (tools.includes('copilot') && !tools.includes('claude')) dirs.add('.agents/skills');
17
- return [...dirs];
18
- }
19
-
20
- // The skill folder an agent of `tool` reads: Copilot uses .claude/skills when Claude is installed.
21
- function skillDirFor(tool, tools) {
22
- return tool === 'claude' || (tool === 'copilot' && tools.includes('claude')) ? '.claude/skills' : '.agents/skills';
23
- }
24
-
25
- // Codex ignores SKILL.md frontmatter flags and reads its invocation policy from this file.
26
- const CODEX_SKILL_DIR = '.agents/skills';
27
- const CODEX_POLICY = 'policy:\n allow_implicit_invocation: false\n';
1
+ // Claude Code's installation paths and agent renderer. Codex artifacts are built separately.
2
+ const SKILL_DIR = '.claude/skills';
3
+ const AGENT_DIR = '.claude/agents';
28
4
 
29
5
  // Subagents are picked from their description, so scope them to levi to keep the agent
30
6
  // from reaching for them on requests that did not go through levi.
@@ -34,65 +10,18 @@ function agentDescription(agent) {
34
10
  return `${text} Used only when ${by} delegates to it; never select it for other requests.`;
35
11
  }
36
12
 
37
- // Tool-neutral capabilities and model tiers (see agents.js), mapped per tool. Omitting `tools`
38
- // keeps the tool's defaults, including MCP servers, which an explicit list would cut off.
13
+ // Tool-neutral capabilities and model tiers (see agents.js), mapped to Claude Code. Omitting
14
+ // `tools` keeps the defaults, including MCP servers, which an explicit list would cut off.
39
15
  const CLAUDE_TOOLS = { read: ['Read', 'Grep', 'Glob'], edit: ['Edit', 'Write'], execute: ['Bash'], web: ['WebFetch', 'WebSearch'] };
40
- const COPILOT_TOOLS = { read: ['read', 'search'], edit: ['edit'], execute: ['execute'], web: ['web'] };
41
16
  const CLAUDE_MODELS = { strong: 'opus', standard: 'sonnet', fast: 'haiku' };
42
- const CODEX_EFFORT = { strong: 'high', standard: 'medium', fast: 'low' };
43
-
44
- function mapTools(tools, table) {
45
- return tools.flatMap((t) => table[t]);
46
- }
47
-
48
- function tomlString(text) {
49
- return '"""\n' + text.replace(/\\/g, '\\\\').replace(/"""/g, '\\"""').trim() + '\n"""';
50
- }
51
-
52
- function renderMarkdown(agent, extra) {
53
- return ['---', `name: ${agent.name}`, `description: ${JSON.stringify(agentDescription(agent))}`, ...extra, '---', '', agent.body.trim(), ''].join(
54
- '\n'
55
- );
56
- }
57
17
 
58
- function renderClaude(agent) {
18
+ function renderAgent(agent) {
59
19
  const extra = [];
60
- if (agent.tools) extra.push(`tools: ${mapTools(agent.tools, CLAUDE_TOOLS).join(', ')}`);
20
+ if (agent.tools) extra.push(`tools: ${agent.tools.flatMap((t) => CLAUDE_TOOLS[t]).join(', ')}`);
61
21
  if (agent.model) extra.push(`model: ${CLAUDE_MODELS[agent.model]}`);
62
- return renderMarkdown(agent, extra);
63
- }
64
-
65
- // Copilot model names change often, so agents keep the user's selected model.
66
- function renderCopilot(agent) {
67
- const extra = agent.tools ? [`tools: ${JSON.stringify(mapTools(agent.tools, COPILOT_TOOLS))}`] : [];
68
- return renderMarkdown(agent, extra);
22
+ return ['---', `name: ${agent.name}`, `description: ${JSON.stringify(agentDescription(agent))}`, ...extra, '---', '', agent.body.trim(), ''].join('\n');
69
23
  }
70
24
 
71
- // Codex has no per-tool list: an agent that can neither edit nor execute runs read-only.
72
- function renderToml(agent) {
73
- const lines = [`name = ${JSON.stringify(agent.name)}`, `description = ${JSON.stringify(agentDescription(agent))}`];
74
- if (agent.model) lines.push(`model_reasoning_effort = "${CODEX_EFFORT[agent.model]}"`);
75
- if (agent.tools) {
76
- const writes = agent.tools.includes('edit') || agent.tools.includes('execute');
77
- lines.push(`sandbox_mode = "${writes ? 'workspace-write' : 'read-only'}"`);
78
- }
79
- lines.push(`developer_instructions = ${tomlString(agent.body)}`, '');
80
- return lines.join('\n');
81
- }
82
-
83
- const AGENT_TARGETS = {
84
- claude: { dir: '.claude/agents', ext: '.md', render: renderClaude },
85
- codex: { dir: '.codex/agents', ext: '.toml', render: renderToml },
86
- copilot: { dir: '.github/agents', ext: '.agent.md', render: renderCopilot },
87
- };
88
-
89
- function invocationHelp(tools) {
90
- return tools
91
- .map((tool) => {
92
- const { label, invoke } = TOOL_INFO[tool];
93
- return ` ${label.padEnd(11)} ${invoke}levi <request> ${invoke}levi-<usecase> <request>`;
94
- })
95
- .join('\n');
96
- }
25
+ const INVOCATION_HELP = ' /levi <request> /levi-<usecase> <request>';
97
26
 
98
- module.exports = { TOOLS, CODEX_SKILL_DIR, CODEX_POLICY, skillDirs, skillDirFor, AGENT_TARGETS, invocationHelp };
27
+ module.exports = { SKILL_DIR, AGENT_DIR, renderAgent, INVOCATION_HELP };
@@ -0,0 +1,48 @@
1
+ #!/usr/bin/env node
2
+ // Small durable record for a Codex workflow. It records progress; it does not run agents.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+
6
+ const [command, file] = process.argv.slice(2);
7
+ function fail(message) { throw new Error(message); }
8
+ function read() {
9
+ const state = JSON.parse(fs.readFileSync(file, 'utf8'));
10
+ if (state.version !== 1 || typeof state.usecase !== 'string' || !Array.isArray(state.history)) fail('invalid checkpoint');
11
+ return state;
12
+ }
13
+ function input() { return JSON.parse(fs.readFileSync(0, 'utf8')); }
14
+ function write(state, exclusive = false) {
15
+ fs.mkdirSync(path.dirname(file), { recursive: true });
16
+ if (exclusive) return fs.writeFileSync(file, JSON.stringify(state, null, 2) + '\n', { flag: 'wx' });
17
+ const temp = `${file}.${process.pid}.tmp`;
18
+ fs.writeFileSync(temp, JSON.stringify(state, null, 2) + '\n', { flag: 'wx' });
19
+ try { fs.renameSync(temp, file); } finally { if (fs.existsSync(temp)) fs.unlinkSync(temp); }
20
+ }
21
+ try {
22
+ if (!file) fail('usage: codex-checkpoint.mjs init|save|status <file>; JSON on stdin for init and save');
23
+ if (command === 'init') {
24
+ const data = input();
25
+ if (typeof data.usecase !== 'string' || !data.usecase || typeof data.request !== 'string') fail('init requires usecase and request');
26
+ const state = { version: 1, usecase: data.usecase, request: data.request, status: 'running', stage: 'intake', history: [], updatedAt: new Date().toISOString() };
27
+ write(state, true);
28
+ console.log(JSON.stringify(state));
29
+ } else if (command === 'save') {
30
+ const data = input();
31
+ if (!['running', 'interrupted', 'blocked', 'waiting_user', 'complete'].includes(data.status) || typeof data.stage !== 'string' || typeof data.next !== 'string' || typeof data.summary !== 'string') fail('save requires status, stage, summary and next');
32
+ const lock = `${file}.lock`;
33
+ fs.mkdirSync(lock); // Fail closed on concurrent writes, including abandoned locks.
34
+ try {
35
+ const state = read();
36
+ if (state.status === 'complete') fail('a completed run cannot be changed');
37
+ state.status = data.status;
38
+ state.stage = data.stage;
39
+ state.next = data.next;
40
+ state.summary = data.summary;
41
+ state.updatedAt = new Date().toISOString();
42
+ state.history.push({ status: data.status, stage: data.stage, summary: data.summary, next: data.next, at: state.updatedAt });
43
+ write(state);
44
+ console.log(JSON.stringify(state));
45
+ } finally { fs.rmdirSync(lock); }
46
+ } else if (command === 'status') console.log(JSON.stringify(read(), null, 2));
47
+ else fail('unknown command');
48
+ } catch (error) { console.error(error.message); process.exitCode = 2; }
@@ -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: