@telpin-sistemas/orqen 0.1.13 → 0.1.15

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
+ }
@@ -2,7 +2,7 @@
2
2
  import { ejecutar, partirComando } from "../lib/proc.js";
3
3
  import { providerEnv, saveProviders, providerFile } from "../lib/provider-credentials.js";
4
4
  import { stageGuideFile } from "../lib/stage-guides.js";
5
- import { lessonsFor } from "./eval.js";
5
+ import { lessonsFor, runUsage } from "./eval.js";
6
6
  import { execFileSync } from "node:child_process";
7
7
  import { readFileSync } from "node:fs";
8
8
  import { userInfo } from "node:os";
@@ -15,12 +15,24 @@ import { envWithLegacy } from "../connectors/legacy.js";
15
15
  import { DRY_RUN_COMMANDS, DryRun } from "../workflow/dry-run.js";
16
16
  import { OpenSpecCli } from "../workflow/openspec.js";
17
17
  import { Process } from "../workflow/process.js";
18
+ import { whoIs } from "../workflow/board.js";
18
19
  import { Store } from "../workflow/store.js";
19
20
  import { GitWorkspace } from "../workflow/workspace.js";
20
- export const WORKFLOW_COMMANDS = ["list", "qa", "approve", "merged", "cancel", "new_worq", "new-worq", "pending", "support", "analyze", "ask", "conversation", "lane", "take", "complete", "pr", "review", "code-review", "schema", "block", "release", "search", "status", "worqs", "worq", "cycle", "connectors", "doctor", "report", "comments", "comment"];
21
+ /** The bot profiles assigned to this stage of this project (none when the person has none, or their file is unreadable). */
22
+ async function stageBots(repoPath, state) {
23
+ try {
24
+ const { botsFor, readBots } = await import("../lib/bots.js");
25
+ const { mainWorktree } = await import("../workflow/config.js");
26
+ return botsFor(readBots(), mainWorktree(repoPath), state);
27
+ }
28
+ catch {
29
+ return [];
30
+ }
31
+ }
32
+ export const WORKFLOW_COMMANDS = ["list", "qa", "approve", "merged", "cancel", "new_worq", "new-worq", "pending", "support", "analyze", "ask", "conversation", "lane", "take", "complete", "pr", "review", "code-review", "schema", "block", "release", "search", "status", "worqs", "worq", "cycle", "connectors", "doctor", "report", "comments", "comment", "gate", "whoami", "watch"];
21
33
  /** What people run: the 9 steps (as /orqen:* commands in their agent) and the CLI commands meant for a person. */
