levi-gear 0.2.0 → 0.4.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.
package/README.md CHANGED
@@ -1,8 +1,18 @@
1
1
  # levi-gear
2
2
 
3
- An agentic kit for AI agents. Each **usecase** is a self-contained workflow (a skill, optionally with subagents) that gets installed for Claude Code, Codex and GitHub Copilot, together with a shared **team** of role agents that usecases can delegate to.
3
+ **Gather a whole software team into your terminal.** levi is an agentic kit that breathes a complete crew into your AI coding tools: a product manager, a teamlead, a developer, a designer and a QA engineer, each with a clear craft and a clear territory. Write a workflow once, and it comes alive in Claude Code, Codex and GitHub Copilot alike.
4
4
 
5
- Requires Node.js 18 or newer. There are no runtime dependencies.
5
+ ## Why levi
6
+
7
+ - **One kit, three tools.** A usecase is written once and installed as native skills and subagents for Claude Code, Codex and GitHub Copilot.
8
+ - **A team, not a lone assistant.** Five role agents, each owning only its own files, pass work to one another through plain files in a shared work folder, so every hand-off leaves a trail you can read.
9
+ - **Craft from idea to release.** Seven ready usecases carry work from a vague idea to a verified result: brainstorming, spec writing, design, test-first feature building, bug fixing, code review and test scenarios.
10
+ - **Tests that cannot be bent.** In `create-feature` and `fix-bug` the tests come first and are locked, and QA writes its test cases from the spec alone, so the code is fixed until the proof passes.
11
+ - **Ask once, then run alone.** All questions are gathered up front; afterwards the run proceeds without you, picks cheap-to-change options on its own and lays them out in a closing report so you can change any of them.
12
+ - **A run that outlasts the quota.** When the 5-hour usage window runs dry, the run resumes itself once it refills, with its context kept, instead of stopping half-way.
13
+ - **Quiet until called.** levi never acts on its own; a prompt without the levi command is handled by your tool as usual. `/levi <request>` routes a request, in any language, to the best matching usecase.
14
+ - **Your files stay yours.** Everything installed is a plain file in your repository. `levi update` refreshes only what you did not touch and never overwrites your edits.
15
+ - **Featherlight.** No runtime dependencies; Node.js 18 or newer is all it asks for.
6
16
 
7
17
  **Full documentation: [docs/](docs/README.md)**: installation, usage, updating, the CLI reference and more.
8
18
 
@@ -55,7 +65,7 @@ Each agent does only its own role's work and writes only the files it owns; work
55
65
 
56
66
  Some usecases are also a role's skill: `spec-writing` for the PM, `design` for the designer, `code-review` for the teamlead and `generate-test-scenarios` for QA. They are installed with every install, and the agent follows that skill's guide whenever it gets that kind of task, from any usecase. A usecase declares this with `skill-for`, `skill-when` and `skill-guide` in its `SKILL.md`.
57
67
 
58
- The usecase's skill or workflow runs the team: it calls each member in turn. The PM only decides who owns each task and records it; the workflow follows that. Members hand work to each other through files in a work folder (`docs/levi/<slug>/` by default): `spec.md`, `status.md`, `docs/designs/`, `architecture.md`, `tasks.md`, `review.md`, `test-plan.md`, `test-report.md`. The shared rules live in `agents/_team-protocol.md`, which is appended to every team agent.
68
+ The usecase's skill or workflow runs the team: it calls each member in turn. The PM only decides who owns each task and records it; the workflow follows that. Members hand work to each other through files in a work folder (`docs/levi/<slug>/` by default): `spec.md`, `status.md`, `docs/designs/`, `architecture.md`, `tasks.md`, `review.md`, `test-plan.md`, `test-report.md`. On Codex, every installed skill also gets a small `scripts/codex-run-state.mjs` helper; long runs record `run.json` in that work folder so they can resume after an interruption. The shared rules live in `agents/_team-protocol.md`, which is appended to every team agent. Every usecase also follows the run rules in `usecases/_run-rules.md`, appended to each installed `SKILL.md`: all questions are asked up front, cheap-to-change choices are picked and reported at the end, and a run that hits the 5-hour quota resumes itself with its context kept ([docs/unattended-runs.md](docs/unattended-runs.md)).
59
69
 
