@telpin-sistemas/orqen 0.1.11 → 0.1.13

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,123 @@
1
+ /**
2
+ * `orqen doctor`: everything the flow needs on this machine and in this repository, checked at once, each problem with what to do.
3
+ * The same things otherwise show up one at a time, in the middle of a stage (gh missing at `orqen pr`, a base branch that is not on
4
+ * origin, a connector without credentials…).
5
+ */
6
+ import { spawnSync } from "node:child_process";
7
+ import { existsSync, readdirSync } from "node:fs";
8
+ import { join } from "node:path";
9
+ import { existeConfig, leerConfig } from "../lib/config.js";
10
+ import { leerManifest } from "../lib/kit.js";
11
+ import { VERSION_CLI } from "../lib/system.js";
12
+ import { ghFailure } from "../workflow/workspace.js";
13
+ export const systemRunner = (cmd, args, o = {}) => {
14
+ const r = spawnSync(cmd, args, { cwd: o.cwd, shell: o.shell, encoding: "utf8", windowsHide: true, timeout: 30_000 });
15
+ return { code: r.status, stdout: r.stdout ?? "", stderr: r.stderr ?? "", error: r.error };
16
+ };
17
+ export async function diagnose(cfg, connectors, run = systemRunner) {
18
+ const repo = cfg.repoPath;
19
+ const out = [];
20
+ const add = (name, status, detail, fix) => out.push({ name, status, detail, ...(fix ? { fix } : {}) });
21
+ // --- repository
22
+ const origin = run("git", ["remote", "get-url", "origin"], { cwd: repo });
23
+ if (origin.error?.code === "ENOENT")
24
+ add("git", "fail", "git is not installed or is not in the PATH", "Install git and open a new terminal");
25
+ else if (origin.code !== 0)
26
+ add("git", "fail", "the repository has no origin remote: branches and PRs cannot be pushed", "git remote add origin <url>");
27
+ else
28
+ add("git", "ok", `origin: ${origin.stdout.trim()}`);
29
+ // --- orqen in the project
30
+ const installed = existeConfig(repo);
31
+ if (!installed)
32
+ add("orqen", "fail", "orqen is not installed in this repository (no orqen/config.yaml)", "orqen init");
33
+ else {
34
+ const kit = leerManifest(repo).kit;
35
+ if (kit === VERSION_CLI)
36
+ add("kit", "ok", `kit ${kit}, same as the CLI`);
37
+ else
38
+ add("kit", "warn", `the kit is ${kit} and the CLI ${VERSION_CLI}: the /orqen:* commands may not match the CLI`, "orqen update --no-cli");
39
+ }
40
+ // --- GitHub CLI: orqen pr, the senior's review, CI and merge detection
41
+ const gh = run("gh", ["auth", "status"], { cwd: repo });
42
+ if (gh.error || gh.code !== 0) {
43
+ const why = ghFailure(gh.error ?? Object.assign(new Error(gh.stderr || "gh failed"), { stderr: gh.stderr }));
44
+ add("gh", "fail", why, gh.error?.code === "ENOENT" ? "Install it from https://cli.github.com and open a new terminal" : "gh auth login");
45
+ }
46
+ else
47
+ add("gh", "ok", (gh.stdout + gh.stderr).split("\n").map((l) => l.trim()).find((l) => /logged in/i.test(l)) ?? "logged in");
48
+ // --- the branch PRs go to
49
+ if (origin.code === 0) {
50
+ const base = run("git", ["ls-remote", "--exit-code", "--heads", "origin", cfg.develBranch], { cwd: repo });
51
+ if (base.code === 0)
52
+ add("base branch", "ok", `${cfg.develBranch} exists on origin`);
53
+ else if (base.code === 2)
54
+ add("base branch", "fail", `the branch PRs go to (${cfg.develBranch}) does not exist on origin: orqen pr will refuse to open them`, `git push origin <branch>:${cfg.develBranch}, or set workflow.devel_branch in orqen/config.yaml`);
55
+ else
56
+ add("base branch", "warn", `could not check whether ${cfg.develBranch} exists on origin (${(base.stderr || "no answer").trim().split("\n")[0]})`);
57
+ }
58
+ // --- connectors
59
+ for (const role of ["requests", "issues"]) {
60
+ const t = connectors[role];
61
+ const name = role === "requests" ? "requests connector" : "issues connector";
62
+ if (!t) {
63
+ if (role === "requests")
64
+ add(name, "fail", "not configured: orqen has nowhere to read the requests from", "orqen connectors setup");
65
+ else
66
+ add(name, "ok", "not configured: development issues go to the requests connector");
67
+ continue;
68
+ }
69
+ let r;
70
+ try {
71
+ r = await t.check();
72
+ }
73
+ catch (e) {
74
+ r = { ok: false, detail: e.message.split("\n")[0] };
75
+ }
76
+ add(name, r.ok ? "ok" : "fail", `${t.label}: ${r.detail}`, r.ok ? undefined : "orqen connectors setup");
77
+ }
78
+ // --- CI: without it, the senior approves without knowing whether the tests pass on the PR
79
+ const wf = join(repo, ".github", "workflows");
80
+ const workflows = existsSync(wf) ? readdirSync(wf).filter((f) => /\.ya?ml$/i.test(f)) : [];
81
+ if (workflows.length)
82
+ add("CI", "ok", `${workflows.length} GitHub Actions workflow(s)`);
83
+ else
84
+ add("CI", "warn", "no GitHub Actions workflows: /orqen:approve cannot check that the tests pass on the PR", "Add a workflow in .github/workflows that runs the tests (if CI runs elsewhere, ignore this)");
85
+ // --- tests the testing stage runs
86
+ if (installed) {
87
+ let tests;
88
+ try {
89
+ tests = leerConfig(repo).entornos.tests;
90
+ }
91
+ catch (e) {
92
+ add("config", "fail", e.message.replace(/\n/g, " "), "Fix orqen/config.yaml and orqen/environment.yaml as the message says");
93
+ }
94
+ const inFile = { unitarios: "unit", integracion: "integration" }; // as written in orqen/environment.yaml
95
+ const set = Object.entries(tests ?? {}).filter(([, v]) => v).map(([k]) => inFile[k] ?? k);
96
+ if (set.length)
97
+ add("tests", "ok", `configured: ${set.join(", ")}`);
98
+ else if (tests)
99
+ add("tests", "warn", "no tests in orqen/environment.yaml: the testing stage has nothing to run", "Set tests.unit in orqen/environment.yaml");
100
+ }
101
+ // --- the agent that runs the stages unattended (orqen cycle, orqen eval)
102
+ const agent = cfg.agentCmd.trim().split(/\s+/)[0];
103
+ if (agent) {
104
+ const a = run(agent, ["--version"], { cwd: repo, shell: process.platform === "win32" });
105
+ if (a.error?.code === "ENOENT" || a.code === 127 || (process.platform === "win32" && a.code === 1 && /not recognized/i.test(a.stderr)))
106
+ add("agent", "warn", `${agent} (agent.command) is not in the PATH: orqen cycle and orqen eval cannot run it`, `Install ${agent} or change agent.command in orqen/config.yaml`);
107
+ else
108
+ add("agent", "ok", `${agent} ${a.stdout.trim().split("\n")[0]}`.trim());
109
+ }
110
+ return out;
111
+ }
112
+ const ICON = { ok: "✔", warn: "⚠", fail: "✘" };
113
+ export function printChecks(checks) {
114
+ const w = Math.max(...checks.map((c) => c.name.length));
115
+ for (const c of checks) {
116
+ console.log(`${ICON[c.status]} ${c.name.padEnd(w)} ${c.detail}`);
117
+ if (c.fix && c.status !== "ok")
118
+ console.log(` ${" ".repeat(w)} → ${c.fix}`);
119
+ }
120
+ const fails = checks.filter((c) => c.status === "fail").length, warns = checks.filter((c) => c.status === "warn").length;
121
+ console.log(fails ? `\n${fails} problem(s) to fix before using the flow${warns ? `, ${warns} warning(s)` : ""}.`
122
+ : warns ? `\nReady, with ${warns} warning(s).` : "\nEverything is ready.");
123
+ }
@@ -357,7 +357,7 @@ async function prepararOpenSpec(repo, agentes, herramientasPedidas, yes) {
357
357
  return { instalacion, version: versionFinal, herramientas };
358
358
  }
