@olegkoval/agent-skills 1.89.0 → 1.91.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 (31) hide show
  1. package/adapters/claude/olko-github-pr/skills/lekker-review/SKILL.md +97 -7
  2. package/adapters/claude/olko-github-pr/skills/lekker-review/references/codex-workflow.md +13 -0
  3. package/adapters/claude/olko-github-pr/skills/lekker-review/references/output-format.md +21 -0
  4. package/adapters/claude/olko-github-pr/skills/lekker-review/references/traces.md +1 -1
  5. package/adapters/claude/olko-github-pr/skills/lekker-review/scripts/lekker-progress.mjs +106 -0
  6. package/adapters/claude/olko-github-pr/skills/lekker-review/scripts/model-matrix.mjs +17 -6
  7. package/adapters/claude/olko-github-pr/skills/lekker-review/scripts/run-log.mjs +27 -2
  8. package/adapters/claude/olko-github-pr/skills/lekker-review/scripts/vendor-bridge.mjs +207 -0
  9. package/package.json +1 -1
  10. package/plugins/olko-apple-kit/.claude-plugin/plugin.json +1 -1
  11. package/plugins/olko-creative/.claude-plugin/plugin.json +1 -1
  12. package/plugins/olko-garmin-kit/.claude-plugin/plugin.json +1 -1
  13. package/plugins/olko-git-tools/.claude-plugin/plugin.json +1 -1
  14. package/plugins/olko-github-pr/.claude-plugin/plugin.json +1 -1
  15. package/plugins/olko-github-pr/skills/lekker-review/README.md +34 -0
  16. package/plugins/olko-github-pr/skills/lekker-review/SKILL.md +97 -7
  17. package/plugins/olko-github-pr/skills/lekker-review/fix-workflow.js +92 -9
  18. package/plugins/olko-github-pr/skills/lekker-review/references/codex-workflow.md +13 -0
  19. package/plugins/olko-github-pr/skills/lekker-review/references/output-format.md +21 -0
  20. package/plugins/olko-github-pr/skills/lekker-review/references/traces.md +1 -1
  21. package/plugins/olko-github-pr/skills/lekker-review/scripts/lekker-progress.mjs +106 -0
  22. package/plugins/olko-github-pr/skills/lekker-review/scripts/model-matrix.mjs +17 -6
  23. package/plugins/olko-github-pr/skills/lekker-review/scripts/run-log.mjs +27 -2
  24. package/plugins/olko-github-pr/skills/lekker-review/scripts/vendor-bridge.mjs +207 -0
  25. package/plugins/olko-github-pr/skills/lekker-review/workflow.js +129 -14
  26. package/plugins/olko-obsidian/.claude-plugin/plugin.json +1 -1
  27. package/plugins/olko-product/.claude-plugin/plugin.json +1 -1
  28. package/plugins/olko-reflection/.claude-plugin/plugin.json +1 -1
  29. package/plugins/olko-release/.claude-plugin/plugin.json +1 -1
  30. package/plugins/olko-skill-meta/.claude-plugin/plugin.json +1 -1
  31. package/plugins/olko-web-ops/.claude-plugin/plugin.json +1 -1
@@ -230,6 +230,26 @@ section if empty.)*
230
230
 
231
231
  ---
232
232
 
233
+ ## 🧭 Decisions
234
+
235
+ *(Why the run went the way it did. Built from the decisions written to the run
236
+ log; omit the whole section with `--quiet-decisions`, and when the run log is
237
+ unavailable.)*
238
+
239
+ - **Depth:** <depth>, <the AUTO-DEPTH rule or "explicit">
240
+ - **Tier:** <tier> (<auto: reason | --risk>)
241
+ - **Routes:** <role> <model> [<effort>] · <role> <model> [<effort>] · ... (<"risk tier routing" | "default model">)
242
+ - **Findings:** <K> kept · <D> downgraded · <X> dropped *(Critical/Important only, counted from the `finding` decisions)*
243
+ - <kept | downgraded | dropped> `<file:line>` <title>: <verifier's one-line reason>
244
+
245
+ Exact rules: one bullet per Critical/Important finding the verifier ruled on,
246
+ in the order they were decided, reason copied from the decision's `why` without
247
+ the leading outcome word. No bullets and `Findings: none verified` when no
248
+ `finding` decisions exist (for example `scan` with no Criticals, or the revmux
249
+ engine). Never add decisions that were not written to the run log.
250
+
251
+ ---
252
+
233
253
  ## 💰 Review Cost