60
70
  ## Update
61
71
 
@@ -20,13 +20,15 @@ You are one member of the levi team: `levi-pm`, `levi-teamlead`, `levi-developer
20
20
  | `review.md` | Teamlead: code review findings |
21
21
  | Database schema, migrations, CI/CD and deployment config | Teamlead |
22
22
  | Application code, unit and integration tests, technical docs of the code | Developer |
23
+ | `choices/<role>-<topic>.md` | Whoever made the choice: one small file per choice (see "Pick, do not ask") |
23
24
  | `test-plan.md` | QA: test plan and test cases |
24
25
  | `docs/tests/` | QA: numbered test scenarios and test cases, with their PASS or FAIL results once run |
25
26
  | `test-report.md` | QA: results, bugs, sign-off |
26
27
  | E2E and acceptance tests | QA |
27
28
 
28
29
  A file the table does not list belongs to the role whose responsibilities cover it. If you cannot tell which, do not write it: hand it off.
29
- - **Never ask the user directly.** You run without the user in the loop. When information is missing, finish what you can and return the questions.
30
+ - **Never ask the user directly.** You run without the user in the loop. When information is missing, finish what you can and return the questions. Return every question you can foresee in your first report, all together: the user is asked once, so a question you hold back is answered late or never.
31
+ - **Pick, do not ask.** When your work yields several acceptable options and a wrong pick is cheap to undo (logo variants, a layout, a palette, a name, a wording), do not turn it into a question. Take the best one, keep the others where the user can still reach them (files in an `alternatives/` folder next to your deliverable), and write `choices/<your-role>-<topic>.md` in the work folder: what was chosen between, your pick, why, the alternatives and how to switch. Questions are for facts only the user knows, scope and acceptance criteria, and anything hard to undo.
30
32
  - **Language.** Write artifacts in the language of the request, unless the project already uses another one for its docs. Code, identifiers and commit messages stay in English.
31
33
  - **Do not guess.** Mark assumptions as assumptions. Do not invent requirements, data, or results you did not observe.
32
34
 
package/package.json CHANGED
@@ -1,10 +1,13 @@
1
1
  {
2
2
  "name": "levi-gear",
3
- "version": "0.2.0",
4
- "description": "An agentic kit: Agent Skills for Claude Code, Codex and Copilot, installable via npm",
3
+ "version": "0.4.0",
4
+ "description": "Summon a whole software team (PM, teamlead, developer, designer, QA) into Claude Code, Codex and Copilot: test-first workflows that run unattended, outlast the quota and never trample your files",
5
5
  "bin": {
6
6
  "levi": "./bin/levi.js"
7
7
  },
8
+ "scripts": {
9
+ "test": "node --test test/codex-runtime.test.mjs test/quota-check.test.mjs"
10
+ },
8
11
  "files": [
9
12
  "agents",
10
13
  "bin",
@@ -2,10 +2,14 @@ const fs = require('fs');
2
2
  const path = require('path');
3
3
  const { ROUTER_NAME, skillName } = require('./usecases');
4
4
  const { CODEX_SKILL_DIR, CODEX_POLICY, skillDirs, skillDirFor, AGENT_TARGETS } = require('./tools');
5
+ const { joinSections } = require('./agents');
5
6
  const { withRoleSkills } = require('./role-skills');
6
7
  const { setField } = require('./frontmatter');
7
8
  const { renderRouter } = require('./router');
8
9
 
10
+ const CODEX_RUN_STATE = path.join(__dirname, '..', 'runtime', 'codex-run-state.mjs');
11
+ const QUOTA_CHECK = path.join(__dirname, '..', 'runtime', 'quota-check.mjs');
12
+
9
13
  // Group keys say which part of the kit a file belongs to; they decide where its hash is
10
14
  // recorded in .levi.json.
11
15
  const usecaseGroup = (id) => `usecase:${id}`;
@@ -26,14 +30,21 @@ function put(out, rel, content, group) {
26
30
 
27
31
  // Every levi skill runs only when the user invokes it: Claude Code and Copilot read the
28
32
  // frontmatter flag, Codex reads agents/openai.yaml (only written where Codex looks).
29
- function addSkill(out, usecase, dir) {
33
+ function addSkill(out, usecase, dir, runRules) {
30
34
  const root = path.posix.join(dir, skillName(usecase.id));
31
35
  for (const rel of walk(usecase.dir, true)) {
32
36
  let content = fs.readFileSync(path.join(usecase.dir, rel));
33
- if (rel === 'SKILL.md') content = setField(content.toString('utf8'), 'disable-model-invocation', 'true');
37
+ if (rel === 'SKILL.md') content = joinSections(setField(content.toString('utf8'), 'disable-model-invocation', 'true'), runRules);
34
38
  put(out, path.posix.join(root, rel), content, usecaseGroup(usecase.id));
35
39
  }
36
- if (dir === CODEX_SKILL_DIR) put(out, path.posix.join(root, 'agents/openai.yaml'), CODEX_POLICY, usecaseGroup(usecase.id));
40
+ // The quota guard in the run rules calls this helper, in every tool.
41
+ 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
+ }
37
48
  }
38
49
 
39
50
  // `prepare` adapts an agent to one tool before it is rendered (team agents get their role skills).
@@ -82,7 +93,7 @@ function build(kit, ids, tools) {
82
93
  }
83
94
  const usecase = byId.get(id);
84
95
  present.push(usecase);
85
- for (const dir of skillDirs(tools)) addSkill(out, usecase, dir);
96
+ for (const dir of skillDirs(tools)) addSkill(out, usecase, dir, kit.runRules);
86
97
  addAgents(out, usecase.agents, tools, usecaseGroup(id));
87
98
  }
88
99
  addRouter(out, present, kit.team, tools);
@@ -5,6 +5,8 @@ const { PREFIX, readAgent, loadTeam } = require('./agents');
5
5
 
6
6
  const ROUTER_NAME = 'levi';
7
7
  const KIT_DIR = path.join(__dirname, '..', '..', 'usecases');
8
+ // Rules every usecase follows; appended to each installed SKILL.md. Not a usecase: it is a file, not a folder.
9
+ const RUN_RULES_FILE = path.join(KIT_DIR, '_run-rules.md');
8
10
 
9
11
  function skillName(id) {
10
12
  return PREFIX + id;
@@ -99,7 +101,8 @@ function loadKit() {
99
101
  checkNames(usecases, team);
100
102
  checkRequires(usecases);
101
103
  checkSkillRoles(usecases, team);
102
- return { usecases, team };
104
+ const runRules = fs.existsSync(RUN_RULES_FILE) ? fs.readFileSync(RUN_RULES_FILE, 'utf8').trim() : '';
105
+ return { usecases, team, runRules };
103
106
  }
104
107
 
105
108
  function listUsecases() {
@@ -0,0 +1,156 @@
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
+ }
@@ -0,0 +1,195 @@
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.
5
+ //
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
11
+
12
+ import fs from 'node:fs';
13
+ import os from 'node:os';
14
+ import path from 'node:path';
15
+ import { spawnSync } from 'node:child_process';
16
+ import { fileURLToPath } from 'node:url';
17
+
18
+ const THRESHOLD = 95;
19
+ const EVERY_HOURS = 2;
20
+ const FIVE_HOURS = 300;
21
+ 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
+
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');
27
+
28
+ function result(tool, fields) {
29
+ const threshold = fields.threshold;
30
+ const used = fields.usedPercent;
31
+ const known = typeof used === 'number';
32
+ return { tool, status: known ? 'ok' : 'unknown', ...fields, atThreshold: known && used >= threshold };
33
+ }
34
+
35
+ // A window whose reset time has passed holds no usage any more.
36
+ function window(used, resetsAtSeconds, now = Date.now()) {
37
+ if (typeof used !== 'number') return {};
38
+ const passed = typeof resetsAtSeconds === 'number' && resetsAtSeconds * 1000 <= now;
39
+ return { usedPercent: passed ? 0 : used, resetsAt: resetsAtSeconds ? new Date(resetsAtSeconds * 1000).toISOString() : null };
40
+ }
41
+
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)' });
45
+ 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}"` });
90
+ }
91
+
92
+ // Statusline hook for Claude Code: the only place it shows the usage is the JSON it pipes in.
93
+ function record(passthrough) {
94
+ const input = fs.readFileSync(0, 'utf8');
95
+ try {
96
+ 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');
98
+ if (!passthrough) process.stdout.write(`5h ${Math.round(five.used_percentage)}%`);
99
+ } catch {
100
+ if (!passthrough) process.stdout.write('5h ?');
101
+ }
102
+ if (passthrough) process.stdout.write(input);
103
+ }
104
+
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
+ function parseArgs(argv) {
165
+ const split = argv.indexOf('--');
166
+ const flags = split === -1 ? [] : argv.slice(split + 1);
167
+ 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);
173
+ }
174
+ return { options, flags };
175
+ }
176
+
177
+ function main() {
178
+ 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 };
182
+ 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));
188
+ }
189
+
190
+ try {
191
+ main();
192
+ } catch (error) {
193
+ console.error(error.message);
194
+ process.exitCode = 2;
195
+ }
@@ -0,0 +1,49 @@
1
+ ## Run rules
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.
4
+
5
+ ### Ask first, then run alone
6
+
7
+ 1. Start with a cheap discovery pass: read the request, the matching specs, plans and designs and the project, and call the agents that only frame or analyze. Do no expensive work (writing, coding, drawing, testing) before it is done.
8
+ 2. From that pass, build the whole list of questions: what is missing, unclear or contradictory; every candidate to confirm (which spec, plan or design to reuse); every irreversible or externally visible step (deleting, publishing, pushing, deploying, spending money).
9
+ 3. Ask them all in one round (several question calls back to back when the tool limits how many fit in one). Each has two to four options, the recommended one first. Say in the same message that the run continues on its own after the answers.
10
+ 4. Then do not ask again. A question that comes up later is parked: carry on with everything that does not depend on it, and give all parked questions together at the end, with the assumption used meanwhile. Stop early only when nothing is left to do without the answer.
11
+
12
+ Ask only about a fact only the user knows (business rules, data, credentials), scope or acceptance criteria, an irreversible or externally visible action, or a pick where a wrong guess wastes a large part of the work. Anything else is a choice.
13
+
14
+ ### Choices are picked, not asked
15
+
16
+ When the work yields several acceptable options and picking one can be undone cheaply (four logo variants, a layout, a palette, a name, a wording, equal libraries), do not wait for the user. Take the recommended option, or the best by your own judgment, and keep going.
17
+
18
+ - Record each choice in its own small file `docs/levi/<slug>/choices/<who>-<topic>.md` (one file per choice, so agents working in parallel never write the same file): what was chosen between, the pick, why, the alternatives and how to switch. Without a work folder, keep the list in your notes. Every agent may write there; agents record their own choices, and the usecase records the choices it makes itself.
19
+ - Keep the rejected options reachable: files go in an `alternatives/` folder next to the deliverable; anything else is described in the entry.
20
+ - Before cleaning up the work folder, read `choices/`. Close the final report with the section "Choices I made for you": each choice, the pick, the alternatives, how to change it, and that the user can change any of them. Do this even when the run ends early (blocked, stalled, parked questions).
21
+
22
+ ### Quota guard
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:
35
+ - *Status line:* the first line, `Status: interrupted | complete`, then the date, time and the usage reading (`usedPercent`, `resetsAt`).
36
+ - *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).
38
+ - *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
+ - *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
+ - *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).
42
+ - *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.
44
+ 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>`.