359
359
  function resumenPlan(plan, config) {
360
- const icono = { crear: pc.green("+"), actualizar: pc.yellow("~"), igual: gris("="), conflicto: pc.red("!") };
360
+ const icono = { crear: pc.green("+"), actualizar: pc.yellow("~"), igual: gris("="), conflicto: pc.red("!"), borrar: pc.red("-"), obsoleto: pc.yellow("?") };
361
361
  const filas = [
362
362
  `${pc.green("+")} ${ARCHIVO_CONFIG} ${gris("(the flow: project, connectors, workflow)")}`,
363
363
  `${pc.green("+")} ${ARCHIVO_ENTORNO} ${gris("(stack, how each part starts, tests)")}`,
@@ -215,15 +215,18 @@ export async function update(o) {
215
215
  if (!cambios.length)
216
216
  p.log.success(`The kit is up to date (v${VERSION_CLI})`);
217
217
  else {
218
- const icono = { crear: pc.green("+"), actualizar: pc.yellow("~"), conflicto: pc.red("!") };
219
- p.note(cambios.map((c) => `${icono[c.accion]} ${c.ruta}${c.accion === "conflicto" ? pc.red(" (local edits require review)") : ""}`).join("\n"), `Kit ${manifest.kit} → ${VERSION_CLI}`);
218
+ const icono = { crear: pc.green("+"), actualizar: pc.yellow("~"), conflicto: pc.red("!"), borrar: pc.red("-"), obsoleto: pc.yellow("?") };
219
+ const nota = { conflicto: pc.red(" (local edits require review)"), borrar: pc.dim(" (no longer in the kit)"), obsoleto: pc.yellow(" (no longer in the kit, but edited: kept)") };
220
+ p.note(cambios.map((c) => `${icono[c.accion]} ${c.ruta}${nota[c.accion] ?? ""}`).join("\n"), `Kit ${manifest.kit} → ${VERSION_CLI}`);
220
221
  if (await confirmar("Apply the kit updates?", true, yes)) {
221
222
  const res = await aplicar(repo, plan, (c) => resolverConflicto(c, yes));
222
223
  actualizarVersiones(repo, { kit: VERSION_CLI, cli: VERSION_CLI });
223
224
  const n = (a) => res.filter((r) => r.accion === a).length;
224
- p.log.success(`Kit v${VERSION_CLI}: ${n("crear")} created, ${n("actualizar")} updated, ${n("mantenido")} kept, ${n("guardado-al-lado")} to merge manually`);
225
+ p.log.success(`Kit v${VERSION_CLI}: ${n("crear")} created, ${n("actualizar")} updated, ${n("borrar")} deleted, ${n("mantenido")} kept, ${n("guardado-al-lado")} to merge manually`);
225
226
  for (const r of res.filter((r) => r.accion === "guardado-al-lado"))
226
227
  p.log.warn(`${r.ruta} → see ${r.detalle}`);
228
+ for (const r of res.filter((r) => r.accion === "obsoleto"))
229
+ p.log.warn(`${r.ruta} is no longer part of the kit and has local edits: it was kept, delete it when you no longer need it`);
227
230
  }
228
231
  }
229
232
  }
@@ -12,11 +12,12 @@ import { jsonSchema } from "../workflow/schemas.js";
12
12
  import { LANES, AGENT_STATES } from "../workflow/states.js";
13
13
  import { buildConnectors } from "../connectors/index.js";
14
14
  import { envWithLegacy } from "../connectors/legacy.js";
15
+ import { DRY_RUN_COMMANDS, DryRun } from "../workflow/dry-run.js";
15
16
  import { OpenSpecCli } from "../workflow/openspec.js";
16
17
  import { Process } from "../workflow/process.js";
17
18
  import { Store } from "../workflow/store.js";
18
19
  import { GitWorkspace } from "../workflow/workspace.js";
19
- export const WORKFLOW_COMMANDS = ["list", "qa", "approve", "merged", "cancel", "new_worq", "pending", "support", "analyze", "ask", "conversation", "lane", "take", "complete", "pr", "review", "code-review", "schema", "block", "release", "search", "status", "worqs", "worq", "cycle", "connectors", "comments", "comment"];
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"];
20
21
  /** What people run: the 9 steps (as /orqen:* commands in their agent) and the CLI commands meant for a person. */
21
22
  export const WORKFLOW_HELP = `The 9 steps (run the /orqen:* commands in your agent: it calls the CLI for you):
22
23
  1 /orqen:list requests orqen list requests [--json] [--all] Everyone's work list, by role (takes nothing)
@@ -37,11 +38,14 @@ Request commands for people:
37
38
  worq <KEY> [--json] One worq: state, request, issue, branch, PR and the files of its record in orqen/worqs/<KEY>/
38
39
  merged <KEY> [--person N] Confirm the hand merge of an approved PR when orqen cannot read it from GitHub
39
40
  new_worq "<title>" <brief.json|-> Worq with no request: creates its issue in the connector, skips support and analysis, born in DEVELOPMENT
41
+ --issue <KEY> Take an issue that already exists instead of creating one (the title defaults to the issue's)
40
42
  cancel <KEY> --reason T Close the request without delivering it: closes the PR unmerged, comments both tickets (CANCELLED)
41
43
  release <KEY> Free a request held by an agent that is no longer working on it
42
44
  comments <KEY> [--json] Read the request and its conversation with the client
43
45
  comment <KEY> <file|-> Reply to the client on the request (--person NAME)
44
46
  connectors [setup] Show and check the connectors (requests and issues), or set them up
47
+ doctor [--json] Check everything the flow needs at once (git, gh, base branch, connectors, CI, tests, agent), with what to do
48
+ report [--since YYYY-MM-DD|<n>d] [--json] How the work flowed: time to close by lane, where it waits, returns to development, estimate
45
49
  cycle [--loop] Unattended mode (cron/CI/server): agent stages only, never support or analysis
46
50
 
47
51
  Agent-only commands (the /orqen:* commands run them) and JSON for tools: orqen help internal`;
@@ -60,6 +64,8 @@ export const WORKFLOW_INTERNAL_HELP = `Agent-only commands (the /orqen:* command
60
64
  block <KEY> <reason> Escalate to a person on the ticket
61
65
  search <query> Search tickets (precedents, related work)
62
66
 
67
+ --dry-run (complete, pr, approve, cancel, new_worq): runs the command's checks and shows what it would do on the tickets, Git and the PR, without doing it
68
+
63
69
  Older names (still work, with a notice): pending → list requests · qa → review
64
70
 
65
71
  JSON for tools (orqen-studio):
@@ -83,11 +89,37 @@ export function quienSoy(repo) {
83
89
  }
84
90
  }
85
91
  export async function runWorkflow(cmd, rest) {
92
+ let dry;
93
+ try {
94
+ await runCommand(cmd, rest, (d) => { dry = d; });
95
+ }
96
+ finally {
97
+ dry?.finish();
98
+ } // what it would have done, and the temporary copy is deleted
99
+ }
100
+ async function runCommand(cmd, rest, onDryRun) {
86
101
  const cfg = loadConfig();
87
- const store = new Store(cfg.stateDir);
88
102
  warnLegacy(cfg);
89
103
  const connectors = buildConnectors(cfg.connectors);
90
- const flow = new Process(cfg, connectors, store, new GitWorkspace(cfg), new OpenSpecCli(cfg.openspecCmd, cfg.repoPath));
104
+ const realStore = new Store(cfg.stateDir);
105
+ const workspace = new GitWorkspace(cfg), openspec = new OpenSpecCli(cfg.openspecCmd, cfg.repoPath);
106
+ // --dry-run: the same command on a copy of the state, with the writes recorded instead of done (see workflow/dry-run.ts)
107
+ const dryAt = rest.indexOf("--dry-run");
108
+ if (dryAt >= 0) {
109
+ rest.splice(dryAt, 1);
110
+ if (!DRY_RUN_COMMANDS.includes(cmd)) {
111
+ console.error(`✘ --dry-run works with: ${DRY_RUN_COMMANDS.filter((c) => c !== "new-worq").join(", ")}. orqen ${cmd} would have run for real, so it was not run.`);
112
+ process.exitCode = 1;
113
+ return;
114
+ }
115
+ }
116
+ const dry = dryAt >= 0 ? new DryRun(cfg, connectors, workspace, openspec, realStore, rest[0]) : undefined;
117
+ if (dry) {
118
+ onDryRun(dry);
119
+ console.log("DRY RUN: nothing is written to the tickets, Git or this machine.\n");
120
+ }
121
+ const store = dry?.store ?? realStore;
122
+ const flow = dry?.flow ?? new Process(cfg, connectors, store, workspace, openspec);
91
123
  const flag = (n) => { const i = rest.indexOf(`--${n}`); return i >= 0 ? (rest.splice(i, 2)[1] ?? "") : undefined; };
92
124
  const has = (n) => { const i = rest.indexOf(`--${n}`); if (i >= 0)
93
125
  rest.splice(i, 1); return i >= 0; };
@@ -234,7 +266,7 @@ export async function runWorkflow(cmd, rest) {
234
266
  continue;
235
267
  console.log(`${titles[role]}:`);
236
268
  for (const b of xs)
237
- console.log(` ${b.work.padEnd(12)} ${b.state.padEnd(15)} ${(b.next[0]?.command ?? "").padEnd(28)} ${b.takenBy ? `(taken by ${b.takenBy} since ${b.since?.slice(0, 16).replace("T", " ")})` : ""}${b.recovered ? " ← state read from the ticket; this machine has no record" : ""}`);
269
+ console.log(` ${b.work.padEnd(12)} ${b.state.padEnd(15)} ${(b.next[0]?.command ?? "").padEnd(28)} ${b.takenBy ? `(taken by ${b.takenBy} since ${b.since?.slice(0, 16).replace("T", " ")})` : ""}${b.recovered ? ` ← state read from the ticket; this machine has no record${b.next[0]?.command ? "" : " and its branch is not on origin yet (it appears when whoever started it pushes)"}` : ""}`);
238
270
  }
239
271
  return;
240
272
  }
@@ -278,15 +310,18 @@ export async function runWorkflow(cmd, rest) {
278
310
  }
279
311
  return;
280
312
  }
313
+ case "new-worq":
281
314
  case "new_worq": {
282
315
  try {
283
- const title = rest[0] ?? "";
284
- const src = rest[1];
285
- if (!title || !src)
286
- throw new Error('Usage: orqen new_worq "<title>" <brief.json|-> [--person NAME] (brief: {"description", "acceptance_criteria": [...], "plan": [...], "estimated_hours"})');
316
+ const issueFlag = flag("issue");
317
+ const existing = issueFlag ? toKey(issueFlag) : undefined;
318
+ // 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"})');
287
322
  const raw = JSON.parse(src === "-" ? readFileSync(0, "utf8") : readFileSync(src, "utf8"));
288
- const r = await flow.newWorq(title, raw, me || agent);
289
- console.log(`✔ ${r.key} created in ${r.state}: issue ${r.url} (no client request) · worq: ${r.dir}/`);
323
+ const r = await flow.newWorq(title, raw, me || agent, existing);
324
+ console.log(`✔ ${r.key} ${existing ? "taken" : "created"} in ${r.state}: issue ${r.url} (no client request) · worq: ${r.dir}/`);
290
325
  console.log(` Next: /orqen:implement ${r.key}`);
291
326
  }
292
327
  catch (e) {
@@ -543,7 +578,7 @@ export async function runWorkflow(cmd, rest) {
543
578
  console.log(`Worq ${w.key}${w.title ? ` — ${w.title}` : ""}`);
544
579
  console.log(` State: ${w.state}${w.round > 1 ? ` (round ${w.round})` : ""}${w.lane ? ` · lane ${w.lane}` : ""}${w.route && w.route !== "development" ? ` · ${w.route}` : ""}`);
545
580
  if (w.next[0])
546
- console.log(` Next: ${w.next[0].command} (${w.role}: ${w.next[0].what})`);
581
+ console.log(` Next: ${w.next[0].command ? `${w.next[0].command} (${w.role}: ${w.next[0].what})` : `${w.role}: ${w.next[0].what}`}`);
547
582
  console.log(` Request: ${w.key} ${w.request_url}`);
548
583
  if (w.issue)
549
584
  console.log(` Issue: ${w.issue}${w.issue_url ? ` ${w.issue_url}` : ""}`);
@@ -554,7 +589,7 @@ export async function runWorkflow(cmd, rest) {
554
589
  if (w.supporter || w.analyst)
555
590
  console.log(` People: ${[w.supporter && `support ${w.supporter}`, w.analyst && `analyst ${w.analyst}`].filter(Boolean).join(" · ")}`);
556
591
  if (item.recovered)
557
- console.log(" The state is read from the ticket's label: this machine has no record. Fetch its branch to recover the worq (git fetch origin " + (w.branch ?? `orqen/${key.toLowerCase()}`) + ").");
592
+ console.log(` ${flow.recoveredHint(key).text}`);
558
593
  else {
559
594
  console.log(` Folder: ${w.dir}/`);
560
595
  for (const f of files)
@@ -590,7 +625,7 @@ export async function runWorkflow(cmd, rest) {
590
625
  const item = flow.item(key) ?? await flow.peek(key);
591
626
  console.log(item ? JSON.stringify({ ...item, artifacts: Object.keys(item.artifacts) }, null, 2) : "unknown");
592
627
  if (item?.recovered)
593
- console.log(`State read from the ticket's label: this machine has no record of ${key}. Fetch its branch (git fetch origin orqen/${key.toLowerCase()}) to recover the full record.`);
628
+ console.log(flow.recoveredHint(key).text);
594
629
  for (const ev of store.events(key))
595
630
  console.log(` ${ev.ts} ${ev.from} → ${ev.to} ${ev.detail}`);
596
631
  }
@@ -599,6 +634,38 @@ export async function runWorkflow(cmd, rest) {
599
634
  console.log(`${r.key.padEnd(12)} ${r.state.padEnd(15)} ${(r.issue ?? "").padEnd(12)} ${r.change ?? ""}`);
600
635
  return;
601
636
  }
637
+ case "report": {
638
+ const { buildReport, printReport } = await import("../workflow/report.js");
639
+ const json = has("json");
640
+ const since = flag("since");
641
+ let from;
642
+ if (since) {
643
+ const days = /^(\d+)d$/i.exec(since);
644
+ from = days ? new Date(Date.now() - Number(days[1]) * 86_400_000) : new Date(since);
645
+ if (Number.isNaN(from.getTime())) {
646
+ console.error("✘ --since takes a date (2026-11-01) or a number of days (30d)");
647
+ process.exitCode = 1;
648
+ return;
649
+ }
650
+ }
651
+ const r = buildReport(store.all().map((item) => ({ item, events: store.events(item.key) })), { from });
652
+ if (json)
653
+ console.log(JSON.stringify(r, null, 2));
654
+ else
655
+ printReport(r);
656
+ return;
657
+ }
658
+ case "doctor": {
659
+ const { diagnose, printChecks } = await import("./doctor.js");
660
+ const checks = await diagnose(cfg, connectors);
661
+ if (has("json"))
662
+ console.log(JSON.stringify({ checks }, null, 2));
663
+ else
664
+ printChecks(checks);
665
+ if (checks.some((c) => c.status === "fail"))
666
+ process.exitCode = 1;
667
+ return;
668
+ }
602
669
  case "connectors": {
603
670
  // JSON for tools such as orqen-studio: {"conectores": {...}, "env": {"JIRA_TOKEN": "..."}} on stdin or in a file
604
671
  const draftInput = () => JSON.parse(!rest[1] || rest[1] === "-" ? readFileSync(0, "utf8") : readFileSync(rest[1], "utf8"));
@@ -4,6 +4,8 @@
4
4
  * of the project; "completed" marks it done. Asana tags need ids, so the state is not mirrored as a tag.
5
5
  */
6
6
  import { idOf, keyOf } from "./config.js";
7
+ import { request } from "./http.js";
8
+ import { toPlain } from "./markup.js";
7
9
  import { BOT_MARK, checkFailure } from "./types.js";
8
10
  const API = "https://app.asana.com/api/1.0";
9
11
  export class AsanaTracker {
@@ -19,13 +21,11 @@ export class AsanaTracker {
19
21
  async requestPage(method, path, body) {
20
22
  if (!this.s.token)
21
23
  throw new Error("Asana connector without token: set ASANA_TOKEN in orqen/.env");
22
- const r = await fetch(this.api + path, {
24
+ const r = await request("Asana", `${method} ${path}`, this.api + path, {
23
25
  method,
24
26
  headers: { Authorization: `Bearer ${this.s.token}`, Accept: "application/json", "Content-Type": "application/json" },
25
27
  body: body === undefined ? undefined : JSON.stringify({ data: body }),
26
28
  });
27
- if (!r.ok)
28
- throw new Error(`Asana ${method} ${path}: ${r.status} ${await r.text()}`);
29
29
  const t = await r.text();
30
30
  return t ? JSON.parse(t) : { data: {} };
31
31
  }
@@ -68,7 +68,7 @@ export class AsanaTracker {
68
68
  }));
69
69
  }
70
70
  async comment(key, text) {
71
- await this.req("POST", `/tasks/${this.gid(key)}/stories`, { text: `${BOT_MARK} ${text}` });
71
+ await this.req("POST", `/tasks/${this.gid(key)}/stories`, { text: `${BOT_MARK} ${toPlain(text)}` });
72
72
  }
73
73
  async setStateLabel() { }
74
74
  async transition(key, name) {
@@ -84,7 +84,7 @@ export class AsanaTracker {
84
84
  return true;
85
85
  }
86
86
  async create(t) {
87
- const r = await this.req("POST", "/tasks", { name: t.title.slice(0, 250), notes: t.description, projects: [this.needProject()] });
87
+ const r = await this.req("POST", "/tasks", { name: t.title.slice(0, 250), notes: toPlain(t.description), projects: [this.needProject()] });
88
88
  return keyOf(this.s.prefix, r.gid);
89
89
  }
90
90
  url(key) { return `https://app.asana.com/0/${this.s.project || 0}/${this.gid(key)}`; }
@@ -5,9 +5,52 @@
5
5
  */
6
6
  import { execFileSync } from "node:child_process";
7
7
  import { idOf, keyOf } from "./config.js";
8
+ import { request } from "./http.js";
8
9
  import { toMarkdown } from "./markup.js";
9
10
  import { BOT_MARK, LEGACY_STATE_LABELS, STATE_LABEL, checkFailure } from "./types.js";
10
11
  const API = "https://api.github.com";
12
+ /**
13
+ * A search filter as parameters of the list of issues, or undefined when the list cannot express it. Without is:open/closed
14
+ * the search returns both, and so does the list (state=all). `label:a,b` means "a or b" in search but "a and b" in the list,
15
+ * so it is searched.
16
+ */
17
+ export function listFilter(query) {
18
+ const f = { state: "all", labels: [] };
19
+ for (const token of query.match(/(?:[^\s"]+|"[^"]*")+/g) ?? []) {
20
+ const m = token.match(/^([a-z]+):(.+)$/i);
21
+ if (!m)
22
+ return undefined;
23
+ const v = m[2].replace(/"/g, "");
24
+ if (!v || v.includes(","))
25
+ return undefined;
26
+ switch (m[1].toLowerCase()) {
27
+ case "is":
28
+ case "state":
29
+ if (v === "issue")
30
+ break;
31
+ if (v === "open" || v === "closed") {
32
+ f.state = v;
33
+ break;
34
+ }
35
+ return undefined;
36
+ case "label":
37
+ f.labels.push(v);
38
+ break;
39
+ case "assignee":
40
+ if (f.assignee)
41
+ return undefined;
42
+ f.assignee = v;
43
+ break;
44
+ case "author":
45
+ if (f.creator)
46
+ return undefined;
47
+ f.creator = v;
48
+ break;
49
+ default: return undefined;
50
+ }
51
+ }
52
+ return f;
53
+ }
11
54
  export class GithubTracker {
12
55
  s;
13
56
  api;
@@ -38,13 +81,12 @@ export class GithubTracker {
38
81
  async req(method, path, body) {
39
82
  if (!this.s.repo && path.includes("{repo}"))
40
83
  throw new Error("GitHub connector without repo (conectores.*.repo: owner/name)");
41
- const r = await fetch(this.api + path.replace("{repo}", this.s.repo), {
84
+ const real = path.replace("{repo}", this.s.repo);
85
+ const r = await request("GitHub", `${method} ${real}`, this.api + real, {
42
86
  method,
43
87
  headers: { Authorization: `Bearer ${this.auth()}`, Accept: "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28", "Content-Type": "application/json" },
44
88
  body: body === undefined ? undefined : JSON.stringify(body),
45
89
  });
46
- if (!r.ok)
47
- throw new Error(`GitHub ${method} ${path.replace("{repo}", this.s.repo)}: ${r.status} ${await r.text()}`);
48
90
  const t = await r.text();
49
91
  return t ? JSON.parse(t) : {};
50
92
  }
@@ -86,7 +128,7 @@ export class GithubTracker {
86
128
  if (!this.s.project) {
87
129
  if (this.s.status)
88
130
  throw new Error("Select a GitHub Project before choosing a pending status");
89
- return this.search(this.s.query);
131
+ return this.find(this.s.query);
90
132
  }
91
133
  // The project's issues (in one status, or in any status when none is chosen), narrowed by the search qualifiers if there are any.
92
134
  const project = await this.project();
@@ -111,7 +153,7 @@ export class GithubTracker {
111
153
  } while (cursor);
112
154
  // Preserve explicitly configured issue qualifiers as an additional filter.
113
155
  if (!oldColumn && this.s.query.trim() && this.s.query.trim() !== "is:open") {
114
- const matching = new Set(await this.search(this.s.query));
156
+ const matching = new Set(await this.find(this.s.query));
115
157
  return [...new Set(keys)].filter((key) => matching.has(key));
116
158
  }
117
159
  return [...new Set(keys)];
@@ -129,6 +171,35 @@ export class GithubTracker {
129
171
  const r = await this.req("GET", `/search/issues?per_page=100&q=${encodeURIComponent(q)}`);
130
172
  return (r.items ?? []).map((i) => keyOf(this.s.prefix, i.number));
131
173
  }
174
+ /**
175
+ * The issues a filter selects. When the filter only has qualifiers the list of issues understands (is:open|closed, state:,
176
+ * label:, assignee:, author:) the list is read instead of the search: the search allows 30 requests per minute (the list,
177
+ * 5000 per hour, which matters for an unattended `orqen cycle`) and returns a single page of 100 (the list is paginated).
178
+ * Anything else (free text, OR, negations) is searched. Neither shows an issue created a few seconds ago: GitHub takes a
179
+ * moment to list it either way, so it shows up on the next run.
180
+ */
181
+ async find(query) {
182
+ const f = listFilter(query);
183
+ if (!f)
184
+ return this.search(query);
185
+ const keys = [];
186
+ for (let page = 1; page <= 10; page++) {
187
+ const p = new URLSearchParams({ state: f.state, per_page: "100", page: String(page) });
188
+ if (f.labels.length)
189
+ p.set("labels", f.labels.join(","));
190
+ if (f.assignee)
191
+ p.set("assignee", f.assignee);
192
+ if (f.creator)
193
+ p.set("creator", f.creator);
194
+ const rows = await this.req("GET", `/repos/{repo}/issues?${p}`);
195
+ keys.push(...rows.filter((i) => !i.pull_request).map((i) => keyOf(this.s.prefix, i.number))); // the list also has PRs
196
+ if (rows.length < 100)
197
+ break;
198
+ }
199
+ return keys;
200
+ }
201
+ labelled(label) { return this.find(`is:open label:"${label}"`); }
202
+ async addLabel(key, label) { await this.req("POST", `/repos/{repo}/issues/${this.n(key)}/labels`, { labels: [label] }); }
132
203
  async ticket(key) {
133
204
  const i = await this.req("GET", `/repos/{repo}/issues/${this.n(key)}`);
134
205
  return {
@@ -0,0 +1,92 @@
1
+ /**
2
+ * HTTP for the connectors: retries what is temporary (the API's rate limit, a gateway error, a network cut) and says so when
3
+ * it gives up, so the flow can tell "try again in a moment" from "this needs a person". Without it, one 502 while listing the
4
+ * requests moved a request to BLOCKED and told the client that human intervention was needed.
5
+ *
6
+ * - 429, and 403 with Retry-After (GitHub's secondary limit): the request was not processed, any method is retried.
7
+ * - 500/502/503/504 and network cuts: only methods that can be repeated (GET, PUT, PATCH, DELETE). A POST (a comment, a new
8
+ * issue) may have been processed before the answer got lost, so retrying it could duplicate it; it fails as temporary instead.
9
+ * The exception is a failure that happens before anything is sent (no DNS, connection refused): safe for any method.
10
+ */
11
+ export class HttpError extends Error {
12
+ status;
13
+ transient;
14
+ constructor(message, status, /** Temporary: the same call can work later. */ transient) {
15
+ super(message);
16
+ this.status = status;
17
+ this.transient = transient;
18
+ this.name = "HttpError";
19
+ }
20
+ }
21
+ /** Whether an error is temporary: the caller should keep the work as it is and try again later, not block it. */
22
+ export const isTransient = (e) => e instanceof HttpError && e.transient;
23
+ export const retryPolicy = {
24
+ /** Calls per request, the first one included. */
25
+ attempts: 4,
26
+ baseMs: 1000,
27
+ /** Longest wait between two calls; a Retry-After above it is not waited for (the error is temporary and the caller decides). */
28
+ maxMs: 20_000,
29
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
30
+ };
31
+ const REPEATABLE = new Set(["GET", "HEAD", "PUT", "PATCH", "DELETE"]);
32
+ const NOTHING_SENT = new Set(["ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN"]); // the failure was before the request left
33
+ const CUT = new Set([...NOTHING_SENT, "ECONNRESET", "ETIMEDOUT", "EPIPE", "UND_ERR_SOCKET", "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_HEADERS_TIMEOUT", "UND_ERR_BODY_TIMEOUT", "ECONNABORTED"]);
34
+ /** Seconds or an HTTP date → milliseconds. */
35
+ function retryAfterMs(h) {
36
+ if (!h)
37
+ return undefined;
38
+ const s = Number(h);
39
+ if (Number.isFinite(s))
40
+ return Math.max(0, s * 1000);
41
+ const d = Date.parse(h);
42
+ return Number.isNaN(d) ? undefined : Math.max(0, d - Date.now());
43
+ }
44
+ function networkCode(e) {
45
+ const c = e?.cause?.code ?? e?.code;
46
+ return typeof c === "string" ? c : undefined;
47
+ }
48
+ /**
49
+ * `fetch` that retries what is temporary. `what` is "METHOD path", for the messages. It returns the response when it is ok and
50
+ * throws an `HttpError` otherwise (`transient` tells whether it is worth trying again later).
51
+ */
52
+ export async function request(system, what, url, init) {
53
+ const method = (init.method ?? "GET").toUpperCase();
54
+ const { attempts, baseMs, maxMs } = retryPolicy;
55
+ for (let attempt = 1;; attempt++) {
56
+ let r;
57
+ try {
58
+ r = await fetch(url, init);
59
+ }
60
+ catch (e) {
61
+ const code = networkCode(e);
62
+ const cut = code !== undefined && CUT.has(code);
63
+ const mayRetry = cut && (REPEATABLE.has(method) || NOTHING_SENT.has(code));
64
+ if (mayRetry && attempt < attempts) {
65
+ await retryPolicy.sleep(backoff(attempt, baseMs, maxMs));
66
+ continue;
67
+ }
68
+ const why = code ?? e.message;
69
+ throw new HttpError(`${system} ${what}: network error (${why})`, 0, cut || /fetch failed|network|timeout|aborted/i.test(e.message));
70
+ }
71
+ if (r.ok)
72
+ return r;
73
+ const text = await r.text();
74
+ const limited = r.status === 429 || (r.status === 403 && (r.headers.has("retry-after") || r.headers.get("x-ratelimit-remaining") === "0" || /rate limit/i.test(text)));
75
+ const gateway = [500, 502, 503, 504].includes(r.status);
76
+ const transient = limited || gateway;
77
+ const mayRetry = limited || (gateway && REPEATABLE.has(method));
78
+ if (mayRetry && attempt < attempts) {
79
+ const asked = retryAfterMs(r.headers.get("retry-after")) ?? (r.headers.get("x-ratelimit-remaining") === "0" ? retryAfterMs(String(Number(r.headers.get("x-ratelimit-reset")) - Date.now() / 1000)) : undefined);
80
+ if (asked === undefined || asked <= maxMs) {
81
+ await retryPolicy.sleep(asked ?? backoff(attempt, baseMs, maxMs));
82
+ continue;
83
+ }
84
+ }
85
+ throw new HttpError(`${system} ${what}: ${r.status} ${text}`, r.status, transient);
86
+ }
87
+ }
88
+ /** 1 s, 2 s, 4 s… with up to 25% of jitter, never above `maxMs`. */
89
+ function backoff(attempt, baseMs, maxMs) {
90
+ const ms = baseMs * 2 ** (attempt - 1);
91
+ return Math.min(maxMs, ms + Math.random() * ms * 0.25);
92
+ }
@@ -4,6 +4,7 @@ import { GithubTracker } from "./github.js";
4
4
  import { JiraTracker } from "./jira.js";
5
5
  import { LocalTracker } from "./local.js";
6
6
  export * from "./types.js";
7
+ export { HttpError, isTransient } from "./http.js";
7
8
  export function trackerFor(s) {
8
9
  if (s.kind === "jira")
9
10
  return new JiraTracker(s);
@@ -1,5 +1,6 @@
1
1
  /** Jira Cloud and Server / Data Center (REST v2; search uses v3 on Cloud). */
2
2
  import { idOf, keyOf } from "./config.js";
3
+ import { request } from "./http.js";
3
4
  import { BOT_MARK, LEGACY_STATE_LABELS, STATE_LABEL, checkFailure } from "./types.js";
4
5
  export class JiraTracker {
5
6
  s;
@@ -41,17 +42,16 @@ export class JiraTracker {
41
42
  const url = new URL(this.base + path);
42
43
  for (const [k, v] of Object.entries(params ?? {}))
43
44
  url.searchParams.set(k, String(v));
44
- const r = await fetch(url, {
45
+ const r = await request("Jira", `${method} ${path}`, url, {
45
46
  method,
46
47
  headers: { Authorization: this.auth, Accept: "application/json", "Content-Type": "application/json" },
47
48
  body: body === undefined ? undefined : JSON.stringify(body),
48
49
  });
49
- if (!r.ok)
50
- throw new Error(`Jira ${method} ${path}: ${r.status} ${await r.text()}`);
51
50
  const t = await r.text();
52
51
  return t ? JSON.parse(t) : {};
53
52
  }
54
53
  pending() { return this.search(this.s.query); }
54
+ labelled(label) { return this.search(`${this.s.project ? `project = "${this.s.project}" AND ` : ""}labels = "${label}" AND statusCategory != Done`); }
55
55
  async search(jql) {
56
56
  const path = this.s.deployment === "cloud" ? "/rest/api/3/search/jql" : "/rest/api/2/search";
57
57
  const r = await this.req("GET", path, undefined, { jql, fields: "key", maxResults: 100 });
@@ -85,6 +85,9 @@ export class JiraTracker {
85
85
  async comment(key, text) {
86
86
  await this.req("POST", `/rest/api/2/issue/${this.native(key)}/comment`, { body: `${BOT_MARK} ${text}` });
87
87
  }
88
+ async addLabel(key, label) {
89
+ await this.req("PUT", `/rest/api/2/issue/${this.native(key)}`, { update: { labels: [{ add: label }] } });
90
+ }
88
91
  async setStateLabel(key, state) {
89
92
  const { labels } = await this.ticket(key);
90
93
  const next = labels.filter((l) => ![STATE_LABEL, ...LEGACY_STATE_LABELS].some((p) => l.startsWith(p))).concat(`${STATE_LABEL}${state.toLowerCase()}`);