234
254
 
235
255
  ```
@@ -237,6 +257,7 @@ Depth: <📦 deps | ⚡ scan | 🔍 medium | 🔬 deep>
237
257
  Diff size: ~<N> lines (~<N> tokens)
238
258
  Agents run: <N total>: <breakdown, e.g. "5 reviewers (sonnet/high) + 6 verifiers (opus/high) + 2 provers (sonnet/high) + 1 critic (opus/high)">
239
259
  Risk tier: <tier> (<auto: reason | --risk>), routes from the workflow's `routing` return value
260
+ Cross-vendor: <N> gate agents on <vendor>, <M> fell back (only with --crossvendor; N and M from crossvendorAgents and crossvendorFallbacks)
240
261
  Rule checks: <N> hard-rule finding(s) validated with rule-specific checks (omit the line when 0)
241
262
  Context sources: <the subset of issue-tracker / chat / docs / framework-docs / monitoring / CI / prior-review-memory actually used>
242
263
 
@@ -6,7 +6,7 @@ points at, and copies the numbers out of, everything else.
6
6
  | Trace | Path | Written by | Kept | What it answers |
7
7
  |---|---|---|---|---|
8
8
  | Run ledger | `~/.local/state/lekker-review/runs.jsonl` | `scripts/run-log.mjs finish`, `backfill` | forever (one line per run) | how long, how many tokens, findings, drops, proofs, verdict, per engine and depth |
9
- | Run archive | `~/.local/state/lekker-review/runs/<runId>/` | `run-log.mjs start/mark/attach/finish` | 90 days (`prune`) | `run.json` with timeline, plus the run's `findings.json`, `worktree.json`, `preflight.json`, `context.json` |
9
+ | Run archive | `~/.local/state/lekker-review/runs/<runId>/` | `run-log.mjs start/mark/decide/attach/finish` | 90 days (`prune`) | `run.json` with timeline and decisions (also appended live to `timeline.jsonl`), plus the run's `findings.json`, `worktree.json`, `preflight.json`, `context.json` |
10
10
  | Dependency ledger | `~/.local/state/lekker-review/deps.json` | `scripts/deps.mjs` | forever | which optional tools were installed or skipped, versions, last upstream check |
11
11
  | Review report | `~/code-reviews/<date>-<target>-<repo>.md` | Step 3 | forever | the review as printed, including the `Review Cost` block |
12
12
  | revmux archive | `~/code-reviews/revmux-tasks/<task>/<NN-run>/` | revmux, plus `revmux.stderr.log` from `scripts/revmux-engine.sh` | forever, never edit | `events.jsonl` (agent start, degraded, retried), `agents/*.jsonl` (per-agent cost and usage), `revmux.stderr.log` (why a round degraded; rounds before 2026-10-20 have none) |
@@ -0,0 +1,106 @@
1
+ #!/usr/bin/env node
2
+ // One-line progress status for lekker-review: a boat drifts over a tide line toward a lighthouse.
3
+ //
4
+ // Usage: node lekker-progress.mjs --stage <stage> --message "<short fact>" [--ascii]
5
+ //
6
+ // Each call prints exactly one line and exits 0, even on bad arguments. On a TTY it first animates
7
+ // the drift on that line (at most 10 fps, under a second); anywhere else (captured tool output, a
8
+ // log) or with NO_COLOR or --ascii it prints the final frame only, with no escape codes.
9
+ // The `decision` stage prints a compass line and leaves the boat where it was.
10
+
11
+ import { pathToFileURL } from 'node:url';
12
+
13
+ export const SLOTS = 8;
14
+ export const MAX_WIDTH = 72;
15
+ const FRAME_MS = 100;
16
+
17
+ // stage -> [slot the boat reaches, mood, default message]
18
+ export const STAGES = {
19
+ start: [0, 'neutral', 'parsed the request'],
20
+ context: [1, 'neutral', 'context ready'],
21
+ review: [2, 'neutral', 'review agents started'],
22
+ verify: [3, 'neutral', 'verifying findings'],
23
+ critic: [4, 'neutral', 'completeness critic'],
24
+ prove: [5, 'neutral', 'proving bugs with tests'],
25
+ fix: [6, 'neutral', 'applying fixes'],
26
+ post: [7, 'neutral', 'posting the review'],
27
+ success: [SLOTS, 'happy', 'review saved'],
28
+ failure: [4, 'sad', 'review stopped'],
29
+ decision: [null, 'neutral', 'decision'],
30
+ };
31
+
32
+ const GLYPHS = {
33
+ false: { boat: '⛵', light: '🗼', tide: ' ~', compass: '🧭 ', neutral: '', happy: '😌', sad: '🌧️' },
34
+ true: { boat: '^', light: 'I', tide: '.', compass: '> ', neutral: '', happy: '(^o^)', sad: '(T.T)' },
35
+ };
36
+
37
+ const WIDE = [[0x1100, 0x115f], [0x231a, 0x231b], [0x23e9, 0x23ec], [0x25fd, 0x25fe], [0x2614, 0x2615],
38
+ [0x2693, 0x2693], [0x26a1, 0x26a1], [0x26f5, 0x26f5], [0x2e80, 0xa4cf], [0xac00, 0xd7a3],
39
+ [0xf900, 0xfaff], [0xfe30, 0xfe6f], [0xff00, 0xff60], [0xffe0, 0xffe6], [0x1f000, 0x1ffff]];
40
+
41
+ function cellWidth(ch) {
42
+ const cp = ch.codePointAt(0);
43
+ if (/\p{M}/u.test(ch) || cp === 0x200d || cp === 0xfe0f) return 0;
44
+ return WIDE.some(([lo, hi]) => cp >= lo && cp <= hi) ? 2 : 1;
45
+ }
46
+
47
+ export const width = (text) => [...text].reduce((n, ch) => n + cellWidth(ch), 0);
48
+
49
+ export function truncate(text, limit) {
50
+ const { out, done } = [...text].reduce((acc, ch) => {
51
+ if (acc.done) return acc;
52
+ const next = acc.used + cellWidth(ch);
53
+ return next > limit - 1 ? { ...acc, done: true } : { out: acc.out + ch, used: next, done: false };
54
+ }, { out: '', used: 0, done: false });
55
+ return done ? `${out}…` : out;
56
+ }
57
+
58
+ const oneLine = (text) => String(text ?? '').split(/\s+/).filter(Boolean).join(' ');
59
+ const fit = (line) => (width(line) <= MAX_WIDTH ? line : truncate(line, MAX_WIDTH));
60
+
61
+ function track(slot, glyphs) {
62
+ const cells = Array.from({ length: SLOTS + 1 }, (_, i) => (i === SLOTS ? glyphs.light : glyphs.tide));
63
+ return cells.map((cell, i) => (i === Math.min(slot, SLOTS) ? glyphs.boat : cell)).join('');
64
+ }
65
+
66
+ // Pure: `tick` is the boat's slot. The mood face shows once the boat has arrived.
67
+ export function frame(stage, tick, { message, ascii = false } = {}) {
68
+ const spec = STAGES[stage];
69
+ const glyphs = GLYPHS[ascii === true];
70
+ const text = oneLine(message ?? spec?.[2] ?? '');
71
+ if (!spec) return fit(`lekker: ${text || stage || 'progress'}`);
72
+ const [target, mood] = spec;
73
+ if (target === null) return fit(`${glyphs.compass}${text || spec[2]}`);
74
+ const face = tick >= target ? glyphs[mood] : '';
75
+ return fit(`${`${track(tick, glyphs)} ${face}`.trimEnd()} ${stage}: ${text}`);
76
+ }
77
+
78
+ const arg = (argv, name) => {
79
+ const i = argv.indexOf(`--${name}`);
80
+ return i === -1 ? undefined : argv[i + 1];
81
+ };
82
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
83
+
84
+ async function main(argv) {
85
+ const stage = arg(argv, 'stage') ?? '';
86
+ const message = arg(argv, 'message');
87
+ const ascii = argv.includes('--ascii') || Boolean(process.env.LEKKER_PROGRESS_ASCII);
88
+ const spec = STAGES[stage];
89
+ const animate = process.stdout.isTTY === true && !process.env.NO_COLOR && !ascii && Array.isArray(spec) && spec[0] !== null;
90
+ if (animate) {
91
+ const target = spec[0];
92
+ const slots = Array.from({ length: Math.min(3, target) }, (_, i) => target - 3 + i).filter((s) => s >= 0);
93
+ for (const slot of slots) {
94
+ process.stdout.write(`\r\x1b[2K${frame(stage, slot, { message, ascii })}`);
95
+ await sleep(FRAME_MS);
96
+ }
97
+ process.stdout.write('\r\x1b[2K');
98
+ }
99
+ const target = spec && spec[0] !== null ? spec[0] : 0;
100
+ process.stdout.write(`${frame(stage, target, { message, ascii })}\n`);
101
+ }
102
+
103
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
104
+ try { await main(process.argv.slice(2)); } catch { /* decoration must never fail a review */ }
105
+ process.exitCode = 0;
106
+ }
@@ -8,10 +8,12 @@
8
8
  // (haiku, luna) only ever do first-pass triage or housekeeping.
