levi-gear 0.5.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.
@@ -8,6 +8,7 @@ const { setField } = require('./frontmatter');
8
8
  const { renderRouter } = require('./router');
9
9
 
10
10
  const QUOTA_CHECK = path.join(__dirname, '..', 'runtime', 'quota-check.mjs');
11
+ const CODEX_CHECKPOINT = path.join(__dirname, '..', 'runtime', 'codex-checkpoint.mjs');
11
12
 
12
13
  // Group keys say which part of the kit a file belongs to; they decide where its hash is
13
14
  // recorded in .levi.json.
@@ -65,7 +66,7 @@ function withRequired(byId, ids) {
65
66
  // The files a clean install of `ids` (and what they require) would contain: Map of
66
67
  // project-relative path to { content, group }. Nothing is written here. Usecases that are a team
67
68
  // role's skill are always installed, since the team always is and its agents rely on them.
68
- function build(kit, ids) {
69
+ function build(kit, ids, targets = ['claude']) {
69
70
  const byId = new Map(kit.usecases.map((u) => [u.id, u]));
70
71
  const out = new Map();
71
72
  const missing = [];
@@ -78,12 +79,57 @@ function build(kit, ids) {
78
79
  }
79
80
  const usecase = byId.get(id);
80
81
  present.push(usecase);
81
- addSkill(out, usecase, kit.runRules);
82
- addAgents(out, usecase.agents, 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');
83
127
  }
84
- addRouter(out, present, kit.team);
85
- addAgents(out, kit.team, 'team', (agent) => withRoleSkills(agent, present, SKILL_DIR));
86
128
  return { files: out, missing, ids: present.map((u) => u.id) };
87
129
  }
88
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
+
89
135
  module.exports = { build, usecaseGroup };
package/src/lib/sync.js CHANGED
@@ -101,7 +101,7 @@ function recordFiles(actions, ids) {
101
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
103
  function sync(projectDir, ids, previous, { force = false, dryRun = false } = {}) {
104
- const desired = build(loadKit(), ids);
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,4 +1,4 @@
1
- // levi installs for Claude Code only: skills go to .claude/skills, subagents to .claude/agents.
1
+ // Claude Code's installation paths and agent renderer. Codex artifacts are built separately.
2
2
  const SKILL_DIR = '.claude/skills';
3
3
  const AGENT_DIR = '.claude/agents';
4
4
 
@@ -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; }
@@ -14,9 +14,11 @@ import crypto from 'node:crypto';
14
14
 
15
15
  const RESULT_LINE = /^\s*- \*\*(Status|Evidence):\*\*.*$/gm;
16
16
 
17
- function hash(file) {
18
- let text = fs.readFileSync(file, 'utf8').replace(/\r\n/g, '\n');
19
- if (file.endsWith('.md')) text = text.replace(RESULT_LINE, '');
17
+ function hash(file, legacy = false, logicalPath = file) {
18
+ const bytes = fs.readFileSync(file);
19
+ if (!legacy && !logicalPath.endsWith('.md')) return crypto.createHash('sha256').update(bytes).digest('hex');
20
+ let text = bytes.toString('utf8').replace(/\r\n/g, '\n');
21
+ if (logicalPath.endsWith('.md')) text = text.replace(RESULT_LINE, '');
20
22
  return crypto.createHash('sha256').update(text).digest('hex');
21
23
  }
22
24
 
@@ -30,22 +32,33 @@ function lock(dir, paths) {
30
32
  if (!paths.length) throw new Error('nothing to lock');
31
33
  const files = {};
32
34
  for (const file of [...new Set(paths.flatMap(walk))].map((f) => path.normalize(f))) {
33
- const copy = path.join(dir, 'files', file);
35
+ // Keep snapshots out of test discovery (for example Node's **/*.test.js).
36
+ const copy = path.join(dir, 'files', `${file}.levi-snapshot`);
34
37
  fs.mkdirSync(path.dirname(copy), { recursive: true });
35
38
  fs.copyFileSync(file, copy);
36
39
  files[file] = hash(file);
37
40
  }
38
- fs.writeFileSync(path.join(dir, 'manifest.json'), JSON.stringify({ files }, null, 2) + '\n');
41
+ fs.writeFileSync(path.join(dir, 'manifest.json'), JSON.stringify({ version: 2, files }, null, 2) + '\n');
39
42
  console.log(JSON.stringify({ locked: Object.keys(files) }, null, 2));
40
43
  }
41
44
 
42
45
  function verify(dir) {
43
- const { files } = JSON.parse(fs.readFileSync(path.join(dir, 'manifest.json'), 'utf8'));
46
+ const { files, version } = JSON.parse(fs.readFileSync(path.join(dir, 'manifest.json'), 'utf8'));
44
47
  const restored = [];
45
48
  for (const [file, expected] of Object.entries(files)) {
46
- if (fs.existsSync(file) && hash(file) === expected) continue;
49
+ const snapshot = path.join(dir, 'files', `${file}.levi-snapshot`);
50
+ const legacy = path.join(dir, 'files', file);
51
+ // Move old snapshots out of test discovery even when the original is intact.
52
+ if (!fs.existsSync(snapshot) && fs.existsSync(legacy) && fs.statSync(legacy).isFile()) fs.renameSync(legacy, snapshot);
53
+ if (!fs.existsSync(snapshot)) throw new Error(`snapshot missing: ${file}`);
54
+ const currentSnapshotHash = hash(snapshot, false, file);
55
+ const oldHash = version !== 2 && currentSnapshotHash !== expected;
56
+ if (currentSnapshotHash !== expected && (!oldHash || hash(snapshot, true, file) !== expected)) {
57
+ throw new Error(`snapshot corrupted: ${file}`);
58
+ }
59
+ if (fs.existsSync(file) && hash(file, oldHash) === expected) continue;
47
60
  fs.mkdirSync(path.dirname(file), { recursive: true });
48
- fs.copyFileSync(path.join(dir, 'files', file), file);
61
+ fs.copyFileSync(snapshot, file);
49
62
  restored.push(file);
50
63
  }
51
64
  console.log(JSON.stringify({ intact: restored.length === 0, restored, checked: Object.keys(files).length }, null, 2));