22
34
  export const WORKFLOW_HELP = `The 9 steps (run the /orqen:* commands in your agent: it calls the CLI for you):
23
- 1 /orqen:list requests orqen list requests [--json] [--all] Everyone's work list, by role (takes nothing)
35
+ 1 /orqen:list requests orqen list requests [--json] [--all] [--mine] Everyone's work list, by role (--mine: only your roles)
24
36
  2 /orqen:support <KEY> First-line support: answer the client or escalate to the analyst
25
37
  3 /orqen:analyze <KEY> Analysis with the analyst: criteria, lane, spec and the issue
26
38
  4 /orqen:list issues orqen list issues [--json] Development queue (free, taken, came back)
@@ -34,11 +46,16 @@ Request commands for people:
34
46
  ask <KEY> <question> Ask the requester on their ticket from any stage (/orqen:ask in the agent)
35
47
  conversation <KEY> Refresh and show the request comments saved in the worq's conversation.json
36
48
  status [KEY] [--json] Where a request is, who acts and what comes next (no KEY: all of them)
49
+ gate <KEY> [--json] The decision a person has to make on it now: what, who, the evidence and the commands that make it
50
+ whoami [--json] Who you are on the team: your name and roles (workflow.people in orqen/config.yaml)
51
+ watch [--json] [--every S] [--since 2h] [--once] Follow the worqs: each move as it happens (--json: one JSON line per event, for tools and CI)
37
52
  worqs [--all] [--json] The worqs on this machine: orqen's unit of work, one per request (request + issue + branch + PR + record)
38
53
  worq <KEY> [--json] One worq: state, request, issue, branch, PR and the files of its record in orqen/worqs/<KEY>/
39
54
  merged <KEY> [--person N] Confirm the hand merge of an approved PR when orqen cannot read it from GitHub
40
- new_worq "<title>" <brief.json|-> Worq with no request: creates its issue in the connector, skips support and analysis, born in DEVELOPMENT
55
+ new_worq "<title>" <brief.json|-> [--json] Worq with no request: creates its issue in the connector, skips support and analysis, born in DEVELOPMENT
41
56
  --issue <KEY> Take an issue that already exists instead of creating one (the title defaults to the issue's)
57
+ <brief.json|-> Alone: the title goes in the brief ("title"), as orqen-studio sends it
58
+ {title, description} Only that: born in ANALYSIS, then /orqen:analyze asks the person what is missing
42
59
  cancel <KEY> --reason T Close the request without delivering it: closes the PR unmerged, comments both tickets (CANCELLED)
43
60
  release <KEY> Free a request held by an agent that is no longer working on it
44
61
  comments <KEY> [--json] Read the request and its conversation with the client
@@ -71,8 +88,9 @@ Older names (still work, with a notice): pending → list requests · qa → rev
71
88
  JSON for tools (orqen-studio):
72
89
  status [KEY] --json · list requests|issues|prs --json · usage --json · tutorial --step <n> --json
73
90
  spec [KEY|change] --json [--dir <worktree>] the spec in the neutral model of src/sdd (any SDD tool)
74
- connectors get|check <json>|set <json>|general-get|general-set [--json]
75
- connectors github-choices <json|-> <requests|issues> <repositories|projects|statuses>`;
91
+ connectors get|check <json> [--matches]|set <json>|general-get|general-set [--json] (check --matches: requests the filter would bring, count + first 3)
92
+ connectors github-choices <json|-> <requests|issues> <repositories|projects|statuses>
93
+ <complete|pr|approve|cancel|new_worq> … --dry-run --json {"dry_run","ok","plan":[{kind,text}],"output","errors"}; gate actions that take it say "dry_run": true`;
76
94
  /** The person at this machine: Git's user.name for this repository, otherwise the system user. */
77
95
  export function quienSoy(repo) {
78
96
  try {
@@ -89,6 +107,9 @@ export function quienSoy(repo) {
89
107
  }
90
108
  }
91
109
  export async function runWorkflow(cmd, rest) {
110
+ // --dry-run --json (tools such as orqen-studio): one JSON with the plan and what the command said, nothing else on stdout
111
+ if (rest.includes("--dry-run") && rest.includes("--json"))
112
+ return dryRunJson(cmd, rest);
92
113
  let dry;
93
114
  try {
94
115
  await runCommand(cmd, rest, (d) => { dry = d; });
@@ -97,7 +118,53 @@ export async function runWorkflow(cmd, rest) {
97
118
  dry?.finish();
98
119
  } // what it would have done, and the temporary copy is deleted
99
120
  }
121
+ /** Options the workflow commands take. One that is not here is a typo, and ignoring it can do the wrong thing (`--chnges` approves; `--isue` creates a new issue). */
122
+ const KNOWN_OPTIONS = new Set(["agent", "all", "analyst", "apply", "changes", "comment", "dir", "dry-run", "every", "force", "issue", "json", "loop", "matches", "mine", "once", "person", "reason", "report", "since", "step", "title", "verdict"]);
123
+ /**
124
+ * `<command> --dry-run --json`: {"dry_run": true, "ok", "plan": [{kind, text}], "output": [lines], "errors": [lines]}.
125
+ * `ok` is false when the command would fail (its checks did not pass): `errors` says why and `plan` is what it got to do.
126
+ */
127
+ async function dryRunJson(cmd, rest) {
128
+ let dry;
129
+ const output = [], errors = [];
130
+ const { log, error } = console;
131
+ const keep = (to) => (...a) => { for (const l of a.map((x) => typeof x === "string" ? x : JSON.stringify(x)).join(" ").split("\n"))
132
+ if (l.trim())
133
+ to.push(l); };
134
+ console.log = keep(output);
135
+ console.error = keep(errors);
136
+ const before = process.exitCode;
137
+ process.exitCode = 0;
138
+ let plan = [];
139
+ try {
140
+ await runCommand(cmd, rest, (d) => { dry = d; });
141
+ }
142
+ catch (e) {
143
+ errors.push(e.message);
144
+ process.exitCode = 1;
145
+ }
146
+ finally {
147
+ const d = dry;
148
+ if (d) {
149
+ plan = d.report();
150
+ d.finish(() => { });
151
+ }
152
+ console.log = log;
153
+ console.error = error;
154
+ }
155
+ const ok = !process.exitCode && !!dry;
156
+ process.exitCode = before; // the JSON says whether it would work; the call itself worked
157
+ // the line every dry run prints first is for people
158
+ const said = output.filter((l) => !l.startsWith("DRY RUN:"));
159
+ console.log(JSON.stringify({ dry_run: true, command: cmd, ok, plan, output: said, errors }, null, 2));
160
+ }
100
161
  async function runCommand(cmd, rest, onDryRun) {
162
+ const unknown = rest.filter((a) => /^--[A-Za-z]/.test(a) && !KNOWN_OPTIONS.has(a.slice(2).split("=")[0]));
163
+ if (unknown.length) {
164
+ console.error(`✘ Unknown option${unknown.length > 1 ? "s" : ""}: ${unknown.join(", ")}. Nothing was run. Valid options: ${[...KNOWN_OPTIONS].map((o) => `--${o}`).join(", ")}.`);
165
+ process.exitCode = 1;
166
+ return;
167
+ }
101
168
  const cfg = loadConfig();
102
169
  warnLegacy(cfg);
103
170
  const connectors = buildConnectors(cfg.connectors);
@@ -169,6 +236,9 @@ async function runCommand(cmd, rest, onDryRun) {
169
236
  : "> **Unattended mode: nobody can answer you.** Do not assume. If a doubt changes the outcome, run " +
170
237
  `\`orqen block ${key} "<specific question>"\`; a person answers it on the ticket.`,