9
9
  //
10
10
  // node model-matrix.mjs --host claude|codex [--risk <tier>] [--lines <n>]
11
- // [--categories auth,billing,...] -- <changed-file>...
11
+ // [--categories auth,billing,...] [--crossvendor] -- <changed-file>...
12
12
  //
13
13
  // `--categories` is the comma-joined `categories[].category` list from
14
14
  // risk-paths.mjs. `--lines` is additions+deletions without lockfiles.
15
+ // `--crossvendor` moves the gate roles to the other host's model at the same
16
+ // tier: a cell gains `vendor` and `hostRoute` (the route it falls back to).
15
17
  // Prints {host, tier, tierSource, reasons, visual, routing}.
16
18
  import { pathToFileURL } from 'node:url'
17
19
 
@@ -92,12 +94,17 @@ export function isVisual(files = []) {
92
94
  return code.length > 0 && code.every(f => UI_FILE.test(f))
93
95
  }
94
96
 
95
- export function routingFor(host, tier, { visual = false } = {}) {
97
+ export function routingFor(host, tier, { visual = false, crossvendor = false } = {}) {
96
98
  if (!HOSTS.includes(host)) throw new Error(`unknown host "${host}"; use one of ${HOSTS.join(', ')}`)
97
99
  if (!TIERS.includes(tier)) throw new Error(`unknown risk tier "${tier}"`)
98
100
  const column = TIERS.indexOf(tier)
99
101
  const routing = Object.fromEntries(Object.entries(MATRIX[host]).map(([role, row]) => [role, row[column]]))
100
- return visual && VISUAL_SPECIALIST[host] ? { ...routing, specialist: VISUAL_SPECIALIST[host] } : routing
102
+ const routed = visual && VISUAL_SPECIALIST[host] ? { ...routing, specialist: VISUAL_SPECIALIST[host] } : routing
103
+ if (!crossvendor) return routed
104
+ const vendor = HOSTS.find(h => h !== host)
105
+ const crossed = Object.fromEntries(GATE_ROLES.map(role =>
106
+ [role, { ...MATRIX[vendor][role][column], vendor, hostRoute: routed[role] }]))
107
+ return { ...routed, ...crossed }
101
108
  }
102
109
 
103
110
  const ROLE_LABELS = {
@@ -134,15 +141,19 @@ function parseArgs(argv) {
134
141
  return i === -1 ? undefined : flags[i + 1]
135
142
  }
136
143
  const categories = (value('--categories') ?? '').split(',').map(s => s.trim()).filter(Boolean)
137
- return { host: value('--host'), override: value('--risk'), lines: Number(value('--lines') ?? 0), categories, files }
144
+ return {
145
+ host: value('--host'), override: value('--risk'), lines: Number(value('--lines') ?? 0), categories, files,
146
+ crossvendor: flags.includes('--crossvendor'),
147
+ }
138
148
  }
139
149
 
140
150
  function main(argv) {
141
- const { host, override, lines, categories, files } = parseArgs(argv)
151
+ const { host, override, lines, categories, files, crossvendor } = parseArgs(argv)
142
152
  try {
143
153
  const { tier, tierSource, reasons } = tierFor({ files, categories, lines, override })
144
154
  const visual = isVisual(files)
145
- console.log(JSON.stringify({ host, tier, tierSource, reasons, visual, routing: routingFor(host, tier, { visual }) }))
155
+ const routing = routingFor(host, tier, { visual, crossvendor })
156
+ console.log(JSON.stringify({ host, tier, tierSource, reasons, visual, ...(crossvendor ? { crossvendor } : {}), routing }))
146
157
  } catch (error) {
147
158
  console.error(`model-matrix: ${error.message}`)
148
159
  process.exit(2)
@@ -11,6 +11,8 @@
11
11
  // node run-log.mjs start --repo <slug> --target <pr-N|branch-x> --mode pr|branch \
12
12
  // --depth <d> --engine workflow|revmux [--fix] [--host claude]
13
13
  // node run-log.mjs mark <runId> <phase> [--note <text>]
14
+ // node run-log.mjs decide <runId> --kind depth|tier|route|finding|fix|post --what <text> --why <text>
15
+ // node run-log.mjs decide <runId> --from-json <file> array of {kind, what, why}
14
16
  // node run-log.mjs attach <runId> <file>...
15
17
  // node run-log.mjs finish <runId> --status ok|failed|aborted [--verdict lgtm|lgtm-with-changes|needs-work]
16
18
  // [--review-file <path>] [--artifact-url <url>] [--wf <wf_id>]... [--note <text>]
@@ -37,6 +39,7 @@ const LEDGER = join(STATE_DIR, 'runs.jsonl');
37
39
  const PROJECTS_DIR = process.env.LEKKER_CLAUDE_PROJECTS || join(homedir(), '.claude', 'projects');
38
40
  const REVMUX_TASKS = process.env.LEKKER_REVMUX_TASKS_DIR || join(homedir(), 'code-reviews', 'revmux-tasks');
39
41
 
42
+ const DECISION_KINDS = ['depth', 'tier', 'route', 'finding', 'fix', 'post'];
40
43
  const argv = process.argv.slice(2);
41
44
  const cmd = argv[0];
42
45
 
@@ -171,6 +174,25 @@ if (cmd === 'start') {
171
174
  if (!existsSync(dir)) fail(`no run ${runId}`);
172
175
  appendFileSync(join(dir, 'timeline.jsonl'), JSON.stringify({ phase, at: new Date().toISOString(), note: flag('note') ?? undefined }) + '\n');
173
176
  console.log(JSON.stringify({ runId, phase }));
177
+ } else if (cmd === 'decide') {
178
+ const runId = argv[1];
179
+ const dir = runDir(runId);
180
+ if (!existsSync(dir)) fail(`no run ${runId}`);
181
+ const fromJson = flag('from-json');
182
+ const raw = fromJson ? readJson(fromJson) : [{ kind: flag('kind'), what: flag('what'), why: flag('why') }];
183
+ if (!Array.isArray(raw)) fail(`--from-json ${fromJson} must hold an array of {kind, what, why}`);
184
+ const text = (v) => (typeof v === 'string' ? v.replace(/\s+/g, ' ').trim() : '');
185
+ const rows = raw.map((d, i) => ({ kind: text(d?.kind), what: text(d?.what), why: text(d?.why), i }));
186
+ const bad = rows.find((r) => !DECISION_KINDS.includes(r.kind) || !r.what || !r.why);
187
+ if (bad) {
188
+ fail(!DECISION_KINDS.includes(bad.kind)
189
+ ? `decision ${bad.i}: unknown kind "${bad.kind}" (use ${DECISION_KINDS.join('|')})`
190
+ : `decision ${bad.i}: --what and --why must be non-empty`);
191
+ }
192
+ const at = new Date().toISOString();
193
+ const lines = rows.map(({ kind, what, why }) => JSON.stringify({ at, kind, what, why }) + '\n').join('');
194
+ appendFileSync(join(dir, 'timeline.jsonl'), lines);
195
+ console.log(JSON.stringify({ runId, decisions: rows.length }));
174
196
  } else if (cmd === 'attach') {
175
197
  const runId = argv[1];
176
198
  const dir = runDir(runId);
@@ -188,7 +210,10 @@ if (cmd === 'start') {
188
210
  const meta = readJson(join(dir, 'run.json'));
189
211
  if (!meta) fail(`no run ${runId}`);
190
212
  const finishedAt = new Date().toISOString();
191
- const timeline = [...readJsonl(join(dir, 'timeline.jsonl')), { phase: 'finish', at: finishedAt }];
213
+ const rows = readJsonl(join(dir, 'timeline.jsonl'));
214
+ // Decision rows have no phase; keeping them out of the timeline keeps phaseDurations exact.
215
+ const timeline = [...rows.filter((r) => r.phase && r.phase !== 'finish'), { phase: 'finish', at: finishedAt }];
216
+ const decisions = rows.filter((r) => r.kind);
192
217
  const workflows = flags('wf').map((id) => summariseWorkflow(findWorkflowRecord(id) || { runId: id }));
193
218
  const reviewWf = workflows.find((w) => w.name === 'lekker-review-core') || null;
194
219
  const row = {
@@ -206,7 +231,7 @@ if (cmd === 'start') {
206
231
  artifactUrl: flag('artifact-url'),
207
232
  note: flag('note', meta.note ?? null),
208
233
  };
209
- writeFileSync(join(dir, 'run.json'), JSON.stringify({ ...row, timeline }, null, 2) + '\n');
234
+ writeFileSync(join(dir, 'run.json'), JSON.stringify({ ...row, timeline, decisions }, null, 2) + '\n');
210
235
  append(row);
211
236
  const unresolved = workflows.filter((w) => w.durationS == null).map((w) => w.wfId);
212
237
  console.log(JSON.stringify({ runId, ledger: LEDGER, wallS: row.wallS, tokensTotal: row.tokensTotal, unresolvedWorkflows: unresolved }));
@@ -0,0 +1,207 @@
1
+ #!/usr/bin/env node
2
+ // Runs one read-only gate agent on the other vendor's CLI and returns schema-checked JSON.
3
+ //
4
+ // node vendor-bridge.mjs --to codex|claude --model <m> --effort <e>
5
+ // --schema <schema.json> --prompt <prompt.md> --cwd <dir> --out <result.json>
6
+ // [--timeout <seconds>]
7
+ //
8
+ // Exit 0: validated JSON is in --out. Exit 3: --out holds {"fallback": "<reason>"}
9
+ // and the caller reruns the agent on its own vendor. Exit 2: unusable arguments.
10
+ // The prompt travels by stdin and every process gets an argument array, so
11
+ // nothing from the prompt, schema or paths is ever parsed by a shell.
12
+ import { execFileSync, spawn } from 'node:child_process'
13
+ import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs'
14
+ import { dirname } from 'node:path'
15
+ import { text } from 'node:stream/consumers'
16
+ import { fileURLToPath } from 'node:url'
17
+
18
+ export const FALLBACK_EXIT = 3
19
+ export const TARGETS = ['codex', 'claude']
20
+ const DEFAULT_TIMEOUT_SECONDS = 600
21
+
22
+ const REQUIRED = ['to', 'model', 'effort', 'schema', 'prompt', 'cwd', 'out']
23
+
24
+ export function parseArgs(argv) {
25
+ const pairs = argv.reduce((acc, token, i) =>
26
+ token.startsWith('--') && i + 1 < argv.length ? { ...acc, [token.slice(2)]: argv[i + 1] } : acc, {})
27
+ const timeout = pairs.timeout === undefined ? DEFAULT_TIMEOUT_SECONDS : Number(pairs.timeout)
28
+ const missing = REQUIRED.filter(key => !pairs[key])
29
+ if (missing.length > 0) return { error: `missing ${missing.map(k => `--${k}`).join(', ')}` }
30
+ if (!TARGETS.includes(pairs.to)) return { error: `--to must be one of ${TARGETS.join(', ')}` }
31
+ if (!(timeout > 0)) return { error: '--timeout must be a positive number of seconds' }
32
+ return { options: { ...Object.fromEntries(REQUIRED.map(k => [k, pairs[k]])), timeout } }
33
+ }
34
+
35
+ const typeMatches = (type, value) => ({
36
+ object: v => v !== null && typeof v === 'object' && !Array.isArray(v),
37
+ array: Array.isArray,
38
+ string: v => typeof v === 'string',
39
+ integer: Number.isInteger,
40
+ number: v => typeof v === 'number',
41
+ boolean: v => typeof v === 'boolean',
42
+ }[type]?.(value) ?? true)
43
+
44
+ // The JSON Schema keywords the lekker gate schemas use: type, enum, minLength,
45
+ // pattern, items, required, properties and anyOf. Any other keyword passes
46
+ // unchecked, so a schema must not rely on one this function does not know.
47
+ export function validate(schema, value, path = '$') {
48
+ if (schema.type !== undefined && !typeMatches(schema.type, value)) return [`${path} is not ${schema.type}`]
49
+ if (schema.enum && !schema.enum.includes(value)) return [`${path} is not one of ${schema.enum.join('|')}`]
50
+ if (typeof value === 'string' && schema.minLength !== undefined && value.length < schema.minLength) {
51
+ return [`${path} is shorter than ${schema.minLength}`]
52
+ }
53
+ if (typeof value === 'string' && schema.pattern !== undefined && !new RegExp(schema.pattern).test(value)) {
54
+ return [`${path} does not match ${schema.pattern}`]
55
+ }
56
+ if (schema.anyOf && schema.anyOf.every(sub => validate(sub, value, path).length > 0)) {
57
+ return [`${path} matches none of the anyOf alternatives`]
58
+ }
59
+ if (Array.isArray(value) && schema.items) {
60
+ return value.flatMap((item, i) => validate(schema.items, item, `${path}[${i}]`))
61
+ }
62
+ if (!typeMatches('object', value)) return []
63
+ const absent = (schema.required ?? []).filter(key => !(key in value)).map(key => `${path}.${key} is required`)
64
+ const nested = Object.entries(schema.properties ?? {})
65
+ .filter(([key]) => key in value)
66
+ .flatMap(([key, sub]) => validate(sub, value[key], `${path}.${key}`))
67
+ return [...absent, ...nested]
68
+ }
69
+
70
+ // Codex strict structured output rejects schemas with optional properties, which
71
+ // every lekker schema has, so Codex gets the schema in the prompt and the bridge
72
+ // validates its answer instead of passing --output-schema.
73
+ export function promptFor(to, prompt, schemaText) {
74
+ return to === 'codex'
75
+ ? `${prompt}\n\nReply with only one JSON value, no prose and no code fence, that matches this JSON Schema:\n${schemaText}\n`
76
+ : prompt
77
+ }
78
+
79
+ // The Claude target gets no shell at all: git options such as --output can
80
+ // write files, and prefix rules cannot exclude them. A fix verifier needs the
81
+ // worktree's uncommitted diff, so the bridge saves it to a file it can Read.
82
+ const CLAUDE_READ_ONLY_TOOLS = 'Read,Grep,Glob'
83
+ const CLAUDE_DENIED_TOOLS = 'Bash,Edit,Write,NotebookEdit'
84
+
85
+ export function worktreeDiff(cwd) {
86
+ try {
87
+ const status = execFileSync('git', ['-C', cwd, 'status', '--short'], { encoding: 'utf8', maxBuffer: 1 << 26 })
88
+ const diff = execFileSync('git', ['-C', cwd, 'diff', '--no-ext-diff', '--no-color'], { encoding: 'utf8', maxBuffer: 1 << 26 })
89
+ return `# git status --short\n${status}\n# git diff\n${diff}`
90
+ } catch {
91
+ return null
92
+ }
93
+ }
94
+
95
+ export function withDiffNote(prompt, diffPath) {
96
+ return diffPath === null
97
+ ? prompt
98
+ : `${prompt}\n\nYou have no shell. The working tree's uncommitted changes (git status and git diff) are saved at ${diffPath}; Read that file wherever these instructions say to run git.\n`
99
+ }
100
+
101
+ export function commandFor({ to, model, effort, schemaText, rawOut, cwd }) {
102
+ return to === 'codex'
103
+ ? { cmd: 'codex', args: ['exec', '-m', model, '-c', `model_reasoning_effort=${effort}`, '-s', 'read-only',
104
+ '--skip-git-repo-check', '-o', rawOut, '-C', cwd, '-'] }
105
+ : { cmd: 'claude', args: ['-p', '--model', model, '--effort', effort, '--output-format', 'json',
106
+ '--json-schema', schemaText, '--permission-mode', 'default',
107
+ '--allowedTools', CLAUDE_READ_ONLY_TOOLS, '--disallowedTools', CLAUDE_DENIED_TOOLS] }
108
+ }
109
+
110
+ const parseJson = raw => {
111
+ try { return { value: JSON.parse(raw) } } catch { return { error: 'output is not valid JSON' } }
112
+ }
113
+
114
+ const unfence = raw => raw.trim().replace(/^```(?:json)?\s*\n?([\s\S]*?)\n?```$/, '$1')
115
+
116
+ // `to` names the CLI that ran: codex leaves its last message in a file, claude prints an envelope.
117
+ export function resultFrom(to, { stdout, rawOutText }) {
118
+ if (to === 'codex') return parseJson(unfence(rawOutText ?? ''))
119
+ const envelope = parseJson(stdout)
120
+ if (envelope.error || !typeMatches('object', envelope.value)) return { error: 'claude output is not a JSON envelope' }
121
+ const { is_error: isError, structured_output: structured, result } = envelope.value
122
+ if (isError) return { error: `claude reported an error: ${String(result).slice(0, 200)}` }
123
+ return structured !== undefined && structured !== null ? { value: structured } : parseJson(unfence(String(result ?? '')))
124
+ }
125
+
126
+ function writeAtomic(path, value) {
127
+ mkdirSync(dirname(path), { recursive: true })
128
+ const staging = `${path}.tmp`
129
+ writeFileSync(staging, `${JSON.stringify(value)}\n`)
130
+ renameSync(staging, path)
131
+ }
132
+
133
+ function runProcess(cmd, args, { stdin, cwd, timeoutMs }) {
134
+ return new Promise(resolve => {
135
+ const child = spawn(cmd, args, { cwd, stdio: ['pipe', 'pipe', 'pipe'] })
136
+ const stdout = text(child.stdout).catch(() => '')
137
+ const stderr = text(child.stderr).catch(() => '')
138
+ const timer = setTimeout(() => {
139
+ child.kill('SIGKILL')
140
+ resolve({ reason: `timed out after ${timeoutMs / 1000}s` })
141
+ }, timeoutMs)
142
+ child.on('error', error => {
143
+ clearTimeout(timer)
144
+ resolve({ reason: error.code === 'ENOENT' ? `${cmd} not found on PATH` : `${cmd} failed to start: ${error.message}` })
145
+ })
146
+ child.on('close', async code => {
147
+ clearTimeout(timer)
148
+ resolve({ code, stdout: await stdout, stderr: await stderr })
149
+ })
150
+ child.stdin.on('error', () => {})
151
+ child.stdin.end(stdin)
152
+ })
153
+ }
154
+
155
+ const firstLine = raw => String(raw ?? '').trim().split('\n')[0].slice(0, 200)
156
+
157
+ function readInputs(promptPath, schemaPath) {
158
+ try {
159
+ return { prompt: readFileSync(promptPath, 'utf8'), schemaText: readFileSync(schemaPath, 'utf8').trim() }
160
+ } catch (error) {
161
+ return { error: firstLine(error.message) }
162
+ }
163
+ }
164
+
165
+ async function runVendor(options) {
166
+ const { to, model, effort, schema, prompt, cwd, timeout, out } = options
167
+ const inputs = readInputs(prompt, schema)
168
+ if (inputs.error) return { fallback: `cannot read prompt or schema: ${inputs.error}` }
169
+ const schemaValue = parseJson(inputs.schemaText)
170
+ if (schemaValue.error) return { fallback: 'schema file is not valid JSON' }
171
+
172
+ const rawOut = `${out}.raw`
173
+ rmSync(rawOut, { force: true })
174
+ const { cmd, args } = commandFor({ to, model, effort, schemaText: inputs.schemaText, rawOut, cwd })
175
+ const diffText = to === 'claude' ? worktreeDiff(cwd) : null
176
+ const diffPath = diffText === null ? null : `${out}.worktree.diff`
177
+ if (diffPath !== null) writeFileSync(diffPath, diffText)
178
+ const stdin = withDiffNote(promptFor(to, inputs.prompt, inputs.schemaText), diffPath)
179
+ const ran = await runProcess(cmd, args, { stdin, cwd, timeoutMs: timeout * 1000 })
180
+ if (ran.reason) return { fallback: ran.reason }
181
+ if (ran.code !== 0) return { fallback: `${cmd} exited ${ran.code}: ${firstLine(ran.stderr)}` }
182
+
183
+ const rawOutText = existsSync(rawOut) ? readFileSync(rawOut, 'utf8') : undefined
184
+ const parsed = resultFrom(to, { stdout: ran.stdout, rawOutText })
185
+ if (parsed.error) return { fallback: parsed.error }
186
+ const problems = validate(schemaValue.value, parsed.value)
187
+ return problems.length > 0 ? { fallback: `schema mismatch: ${problems[0]}` } : { value: parsed.value }
188
+ }
189
+
190
+ async function main(argv) {
191
+ const { options, error } = parseArgs(argv)
192
+ if (error) {
193
+ console.error(`vendor-bridge: ${error}`)
194
+ process.exit(2)
195
+ }
196
+ const outcome = await runVendor(options)
197
+ const failed = outcome.fallback !== undefined
198
+ writeAtomic(options.out, failed ? { fallback: outcome.fallback } : outcome.value)
199
+ if (failed) console.error(`vendor-bridge: fallback: ${outcome.fallback}`)
200
+ process.exit(failed ? FALLBACK_EXIT : 0)
201
+ }
202
+
203
+ // Real paths, so a skill installed through a symlinked directory still runs.
204
+ const isEntrypoint = () => {
205
+ try { return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url)) } catch { return false }
206
+ }
207
+ if (isEntrypoint()) main(process.argv.slice(2))