@telpin-sistemas/orqen 0.1.14 → 0.1.16

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.
@@ -0,0 +1,65 @@
1
+ /** `orqen bots` and `orqen mcp`: the bot profiles of this person and the MCP servers their agents can reach. */
2
+ import { readFileSync } from "node:fs";
3
+ import { ZodError } from "zod";
4
+ import { botsFile, botsFor, readBots, stagesIn, STAGES, toolsIn, writeBots } from "../lib/bots.js";
5
+ import { mcpServers } from "../lib/mcp.js";
6
+ import { mainWorktree, repoRoot } from "../workflow/config.js";
7
+ export const BOTS_HELP = ` bots [--json] Your bot profiles and the stages of this project where each one helps (~/.orqen/bots.json)
8
+ bots set <file|-> Save the whole list (JSON: {"bots": [{name, prompt, projects: {<repo>: [stages]}, connectors}]})
9
+ mcp [--json] MCP servers your agents can reach (.mcp.json, Claude Code, Codex, Gemini); added in each agent`;
10
+ const here = () => mainWorktree(repoRoot());
11
+ function view(bots, repo) {
12
+ return {
13
+ file: botsFile(),
14
+ repo,
15
+ stages: STAGES,
16
+ bots,
17
+ here: {
18
+ tools: toolsIn(bots, repo),
19
+ stages: Object.fromEntries(STAGES.map((s) => [s, botsFor(bots, repo, s).map((b) => b.name)]).filter(([, n]) => n.length)),
20
+ },
21
+ };
22
+ }
23
+ function fail(e) {
24
+ const msg = e instanceof ZodError ? e.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ") : e.message;
25
+ console.error(`✘ ${msg}`);
26
+ process.exitCode = 1;
27
+ }
28
+ export async function botsCommand(args) {
29
+ const json = args.includes("--json");
30
+ const rest = args.filter((a) => a !== "--json");
31
+ const repo = here();
32
+ try {
33
+ if (rest[0] === "set") {
34
+ const src = rest[1] && rest[1] !== "-" ? readFileSync(rest[1], "utf8") : readFileSync(0, "utf8");
35
+ const bots = writeBots(JSON.parse(src));
36
+ return console.log(JSON.stringify(view(bots, repo), null, 2));
37
+ }
38
+ if (rest[0]) {
39
+ console.error(`✘ orqen bots: unknown "${rest[0]}" (bots [--json] | bots set <file|->)`);
40
+ process.exitCode = 1;
41
+ return;
42
+ }
43
+ const bots = readBots();
44
+ if (json)
45
+ return console.log(JSON.stringify(view(bots, repo), null, 2));
46
+ if (!bots.length)
47
+ return console.log(`No bots yet. orqen-studio (Settings › Bots) creates them, or: orqen bots set <file>\n${botsFile()}`);
48
+ for (const b of bots) {
49
+ const st = stagesIn(b, repo);
50
+ console.log(`${b.name.padEnd(20)} ${st.length ? st.join(", ") : "(not in this project)"}${b.connectors.length ? ` · mcp: ${b.connectors.join(", ")}` : ""}`);
51
+ }
52
+ }
53
+ catch (e) {
54
+ fail(e);
55
+ }
56
+ }
57
+ export async function mcpCommand(args) {
58
+ const list = mcpServers(repoRoot() ? here() : undefined);
59
+ if (args.includes("--json"))
60
+ return console.log(JSON.stringify({ servers: list }, null, 2));
61
+ if (!list.length)
62
+ return console.log("No MCP servers configured (add them in Claude Code, Codex or Gemini).");
63
+ for (const s of list)
64
+ console.log(`${s.name.padEnd(20)} ${s.source.padEnd(8)} ${s.file}`);
65
+ }
@@ -3,7 +3,7 @@
3
3
  * (injected into each stage's instructions) and new eval cases.
4
4
  */
5
5
  import { execFileSync } from "node:child_process";
6
- import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
6
+ import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
7
7
  import { join } from "node:path";
8
8
  import { stringify } from "yaml";
9
9
  import { buildConnectors } from "../connectors/index.js";
@@ -18,7 +18,11 @@ export const EVAL_HELP = ` eval [case|step...] Run the agent on test ticket
18
18
  --keep Keep the test projects · --json Machine-readable result
19
19
  learn What the team marked right/wrong in the desktop app, by step
20
20
  --apply Add the new notes to orqen/knowledge/lessons/<STAGE>.md (the agent reads them in that stage)
21
- --to-eval <run> Turn a run marked wrong into an eval case (orqen/evals/)`;
21
+ --apply <run> Only that note · --discard <run> Drop a note without making it a lesson
22
+ --to-eval <run> Turn a run marked wrong into an eval case (orqen/evals/)
23
+ --json Feedback by step, the pending notes, the lessons of each stage and the eval history
24
+ run record <file|-> Log an agent run of a worq (JSON: run, key, command, state_before, secs, cost…) in orqen/state/app-chat/runs.jsonl
25
+ feedback <run> up|down Mark a run right or wrong · --note <text|-> what was wrong (it becomes a lesson with learn --apply)`;
22
26
  function gitRoot() {
23
27
  try {
24
28
  return execFileSync("git", ["rev-parse", "--show-toplevel"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
@@ -44,6 +48,16 @@ function takeBool(args, name) {
44
48
  export async function evalCommand(args) {
45
49
  const a = [...args];
46
50
  const json = takeBool(a, "json"), keep = takeBool(a, "keep"), noLessons = takeBool(a, "no-lessons");
51
+ if (takeBool(a, "history")) {
52
+ const h = evalHistory(gitRoot());
53
+ if (json)
54
+ return console.log(JSON.stringify(h, null, 2));
55
+ if (!h.length)
56
+ return console.log("No eval runs yet: orqen eval");
57
+ for (const r of h.slice(-10))
58
+ console.log(` ${r.ts.slice(0, 16).replace("T", " ")} ${r.passed}/${r.total}${r.lessons ? "" : " (no lessons)"}${r.cost !== undefined ? ` US$ ${Number(r.cost).toFixed(2)}` : ""} ${r.agent}`);
59
+ return;
60
+ }
47
61
  const agentFlag = takeFlag(a, "agent"), judgeFlag = takeFlag(a, "judge");
48
62
  const repo = gitRoot();
49
63
  const cfgAgent = existsSync(join(repo, "orqen", "config.yaml")) ? loadConfig().agentCmd : "";
@@ -94,6 +108,12 @@ const STAGE_OF = {
94
108
  "/orqen:support": "SUPPORT", "/orqen:analyze": "ANALYSIS", "/orqen:implement": "DEVELOPMENT",
95
109
  "/orqen:pr": "DELIVERY", "/orqen:review": "TESTING", "/orqen:approve": "DELIVERY",
96
110
  };
111
+ /** The stage a run's lessons belong to: by its command, else by the state it ran in (the desktop app's "Start task" runs are "workflow"). */
112
+ const STATE_STAGE = {
113
+ NEW: "SUPPORT", SUPPORT: "SUPPORT", ANALYSIS: "ANALYSIS", WAITING_CLIENT: "ANALYSIS", DEVELOPMENT: "DEVELOPMENT", EXECUTION: "DEVELOPMENT",
114
+ TESTING: "TESTING", QA_REVIEW: "TESTING", VERIFICATION: "TESTING", CODE_REVIEW: "DELIVERY", DELIVERY: "DELIVERY",
115
+ };
116
+ const stageOfRun = (rec) => STAGE_OF[rec?.command ?? ""] ?? STATE_STAGE[rec?.state_before ?? ""] ?? "GENERAL";
97
117
  const STEP_OF = { "/orqen:support": "support", "/orqen:analyze": "analyze" };
98
118
  /** The desktop app's run log: runs, verdicts and what the person said was wrong. */
99
119
  export function readFeedback(repo) {
@@ -124,7 +144,11 @@ export function readFeedback(repo) {
124
144
  }
125
145
  export async function learnCommand(args) {
126
146
  const a = [...args];
127
- const apply = takeBool(a, "apply");
147
+ const applyArg = takeFlag(a, "apply");
148
+ const apply = applyArg !== undefined;
149
+ const only = applyArg || undefined; // --apply <run>: just that note
150
+ const discard = takeFlag(a, "discard");
151
+ const json = takeBool(a, "json");
128
152
  const toEval = takeFlag(a, "to-eval");
129
153
  const repo = gitRoot();
130
154
  const { runs, verdicts } = readFeedback(repo);
@@ -132,6 +156,16 @@ export async function learnCommand(args) {
132
156
  return caseFromRun(repo, toEval, runs, verdicts);
133
157
  const doneFile = join(repo, "orqen", "state", "app-chat", "learned.json");
134
158
  const done = new Set(existsSync(doneFile) ? JSON.parse(readFileSync(doneFile, "utf8")) : []);
159
+ const saveDone = () => { mkdirSync(join(repo, "orqen", "state", "app-chat"), { recursive: true }); writeFileSync(doneFile, JSON.stringify([...done], null, 2)); };
160
+ if (discard) {
161
+ if (!verdicts.has(discard))
162
+ throw new Error(`Run ${discard} has no feedback in orqen/state/app-chat/runs.jsonl`);
163
+ done.add(discard);
164
+ saveDone();
165
+ return console.log(json ? JSON.stringify({ ok: true, discarded: discard }) : `✔ Note of ${discard} dropped: it will not become a lesson.`);
166
+ }
167
+ if (json)
168
+ return console.log(JSON.stringify(learnState(repo, runs, verdicts, done), null, 2));
135
169
  const byCommand = new Map();
136
170
  const fresh = [];
137
171
  for (const v of verdicts.values()) {
@@ -140,9 +174,11 @@ export async function learnCommand(args) {
140
174
  const n = byCommand.get(cmd) ?? { up: 0, down: 0 };
141
175
  n[v.verdict]++;
142
176
  byCommand.set(cmd, n);
143
- if (rec && v.verdict === "down" && v.note && !done.has(v.run))
177
+ if (rec && v.verdict === "down" && v.note && !done.has(v.run) && (!only || v.run === only))
144
178
  fresh.push({ rec, v });
145
179
  }
180
+ if (only && !fresh.length)
181
+ throw new Error(`Run ${only} has no pending note (marked wrong, with what was wrong, not applied yet).`);
146
182
  if (!byCommand.size) {
147
183
  console.log("No feedback yet: mark runs with ✓ / ✗ in the desktop app's chat.");
148
184
  return;
@@ -165,7 +201,7 @@ export async function learnCommand(args) {
165
201
  mkdirSync(dir, { recursive: true });
166
202
  const touched = new Set();
167
203
  for (const { rec, v } of fresh) {
168
- const stage = STAGE_OF[rec.command] ?? "GENERAL";
204
+ const stage = stageOfRun(rec);
169
205
  const file = join(dir, `${stage}.md`);
170
206
  if (!existsSync(file))
171
207
  writeFileSync(file, `# Lessons for ${stage}\n\nWhat the team corrected in past runs. The agent reads this file in the ${stage} stage: keep it short and concrete; delete what no longer applies.\n\n`);
@@ -173,8 +209,7 @@ export async function learnCommand(args) {
173
209
  touched.add(`orqen/knowledge/lessons/${stage}.md`);
174
210
  done.add(v.run);
175
211
  }
176
- mkdirSync(join(repo, "orqen", "state", "app-chat"), { recursive: true });
177
- writeFileSync(doneFile, JSON.stringify([...done], null, 2));
212
+ saveDone();
178
213
  console.log(`\nUpdated: ${[...touched].join(", ")}. Review them and commit: the whole team's agents learn from them.`);
179
214
  }