171
238
  "",
239
+ ...(ctx.no_client ? [`> **No client: this worq was started by the team.** ${ctx.requester ?? "The person you are working with"} is the requester. ` +
240
+ "Ask them directly here whatever the description leaves open (one question at a time, with your recommendation); " +
241
+ `do not use \`orqen ask\` or wait for answers on the ticket.`, ""] : []),
172
242
  guide(s),
173
243
  "",
174
244
  // the feedback loop: what the team corrected in this stage before (orqen learn --apply)
@@ -244,7 +314,13 @@ async function runCommand(cmd, rest, onDryRun) {
244
314
  console.log(` ${b.work.padEnd(12)} ${(b.lane ?? "").padEnd(7)} ${b.pr}\n${"".padEnd(15)}${b.qa ? `QA ${b.qa} · ` : ""}review: ${b.review?.status}${b.review?.detail ? ` (${b.review.detail})` : ""}${ciText(b.checks)}`);
245
315
  return;
246
316
  }
247
- const board = await flow.board(all);
317
+ const mine = has("mine");
318
+ let board = await flow.board(all);
319
+ // --mine: only what waits for one of the roles of the person at this machine (workflow.people)
320
+ if (mine) {
321
+ const me2 = whoIs(cfg.people, me);
322
+ board = board.filter((b) => me2.roles.includes(b.role));
323
+ }
248
324
  if (what === "issues") {
249
325
  const q = board.filter((b) => b.state === "DEVELOPMENT");
250
326
  if (json)
@@ -312,20 +388,34 @@ async function runCommand(cmd, rest, onDryRun) {
312
388
  }
313
389
  case "new-worq":
314
390
  case "new_worq": {
391
+ let json = false;
315
392
  try {
316
393
  const issueFlag = flag("issue");
317
394
  const existing = issueFlag ? toKey(issueFlag) : undefined;
395
+ json = has("json");
318
396
  // with --issue the title is optional (the issue's is used): orqen new_worq --issue GH-12 brief.json
319
- const [title, src] = existing && rest.length === 1 ? ["", rest[0]] : [rest[0] ?? "", rest[1]];
320
- if ((!title && !existing) || !src)
321
- throw new Error('Usage: orqen new_worq "<title>" <brief.json|-> [--person NAME] or orqen new_worq --issue <KEY> ["<title>"] <brief.json|-> (brief: {"description", "acceptance_criteria": [...], "plan": [...], "estimated_hours"})');
397
+ // with only the brief, its "title" is the worq's (orqen-studio sends everything on stdin: no quoting of the title on Windows)
398
+ const usage = 'Usage: orqen new_worq "<title>" <brief.json|-> [--person NAME] or orqen new_worq <brief.json|-> or orqen new_worq --issue <KEY> ["<title>"] <brief.json|-> (brief: {"title", "description", "acceptance_criteria": [...], "plan": [...], "estimated_hours"})';
399
+ let [title, src] = rest.length === 1 ? ["", rest[0]] : [rest[0] ?? "", rest[1]];
400
+ if (!src)
401
+ throw new Error(usage);
322
402
  const raw = JSON.parse(src === "-" ? readFileSync(0, "utf8") : readFileSync(src, "utf8"));
403
+ if (!title && typeof raw?.title === "string")
404
+ title = raw.title;
405
+ if (!title.trim() && !existing)
406
+ throw new Error(usage);
323
407
  const r = await flow.newWorq(title, raw, me || agent, existing);
408
+ // --json: for orqen-studio's "New Worq" (the worq it has to open, or the error to show in the form)
409
+ if (json)
410
+ return console.log(JSON.stringify({ ok: true, ...r, taken: !!existing }));
324
411
  console.log(`✔ ${r.key} ${existing ? "taken" : "created"} in ${r.state}: issue ${r.url} (no client request) · worq: ${r.dir}/`);
325
- console.log(` Next: /orqen:implement ${r.key}`);
412
+ console.log(` Next: ${"next" in r ? r.next : `/orqen:implement ${r.key}`}`);
326
413
  }
327
414
  catch (e) {
328
- console.error(`✘ ${e.message}`);
415
+ if (json)
416
+ console.log(JSON.stringify({ ok: false, error: e.message }));
417
+ else
418
+ console.error(`✘ ${e.message}`);
329
419
  process.exitCode = 1;
330
420
  }
331
421
  return;
@@ -345,6 +435,77 @@ async function runCommand(cmd, rest, onDryRun) {
345
435
  }
346
436
  return;
347
437
  }
438
+ case "gate": {
439
+ const json = has("json");
440
+ try {
441
+ const key = toKey(rest[0]);
442
+ if (!key)
443
+ throw new Error("Usage: orqen gate <KEY> [--json]");
444
+ const g = flow.gate(key);
445
+ const me2 = whoIs(cfg.people, me);
446
+ // whether the person at this machine is the one who decides (by role; the approvers lists, if any, still apply on the tickets)
447
+ const yours = g.waiting && !g.outside && me2.roles.includes(g.role);
448
+ if (json)
449
+ return console.log(JSON.stringify({ ...g, yours, me: me2.name }, null, 2));
450
+ if (!g.waiting)
451
+ return console.log(`${g.key} (${g.state}): nobody has to decide anything now.${g.what ? ` ${g.what}.` : ""}`);
452
+ console.log(`${g.key} (${g.state}) · ${g.role}${g.who ? ` (${g.who.join(", ")})` : ""}${yours ? " · it is yours" : ""}`);
453
+ console.log(` ${g.what}`);
454
+ for (const e of g.evidence)
455
+ console.log(` ${e.ok === true ? "✔" : e.ok === false ? "✘" : "?"} ${e.detail ?? e.label}`);
456
+ for (const a of g.actions)
457
+ console.log(` → ${a.label}: ${a.kind === "cli" ? `orqen ${a.cli.join(" ")}${a.text ? ` (${a.text}, on stdin)` : ""}` : a.agent}`);
458
+ }
459
+ catch (e) {
460
+ if (json)
461
+ console.log(JSON.stringify({ error: e.message }));
462
+ else
463
+ console.error(`✘ ${e.message}`);
464
+ process.exitCode = 1;
465
+ }
466
+ return;
467
+ }
468
+ case "watch": {
469
+ // every few seconds, the new events of the local record (what `orqen cycle`, the agents and the people do here)
470
+ const json = has("json");
471
+ const every = Math.max(1, Number(flag("every") ?? 5));
472
+ const sinceArg = flag("since");
473
+ const once = has("once");
474
+ const me2 = whoIs(cfg.people, me);
475
+ let last = sinceArg ? new Date(/^\d+[mhd]$/.test(sinceArg) ? Date.now() - Number(sinceArg.slice(0, -1)) * { m: 60e3, h: 3600e3, d: 86400e3 }[sinceArg.slice(-1)] : sinceArg).toISOString() : new Date().toISOString();
476
+ const tick = () => {
477
+ const fresh = [];
478
+ for (const item of store.all())
479
+ for (const ev of store.events(item.key))
480
+ if (ev.ts > last)
481
+ fresh.push({ key: item.key, title: item.title, ev });
482
+ fresh.sort((a, b) => a.ev.ts.localeCompare(b.ev.ts));
483
+ for (const { key, title, ev } of fresh) {
484
+ const item = store.get(key);
485
+ const role = item ? flow.boardItem(item).role : undefined;
486
+ const forMe = !!role && ["support", "analyst", "qa", "senior"].includes(role) && me2.roles.includes(role) && ev.to === item?.state;
487
+ if (json)
488
+ console.log(JSON.stringify({ key, title, ...ev, role, for_me: forMe }));
489
+ else
490
+ console.log(`${ev.ts.slice(11, 16)} ${key.padEnd(10)} ${ev.from === ev.to ? ev.to : `${ev.from} → ${ev.to}`} ${ev.detail}${ev.person ? ` (${ev.person})` : ""}${forMe ? " ← yours" : ""}`);
491
+ last = ev.ts;
492
+ }
493
+ };
494
+ tick();
495
+ if (once)
496
+ return;
497
+ if (!json)
498
+ console.error(`Watching the worqs every ${every} s (Ctrl+C to stop)…`);
499
+ await new Promise(() => { setInterval(tick, every * 1000); });
500
+ return;
501
+ }
502
+ case "whoami": {
503
+ const w = whoIs(cfg.people, me);
504
+ if (has("json"))
505
+ return console.log(JSON.stringify(w));
506
+ console.log(`${w.name ?? "(no git user.name)"} · ${w.roles.length ? w.roles.join(", ") : "no roles"}${!w.configured ? " (workflow.people is not set: everyone does everything)" : !w.listed ? " (not listed in workflow.people of orqen/config.yaml)" : ""}`);
507
+ return;
508
+ }
348
509
  case "merged": {
349
510
  try {
350
511
  const key = toKey(rest[0]);
@@ -495,7 +656,8 @@ async function runCommand(cmd, rest, onDryRun) {
495
656
  return dispatch();
496
657
  }
497
658
  try {
498
- const reason = flag("reason") ?? "";
659
+ const reasonArg = flag("reason") ?? "";
660
+ const reason = reasonArg === "-" ? readFileSync(0, "utf8") : reasonArg;
499
661
  const reportFile = flag("report");
500
662
  const key = toKey(rest[0]);
501
663
  const decision = rest[1] ?? "";
@@ -574,7 +736,7 @@ async function runCommand(cmd, rest, onDryRun) {
574
736
  const files = item.recovered ? [] : worqFiles(join(cfg.factoryDir, item.key));
575
737
  const events = store.events(item.key);
576
738
  if (json)
577
- return console.log(JSON.stringify({ ...w, files, events: events.slice(-10) }, null, 2));
739
+ return console.log(JSON.stringify({ ...w, files, events: events.slice(-10), usage: runUsage(cfg.repoPath, item.key) }, null, 2));
578
740
  console.log(`Worq ${w.key}${w.title ? ` — ${w.title}` : ""}`);
579
741
  console.log(` State: ${w.state}${w.round > 1 ? ` (round ${w.round})` : ""}${w.lane ? ` · lane ${w.lane}` : ""}${w.route && w.route !== "development" ? ` · ${w.route}` : ""}`);
580
742
  if (w.next[0])
@@ -612,7 +774,7 @@ async function runCommand(cmd, rest, onDryRun) {
612
774
  const k = toKey(rest[0]);
613
775
  const item = flow.item(k) ?? await flow.peek(k);
614
776
  const b = item ? flow.boardItem(item) : undefined;
615
- return console.log(JSON.stringify(item ? { ...item, role: b.role, next: b.next, qa_status: b.qa, returned: b.returned, events: store.events(item.key) } : null, null, 2));
777
+ return console.log(JSON.stringify(item ? { ...item, role: b.role, next: b.next, qa_status: b.qa, returned: b.returned, events: store.events(item.key), usage: runUsage(cfg.repoPath, item.key), bots: item ? await stageBots(cfg.repoPath, item.state) : [] } : null, null, 2));
616
778
  }
617
779
  return console.log(JSON.stringify(store.all().map((r) => ({
618
780
  key: r.key, title: r.title ?? r.artifacts?.ANALYSIS?.summary, state: r.state, issue: r.issue, lane: r.lane, route: r.route, round: r.round, branch: r.branch || undefined,
@@ -696,7 +858,8 @@ async function runCommand(cmd, rest, onDryRun) {
696
858
  if (rest[0] === "check") {
697
859
  const { checkDraft, parseDraft } = await import("../lib/connectors-edit.js");
698
860
  const { leerEnv } = await import("../lib/env.js");
699
- const result = await checkDraft(parseDraft(draftInput()), providerEnv(cfg.repoPath));
861
+ const matches = has("matches");
862
+ const result = await checkDraft(parseDraft(draftInput()), providerEnv(cfg.repoPath), { matches });
700
863
  return console.log(JSON.stringify({ connectors: result }, null, 2));
701
864
  }
702
865
  if (rest[0] === "set") {
@@ -35,14 +35,25 @@ export class AsanaTracker {
35
35
  gid = (key) => idOf(this.s.prefix, key);
36
36
  needProject() { if (!this.s.project)
37
37
  throw new Error("Asana connector without project (conectores.*.proyecto: project gid)"); return this.s.project; }
38
+ /** Every task of a listing: Asana pages them (100 at most) and a request past the first page would never be seen. */
39
+ async allPages(path) {
40
+ const out = [];
41
+ let offset;
42
+ do {
43
+ const page = await this.requestPage("GET", offset ? `${path}&offset=${encodeURIComponent(offset)}` : path);
44
+ out.push(...(page.data ?? []));
45
+ offset = page.next_page?.offset;
46
+ } while (offset);
47
+ return out;
48
+ }
38
49
  async pending() {
39
- const tasks = await this.req("GET", `/projects/${this.needProject()}/tasks?completed_since=now&limit=100&opt_fields=tags.name`);
50
+ const tasks = await this.allPages(`/projects/${this.needProject()}/tasks?completed_since=now&limit=100&opt_fields=tags.name`);
40
51
  const tag = this.s.tag.toLowerCase();
41
52
  return tasks.filter((t) => (t.tags ?? []).some((g) => g.name?.toLowerCase() === tag)).map((t) => keyOf(this.s.prefix, t.gid));
42
53
  }
43
54
  /** Text search inside the project (name and notes). */
44
55
  async search(query) {
45
- const tasks = await this.req("GET", `/projects/${this.needProject()}/tasks?limit=100&opt_fields=name,notes`);
56
+ const tasks = await this.allPages(`/projects/${this.needProject()}/tasks?limit=100&opt_fields=name,notes`);
46
57
  const q = query.toLowerCase();
47
58
  return tasks.filter((t) => `${t.name} ${t.notes ?? ""}`.toLowerCase().includes(q)).map((t) => keyOf(this.s.prefix, t.gid));
48
59
  }
@@ -227,9 +227,18 @@ export class GithubTracker {
227
227
  }
228
228
  async create(t) {
229
229
  const i = await this.req("POST", "/repos/{repo}/issues", { title: t.title.slice(0, 250), body: toMarkdown(t.description), labels: [...this.s.labels, ...(t.labels ?? [])] });
230
- if (this.s.project)
231
- await this.addToProject(i.node_id);
232
- return keyOf(this.s.prefix, i.number);
230
+ const key = keyOf(this.s.prefix, i.number);
231
+ if (this.s.project) {
232
+ // the issue exists already: losing its key here would leave it orphaned and the next attempt would create a second one. The
233
+ // project column is set again by the first transition (transition() adds the issue to the project if it is not there).
234
+ try {
235
+ await this.addToProject(i.node_id);
236
+ }
237
+ catch (e) {
238
+ console.error(`[orqen] warning: ${key} was created but could not be added to the GitHub project (${e.message.split("\n")[0]}); it is added at its next move`);
239
+ }
240
+ }
241
+ return key;
233
242
  }
234
243
  /** Without a project: "closed"/"open" close or reopen the issue. With a project: moves it to that option of the field (Status). */
235
244
  async transition(key, name) {