180
215
  /** A run marked wrong → orqen/evals/<key>-<step>.yaml with the ticket as it is now, for the person to finish the expectations. */
@@ -216,3 +251,98 @@ export function lessonsFor(repo, state) {
216
251
  const capped = text.length > 6000 ? `${text.slice(0, 6000)}\n…` : text;
217
252
  return `## Team lessons for this stage (orqen/knowledge/lessons/${state}.md)\nCorrections from past runs. Follow them unless the person says otherwise.\n\n${capped.replace(/^# .*\n+/, "")}`;
218
253
  }
254
+ /** Where the desktop app (and `orqen run record`) logs the agent runs of each worq and the person's verdicts. */
255
+ export const runsFile = (repo) => join(repo, "orqen", "state", "app-chat", "runs.jsonl");
256
+ function appendRun(repo, rec) {
257
+ mkdirSync(join(repo, "orqen", "state", "app-chat"), { recursive: true });
258
+ appendFileSync(runsFile(repo), JSON.stringify(rec) + "\n");
259
+ }
260
+ const nowSecs = () => String(Math.floor(Date.now() / 1000));
261
+ const readArg = (v) => v === "-" ? readFileSync(0, "utf8") : existsSync(v) ? readFileSync(v, "utf8") : v;
262
+ /** `orqen run record <file|->`: one agent run of a worq, as any tool that runs agents logs it (the desktop app does). */
263
+ export function runCommand(args) {
264
+ const [sub, src] = args;
265
+ if (sub !== "record" || !src)
266
+ throw new Error("Usage: orqen run record <run.json|-> (JSON: run, key, command, state_before, secs, cost, agent, model…)");
267
+ const rec = JSON.parse(src === "-" ? readFileSync(0, "utf8") : readFileSync(src, "utf8"));
268
+ if (typeof rec.run !== "string" || typeof rec.key !== "string")
269
+ throw new Error("The run needs \"run\" (its id) and \"key\" (the worq).");
270
+ appendRun(gitRoot(), { ...rec, type: "run", ts: rec.ts ?? nowSecs() });
271
+ }
272
+ /** `orqen feedback <run> up|down [--note <text|->]`: the person says whether a run was right; a note says what was wrong. */
273
+ export function feedbackCommand(args) {
274
+ const a = [...args];
275
+ const noteArg = takeFlag(a, "note");
276
+ const [run, verdict] = a;
277
+ if (!run || (verdict !== "up" && verdict !== "down" && verdict !== "note"))
278
+ throw new Error("Usage: orqen feedback <run> up|down [--note <text|->] · orqen feedback <run> note <text|->");
279
+ const repo = gitRoot();
280
+ const key = readFeedback(repo).runs.get(run)?.key;
281
+ const text = verdict === "note" ? readArg(a[2] ?? "") : noteArg !== undefined ? readArg(noteArg) : "";
282
+ if (verdict !== "note")
283
+ appendRun(repo, { type: "feedback", run, ts: nowSecs(), key, verdict });
284
+ if (text.trim())
285
+ appendRun(repo, { type: "feedback-note", run, ts: nowSecs(), key, text: text.trim() });
286
+ }
287
+ /** Time and cost of a worq's agent runs (from the run log), in total and by the stage they ran in. */
288
+ export function runUsage(repo, key) {
289
+ const { runs, verdicts } = readFeedback(repo);
290
+ const total = { runs: 0, secs: 0, cost: 0, up: 0, down: 0 };
291
+ const byState = {};
292
+ for (const r of runs.values()) {
293
+ if (r.key !== key)
294
+ continue;
295
+ const x = r;
296
+ total.runs++;
297
+ total.secs += x.secs ?? 0;
298
+ total.cost += x.cost ?? 0;
299
+ const st = (byState[r.state_before ?? "?"] ??= { runs: 0, secs: 0, cost: 0 });
300
+ st.runs++;
301
+ st.secs += x.secs ?? 0;
302
+ st.cost += x.cost ?? 0;
303
+ const v = verdicts.get(r.run)?.verdict;
304
+ if (v)
305
+ total[v]++;
306
+ }
307
+ return total.runs ? { ...total, secs: Math.round(total.secs), cost: Math.round(total.cost * 100) / 100, by_state: byState } : undefined;
308
+ }
309
+ /** `orqen eval` runs so far (orqen/state/evals/history.jsonl). */
310
+ export function evalHistory(repo) {
311
+ const f = join(repo, "orqen", "state", "evals", "history.jsonl");
312
+ if (!existsSync(f))
313
+ return [];
314
+ return readFileSync(f, "utf8").split(/\r?\n/).filter((l) => l.trim()).flatMap((l) => { try {
315
+ return [JSON.parse(l)];
316
+ }
317
+ catch {
318
+ return [];
319
+ } });
320
+ }
321
+ /** What `orqen learn --json` says: feedback by step, the notes waiting to become lessons, the lessons of each stage and the evals. */
322
+ function learnState(repo, runs, verdicts, done) {
323
+ const byCommand = new Map();
324
+ const byStage = new Map();
325
+ const notes = [];
326
+ for (const v of verdicts.values()) {
327
+ const rec = runs.get(v.run);
328
+ const cmd = rec?.command ?? "chat";
329
+ const c = byCommand.get(cmd) ?? { command: cmd, up: 0, down: 0 };
330
+ c[v.verdict]++;
331
+ byCommand.set(cmd, c);
332
+ const stage = stageOfRun(rec);
333
+ const st = byStage.get(stage) ?? { up: 0, down: 0 };
334
+ st[v.verdict]++;
335
+ byStage.set(stage, st);
336
+ if (rec && v.verdict === "down" && v.note && !done.has(v.run))
337
+ notes.push({ run: v.run, key: rec.key, command: cmd, stage, note: v.note, ts: rec.ts });
338
+ }
339
+ const dir = join(repo, "orqen", "knowledge", "lessons");
340
+ const lessons = existsSync(dir) ? readdirSync(dir).filter((f) => f.endsWith(".md")).map((f) => {
341
+ const text = readFileSync(join(dir, f), "utf8");
342
+ return { stage: f.replace(/\.md$/, ""), count: text.split(/\r?\n/).filter((l) => /^\s*[-*] /.test(l)).length, updated: statSync(join(dir, f)).mtime.toISOString(), file: `orqen/knowledge/lessons/${f}` };
343
+ }) : [];
344
+ return {
345
+ by_command: [...byCommand.values()], by_stage: [...byStage].map(([stage, n]) => ({ stage, ...n })),
346
+ notes, lessons, evals: evalHistory(repo).slice(-20),
347
+ };
348
+ }