@telpin-sistemas/orqen 0.1.15 → 0.1.17

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 (35) hide show
  1. package/dist/commands/client-chat.js +8 -1
  2. package/dist/commands/studio.js +391 -0
  3. package/dist/commands/tutorial.js +6 -4
  4. package/dist/commands/workflow.js +55 -15
  5. package/dist/connectors/github.js +4 -0
  6. package/dist/connectors/jira.js +4 -3
  7. package/dist/index.js +6 -0
  8. package/dist/lib/checkpoints.js +196 -0
  9. package/dist/lib/coded-error.js +32 -0
  10. package/dist/lib/config-keys.js +1 -1
  11. package/dist/lib/config.js +7 -1
  12. package/dist/lib/schedules.js +151 -0
  13. package/dist/lib/worq-notes.js +137 -0
  14. package/dist/template/.agents/commands/analyze.md +1 -1
  15. package/dist/template/.agents/commands/approve.md +2 -2
  16. package/dist/template/.agents/commands/implement.md +3 -3
  17. package/dist/template/.agents/commands/pr.md +1 -1
  18. package/dist/template/.agents/commands/review.md +2 -2
  19. package/dist/template/.agents/commands/support.md +2 -2
  20. package/dist/template/AGENTS.md +13 -4
  21. package/dist/template/stages/analysis.md +1 -1
  22. package/dist/template/stages/delivery.md +1 -1
  23. package/dist/template/stages/development.md +1 -1
  24. package/dist/template/stages/execution.md +1 -1
  25. package/dist/template/stages/specification.md +1 -1
  26. package/dist/template/stages/support.md +1 -1
  27. package/dist/template/stages/verification.md +1 -1
  28. package/dist/tutorial/app.js +37 -23
  29. package/dist/workflow/config.js +11 -0
  30. package/dist/workflow/dry-run-commands.js +1 -1
  31. package/dist/workflow/dry-run.js +2 -1
  32. package/dist/workflow/process.js +134 -15
  33. package/dist/workflow/report.js +14 -3
  34. package/dist/workflow/routed.js +1 -0
  35. package/package.json +1 -1
@@ -18,10 +18,17 @@ export function parseTeamComment(body) {
18
18
  const m = t.match(/^\*{1,2}([^*\n]{1,60}?):\*{1,2}\s*/);
19
19
  return m ? { author: m[1].trim(), text: t.slice(m[0].length) } : { author: "orqen", text: t };
20
20
  }
21
+ /** Phrases of the comments orqen writes to the client (see workflow/process.ts): the rest of its comments are notes on the workflow. */
22
+ const TO_CLIENT = [/^Question for /, /To confirm the request is solved/, /To accept the result/, /Please confirm the following/];
23
+ export function audienceOf(author, text) {
24
+ if (author && author !== "orqen")
25
+ return "client"; // a person answered with `orqen comment` (signed with their name)
26
+ return TO_CLIENT.some((r) => r.test(text)) ? "client" : "internal";
27
+ }
21
28
  export function toMessage(c) {
22
29
  if (isBotComment(c.body)) {
23
30
  const p = parseTeamComment(c.body);
24
- return { id: c.id, from: "team", author: p.author, text: p.text, created: c.created };
31
+ return { id: c.id, from: "team", author: p.author, text: p.text, created: c.created, audience: audienceOf(p.author, p.text) };
25
32
  }
26
33
  return { id: c.id, from: "client", author: c.authorName || c.author, text: c.body, created: c.created };
27
34
  }
@@ -0,0 +1,391 @@
1
+ /**
2
+ * Commands behind orqen Studio's review and automation screens (they work the same from a terminal):
3
+ * checkpoints of a worq's worktree, attribution of its lines, review notes, evidence for QA, automations and
4
+ * worktree cleanup. Everything is local to this machine (orqen/state/ and refs/orqen/ in git).
5
+ */
6
+ import { execFileSync } from "node:child_process";
7
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
8
+ import { tmpdir, userInfo } from "node:os";
9
+ import { basename, join, resolve } from "node:path";
10
+ import { attribution, Checkpoints } from "../lib/checkpoints.js";
11
+ import { EvidenceStore, ReviewNotes } from "../lib/worq-notes.js";
12
+ import { Schedules } from "../lib/schedules.js";
13
+ import { detectarIdioma } from "../lib/lang.js";
14
+ import { mainWorktree, repoRoot } from "../workflow/config.js";
15
+ import { Store as WorqStore } from "../workflow/store.js";
16
+ export const STUDIO_COMMANDS = ["checkpoint", "attribution", "review-notes", "evidence", "schedule", "worktree"];
17
+ export const STUDIO_HELP = `
18
+ Review and automation (orqen Studio uses them; everything is local to this machine):
19
+ checkpoint <KEY> [--json] Checkpoints of the worq's worktree (a snapshot of every file, in git, outside the branch)
20
+ save [--label T] [--by agent|person] [--run ID] [--dir D] take one (the files changed since the previous one)
21
+ diff <from> [<to>] [--patch] [--file F] what changed between two checkpoints (to: now)
22
+ restore <id> put the files back as they were (what is there now is saved first)
23
+ attribution <KEY> [--dir D] [--base B] [--json] Lines the worq adds, by who wrote them (agent turns vs people)
24
+ review-notes <KEY> [--json] Review notes on lines of the worq's diff
25
+ add <file>:<line>[-<end>] <text|-> · resolve|reopen|remove <id> · text (the open ones, for "request changes")
26
+ evidence <KEY> [--json] Evidence for QA (screenshots, logs), by acceptance criterion
27
+ add <file> [--criterion N] [--note T] [--name N] · remove <id>
28
+ schedule [--json] Automations: an agent runs a prompt on a schedule; what it finds becomes a worq
29
+ add --name N --cron "m h dom mon dow" --prompt <text|-> [--bot B] [--agent CMD] [--max-minutes M]
30
+ run <id> · tick (the ones due) · enable|disable|remove <id>
31
+ worktree prune [--dry-run] [--force] [--json] Remove the worktrees of delivered or cancelled worqs (clean ones; --force: also with changes)`;
32
+ const stateDir = () => process.env.ORQEN_STATE_DIR || join(mainWorktree(repoRoot()), "orqen", "state");
33
+ /** Options: `--name value` pairs and flags, taken out of `args`. */
34
+ function opts(args) {
35
+ const value = (n) => { const i = args.indexOf(`--${n}`); if (i < 0)
36
+ return undefined; const v = args[i + 1] ?? ""; args.splice(i, 2); return v; };
37
+ const flag = (n) => { const i = args.indexOf(`--${n}`); if (i >= 0)
38
+ args.splice(i, 1); return i >= 0; };
39
+ return { value, flag };
40
+ }
41
+ const stdinOr = (v) => v === "-" ? readFileSync(0, "utf8") : v ?? "";
42
+ function me() {
43
+ try {
44
+ const n = execFileSync("git", ["config", "user.name"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
45
+ if (n)
46
+ return n;
47
+ }
48
+ catch { /* none */ }
49
+ try {
50
+ return userInfo().username || undefined;
51
+ }
52
+ catch {
53
+ return undefined;
54
+ }
55
+ }
56
+ function out(json, value, text) {
57
+ console.log(json ? JSON.stringify(value, null, 2) : text());
58
+ }
59
+ export async function studioCommand(cmd, args) {
60
+ const o = opts(args);
61
+ const json = o.flag("json");
62
+ try {
63
+ switch (cmd) {
64
+ case "checkpoint": return checkpoint(args, o, json);
65
+ case "attribution": return attributionCmd(args, o, json);
66
+ case "review-notes": return reviewNotes(args, o, json);
67
+ case "evidence": return evidence(args, o, json);
68
+ case "schedule": return await schedule(args, o, json);
69
+ case "worktree": return worktree(args, o, json);
70
+ }
71
+ }
72
+ catch (e) {
73
+ const msg = e.message;
74
+ if (json)
75
+ console.log(JSON.stringify({ ok: false, error: msg }));
76
+ else
77
+ console.error(`✘ ${msg}`);
78
+ process.exitCode = 1;
79
+ }
80
+ }
81
+ const needKey = (args, usage) => {
82
+ const key = args.shift();
83
+ if (!key || key.startsWith("-"))
84
+ throw new Error(`Usage: ${usage}`);
85
+ return key;
86
+ };
87
+ // ------------------------------------------------------------------ checkpoint / attribution
88
+ function checkpoint(args, o, json) {
89
+ const key = needKey(args, "orqen checkpoint <KEY> [save|diff|restore] [--json]");
90
+ const dir = resolve(o.value("dir") ?? process.cwd());
91
+ const cps = new Checkpoints(stateDir());
92
+ const sub = args.shift() ?? "list";
93
+ if (sub === "list") {
94
+ const list = cps.list(key);
95
+ return out(json, { key, checkpoints: list }, () => list.length ? list.map((c) => `${c.id} ${c.at.slice(0, 16).replace("T", " ")} ${c.by.padEnd(6)} ${c.label}`).join("\n") : `${key} has no checkpoints yet.`);
96
+ }
97
+ if (sub === "save") {
98
+ const by = o.value("by");
99
+ if (by && !["agent", "person", "base"].includes(by))
100
+ throw new Error("--by: agent, person or base");
101
+ const r = cps.save(key, dir, { label: o.value("label"), by, run: o.value("run") });
102
+ return out(json, { ok: true, ...r }, () => r.same ? `Nothing changed since ${r.id} (${r.label}).` : `✔ ${r.id} saved (${r.label})${r.files.length ? `: ${r.files.length} file(s) changed` : ""}`);
103
+ }
104
+ if (sub === "diff") {
105
+ const from = cps.get(key, args.shift() ?? "");
106
+ const toId = args.shift();
107
+ const to = toId && toId !== "now" ? cps.get(key, toId).tree : Checkpoints.snapshotTree(dir);
108
+ const file = o.value("file");
109
+ if (o.flag("patch"))
110
+ return console.log(Checkpoints.patch(dir, from.tree, to, file));
111
+ const files = Checkpoints.diff(dir, from.tree, to).filter((f) => !file || f.path === file);
112
+ return out(json, { key, from: from.id, to: toId ?? "now", files }, () => files.map((f) => `${f.path} +${f.add} −${f.del}`).join("\n") || "No changes.");
113
+ }
114
+ if (sub === "restore") {
115
+ const r = cps.restore(key, dir, args.shift() ?? "");
116
+ return out(json, { ok: true, ...r }, () => `✔ Back to ${r.restored.id} (${r.restored.label}): ${r.files.length} file(s). What was there is ${r.saved.id}.`);
117
+ }
118
+ throw new Error(`Unknown: orqen checkpoint ${key} ${sub}`);
119
+ }
120
+ function attributionCmd(args, o, json) {
121
+ const key = needKey(args, "orqen attribution <KEY> [--dir D] [--base B] [--json]");
122
+ const dir = resolve(o.value("dir") ?? process.cwd());
123
+ let base = o.value("base");
124
+ if (!base) {
125
+ try {
126
+ const cfg = readFileSync(join(mainWorktree(dir), "orqen", "config.yaml"), "utf8");
127
+ base = cfg.match(/^\s*(?:base_branch|rama_base)\s*:\s*["']?([\w./-]+)/m)?.[1];
128
+ }
129
+ catch { /* no config */ }
130
+ }
131
+ const r = attribution(new Checkpoints(stateDir()), key, dir, base || "main");
132
+ out(json, { key, ...r }, () => `${key}: ${r.total.added} line(s) added · agent ${r.total.agent} (${r.total.pct_agent}%) · people ${r.total.person}` +
133
+ (r.files.length ? "\n" + r.files.map((f) => ` ${f.path} +${f.added} (agent ${f.agent})`).join("\n") : ""));
134
+ }
135
+ // ------------------------------------------------------------------ review notes / evidence
136
+ function reviewNotes(args, o, json) {
137
+ const key = needKey(args, "orqen review-notes <KEY> [add|resolve|reopen|remove|text] [--json]");
138
+ const notes = new ReviewNotes(stateDir());
139
+ const sub = args.shift() ?? "list";
140
+ switch (sub) {
141
+ case "list": {
142
+ const list = notes.list(key);
143
+ return out(json, { key, notes: list }, () => list.map((n) => `${n.id} [${n.status}] ${n.file}:${n.line}${n.end ? `-${n.end}` : ""} ${n.text}`).join("\n") || `${key} has no review notes.`);
144
+ }
145
+ case "add": {
146
+ const where = args.shift() ?? "";
147
+ const code = o.value("code");
148
+ const n = notes.add(key, where, stdinOr(args.join(" ") || undefined), { person: me(), code });
149
+ return out(json, { ok: true, note: n }, () => `✔ ${n.id} on ${n.file}:${n.line}`);
150
+ }
151
+ case "resolve":
152
+ case "reopen": {
153
+ const n = notes.set(key, args.shift() ?? "", { status: sub === "resolve" ? "resolved" : "open" });
154
+ return out(json, { ok: true, note: n }, () => `✔ ${n.id} ${n.status}`);
155
+ }
156
+ case "remove": {
157
+ const id = args.shift() ?? "";
158
+ notes.remove(key, id);
159
+ return out(json, { ok: true }, () => `✔ ${id} removed`);
160
+ }
161
+ case "text": {
162
+ const text = notes.text(key);
163
+ return out(json, { key, text, open: notes.list(key).filter((n) => n.status === "open").length }, () => text);
164
+ }
165
+ case "sent": {
166
+ const n = notes.markSent(key);
167
+ return out(json, { ok: true, sent: n }, () => `✔ ${n} note(s) marked as sent`);
168
+ }
169
+ }
170
+ throw new Error(`Unknown: orqen review-notes ${key} ${sub}`);
171
+ }
172
+ function evidence(args, o, json) {
173
+ const key = needKey(args, "orqen evidence <KEY> [add <file>|remove <id>] [--json]");
174
+ const ev = new EvidenceStore(stateDir());
175
+ const sub = args.shift() ?? "list";
176
+ if (sub === "list") {
177
+ const list = ev.list(key);
178
+ return out(json, { key, evidence: list, criteria: ev.covered(key) }, () => list.map((e) => `${e.id} ${e.criterion ? `criterion ${e.criterion}` : "—"} ${e.name}${e.note ? ` · ${e.note}` : ""}`).join("\n") || `${key} has no evidence.`);
179
+ }
180
+ if (sub === "add") {
181
+ const file = args.shift();
182
+ if (!file)
183
+ throw new Error("Usage: orqen evidence <KEY> add <file> [--criterion N] [--note T]");
184
+ const c = o.value("criterion");
185
+ const e = ev.add(key, resolve(file), { criterion: c ? Number(c) : undefined, note: stdinOr(o.value("note")), name: o.value("name"), person: me() });
186
+ return out(json, { ok: true, evidence: e }, () => `✔ ${e.id} added to ${key}${e.criterion ? ` (criterion ${e.criterion})` : ""}`);
187
+ }
188
+ if (sub === "remove") {
189
+ const id = args.shift() ?? "";
190
+ ev.remove(key, id);
191
+ return out(json, { ok: true }, () => `✔ ${id} removed`);
192
+ }
193
+ throw new Error(`Unknown: orqen evidence ${key} ${sub}`);
194
+ }
195
+ // ------------------------------------------------------------------ automations
196
+ async function schedule(args, o, json) {
197
+ const store = new Schedules(stateDir());
198
+ const sub = args.shift() ?? "list";
199
+ const es = detectarIdioma() === "es";
200
+ switch (sub) {
201
+ case "list": {
202
+ const list = store.view(es);
203
+ return out(json, { schedules: list }, () => list.map((s) => `${s.id.padEnd(22)} ${s.enabled ? "on " : "off"} ${s.when.padEnd(24)} ${s.name}${s.last ? ` · last: ${s.last.worq ?? s.last.summary.slice(0, 50)}` : ""}`).join("\n") || "No automations.");
204
+ }
205
+ case "add": {
206
+ const mm = o.value("max-minutes");
207
+ const s = store.add({ name: o.value("name") ?? "", cron: o.value("cron") ?? "", prompt: stdinOr(o.value("prompt")), bot: o.value("bot"), agent: o.value("agent"),
208
+ maxMinutes: mm ? Number(mm) : undefined, notifyAlways: o.flag("notify-always") });
209
+ return out(json, { ok: true, schedule: s }, () => `✔ ${s.id} created`);
210
+ }
211
+ case "enable":
212
+ case "disable": {
213
+ const s = store.update(store.get(args.shift() ?? "").id, { enabled: sub === "enable" });
214
+ return out(json, { ok: true, schedule: s }, () => `✔ ${s.id} ${s.enabled ? "enabled" : "disabled"}`);
215
+ }
216
+ case "update": {
217
+ const s = store.get(args.shift() ?? "");
218
+ const mm = o.value("max-minutes");
219
+ const prompt = o.value("prompt");
220
+ const change = {};
221
+ for (const k of ["name", "cron", "bot", "agent"]) {
222
+ const v = o.value(k);
223
+ if (v !== undefined)
224
+ change[k] = v;
225
+ }
226
+ if (prompt !== undefined)
227
+ change.prompt = stdinOr(prompt);
228
+ if (mm)
229
+ change.maxMinutes = Number(mm);
230
+ const r = store.update(s.id, change);
231
+ return out(json, { ok: true, schedule: r }, () => `✔ ${r.id} updated`);
232
+ }
233
+ case "remove": {
234
+ const s = store.get(args.shift() ?? "");
235
+ store.remove(s.id);
236
+ return out(json, { ok: true }, () => `✔ ${s.id} removed`);
237
+ }
238
+ case "due": {
239
+ const due = store.due();
240
+ return out(json, { due: due.map((s) => s.id) }, () => due.map((s) => s.id).join("\n"));
241
+ }
242
+ case "run": {
243
+ const r = await runSchedule(store, store.get(args.shift() ?? ""));
244
+ return out(json, { ok: r.ok, run: r }, () => `${r.ok ? "✔" : "✘"} ${r.worq ? `created ${r.worq}` : r.summary}`);
245
+ }
246
+ case "tick": {
247
+ const lock = join(stateDir(), "schedules.lock");
248
+ if (existsSync(lock)) {
249
+ const age = Date.now() - Number(readFileSync(lock, "utf8") || 0);
250
+ if (age < 90 * 60_000)
251
+ return out(json, { ran: [], busy: true }, () => "Another tick is running.");
252
+ }
253
+ mkdirSync(stateDir(), { recursive: true });
254
+ writeFileSync(lock, String(Date.now()));
255
+ try {
256
+ const ran = [];
257
+ for (const s of store.due())
258
+ ran.push({ id: s.id, name: s.name, ...(await runSchedule(store, s)) });
259
+ return out(json, { ran }, () => ran.map((r) => `${r.ok ? "✔" : "✘"} ${r.id}: ${r.worq ? `created ${r.worq}` : r.summary}`).join("\n") || "Nothing due.");
260
+ }
261
+ finally {
262
+ rmSync(lock, { force: true });
263
+ }
264
+ }
265
+ }
266
+ throw new Error(`Unknown: orqen schedule ${sub}`);
267
+ }
268
+ /** Runs one automation in a throwaway worktree of the base branch; what it finds becomes a worq. */
269
+ async function runSchedule(store, s) {
270
+ const { loadConfig } = await import("../workflow/config.js");
271
+ const { Store } = await import("../workflow/store.js");
272
+ const { ejecutarAsync, partirComando } = await import("../lib/proc.js");
273
+ const cfg = loadConfig();
274
+ const main = mainWorktree(cfg.repoPath);
275
+ const before = new Set(new Store(cfg.stateDir).all().map((r) => r.key));
276
+ const dir = join(tmpdir(), `orqen-auto-${s.id}-${Date.now()}`);
277
+ const started = Date.now();
278
+ const git = (a) => execFileSync("git", a, { cwd: main, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
279
+ let ok = false, summary = "";
280
+ try {
281
+ try {
282
+ git(["worktree", "add", "--detach", dir, cfg.baseBranch]);
283
+ }
284
+ catch {
285
+ git(["worktree", "add", "--detach", dir, "HEAD"]);
286
+ }
287
+ let botPrompt = "";
288
+ if (s.bot) {
289
+ try {
290
+ const { readBots } = await import("../lib/bots.js");
291
+ botPrompt = readBots().find((b) => b.name.toLowerCase() === s.bot.toLowerCase())?.prompt ?? "";
292
+ }
293
+ catch { /* no bots file */ }
294
+ }
295
+ const prompt = [
296
+ botPrompt && `${botPrompt}\n`,
297
+ `You run unattended as the orqen automation "${s.name}" on a throwaway copy of ${cfg.baseBranch}. Nobody can answer you.`,
298
+ "Never commit, push, open a PR or change tickets. You may run commands and read anything.",
299
+ "If you find something the team should do, create ONE worq for it with:",
300
+ ' orqen new_worq - (stdin: {"title": "<short title>", "description": "<what you found, evidence, a proposed fix>"})',
301
+ "If there is nothing to do, do not create one.",
302
+ "End with one line: RESULT: <what you found, in one sentence>.",
303
+ "", "Task:", s.prompt,
304
+ ].filter(Boolean).join("\n");
305
+ const [bin, ...rest] = partirComando(s.agent || cfg.agentCmd);
306
+ const placeholder = rest.some((a) => a.includes("{prompt}"));
307
+ const r = await ejecutarAsync(bin, placeholder ? rest.map((a) => a.replace("{prompt}", prompt)) : rest, {
308
+ cwd: dir, entrada: placeholder ? undefined : prompt, timeoutMs: s.maxMinutes * 60_000,
309
+ env: { ...process.env, ORQEN_AGENT: `automation:${s.id}`, REPO_PATH: dir },
310
+ });
311
+ const text = `${r.stdout}\n${r.stderr}`;
312
+ summary = text.match(/RESULT:\s*(.+)/)?.[1]?.trim() ?? text.trim().split(/\r?\n/).filter(Boolean).at(-1)?.slice(0, 300) ?? "";
313
+ ok = r.codigo === 0;
314
+ if (!ok && !summary)
315
+ summary = `The agent ended with code ${r.codigo}`;
316
+ }
317
+ catch (e) {
318
+ summary = e.message.split("\n")[0];
319
+ }
320
+ finally {
321
+ try {
322
+ git(["worktree", "remove", "--force", dir]);
323
+ }
324
+ catch {
325
+ rmSync(dir, { recursive: true, force: true });
326
+ try {
327
+ git(["worktree", "prune"]);
328
+ }
329
+ catch { /* */ }
330
+ }
331
+ }
332
+ const worq = new Store(cfg.stateDir).all().map((r) => r.key).find((k) => !before.has(k));
333
+ const run = { at: new Date(started).toISOString(), secs: Math.round((Date.now() - started) / 1000), ok, ...(worq ? { worq } : {}), summary };
334
+ store.update(s.id, { last: run });
335
+ return run;
336
+ }
337
+ // ------------------------------------------------------------------ worktrees
338
+ function worktree(args, o, json) {
339
+ const sub = args.shift();
340
+ if (sub !== "prune")
341
+ throw new Error("Usage: orqen worktree prune [--dry-run] [--force] [--json]");
342
+ const dry = o.flag("dry-run"), force = o.flag("force");
343
+ const main = mainWorktree(repoRoot());
344
+ const git = (a, cwd = main) => execFileSync("git", a, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
345
+ // the state of each worq: orqen/state/<KEY>.json files hold { state }
346
+ const states = new Map();
347
+ const sd = stateDir();
348
+ try {
349
+ for (const r of new WorqStore(sd).all())
350
+ states.set(r.key.toUpperCase(), r.state);
351
+ }
352
+ catch { /* no state */ }
353
+ const trees = git(["worktree", "list", "--porcelain"]).split(/\r?\n\r?\n/).map((b) => {
354
+ const path = b.match(/^worktree (.+)$/m)?.[1]?.trim() ?? "";
355
+ const branch = b.match(/^branch refs\/heads\/(.+)$/m)?.[1]?.trim();
356
+ return { path, branch };
357
+ }).filter((t) => t.path && resolve(t.path) !== resolve(main));
358
+ const result = [];
359
+ for (const t of trees) {
360
+ const key = (t.branch?.startsWith("orqen/") ? t.branch.slice(6) : basename(t.path)).toUpperCase();
361
+ const state = states.get(key);
362
+ if (!state || !["CLOSED", "CANCELLED"].includes(state))
363
+ continue;
364
+ let dirty = false;
365
+ try {
366
+ dirty = !!git(["status", "--porcelain"], t.path).trim();
367
+ }
368
+ catch { /* missing folder: prune */ }
369
+ if (dirty && !force) {
370
+ result.push({ key, path: t.path, removed: false, why: "has uncommitted changes" });
371
+ continue;
372
+ }
373
+ if (!dry) {
374
+ try {
375
+ git(["worktree", "remove", ...(force ? ["--force"] : []), t.path]);
376
+ }
377
+ catch (e) {
378
+ result.push({ key, path: t.path, removed: false, why: e.message.split("\n")[0] });
379
+ continue;
380
+ }
381
+ }
382
+ result.push({ key, path: t.path, removed: !dry });
383
+ }
384
+ if (!dry) {
385
+ try {
386
+ git(["worktree", "prune"]);
387
+ }
388
+ catch { /* */ }
389
+ }
390
+ out(json, { dry_run: dry, worktrees: result }, () => result.length ? result.map((r) => `${r.removed ? "✔ removed" : dry && !r.why ? "· would remove" : "· kept"} ${r.key} ${r.path}${r.why ? ` (${r.why})` : ""}`).join("\n") : "No worktrees of delivered or cancelled worqs.");
391
+ }
@@ -18,7 +18,7 @@ import { detectarIdioma, normalizarIdioma } from "../lib/lang.js";
18
18
  import { ejecutarLinea } from "../lib/proc.js";
19
19
  import { pasosTutorial, textosUi } from "../tutorial/content.js";
20
20
  import { renderMarkdown, renderTerminal } from "../tutorial/render.js";
21
- import { pasosApp } from "../tutorial/app.js";
21
+ import { pasosApp, pasosStudio } from "../tutorial/app.js";
22
22
  import { interactivo, p, pc } from "../ui/console.js";
23
23
  /** Closest folder (this one or a parent) with orqen/config.yaml. */
24
24
  export function buscarRepo(desde) {
@@ -73,7 +73,7 @@ function comandoDemo(linea) {
73
73
  export async function tutorial(args) {
74
74
  const { values: v, positionals } = parseArgs({
75
75
  args, allowPositionals: true, strict: false,
76
- options: { step: { type: "string" }, list: { type: "boolean" }, json: { type: "boolean" }, lang: { type: "string" }, dir: { type: "string" } },
76
+ options: { step: { type: "string" }, list: { type: "boolean" }, json: { type: "boolean" }, studio: { type: "boolean" }, lang: { type: "string" }, dir: { type: "string" } },
77
77
  });
78
78
  const idioma = normalizarIdioma(v.lang) ?? detectarIdioma();
79
79
  const ui = textosUi(idioma);
@@ -87,8 +87,9 @@ export async function tutorial(args) {
87
87
  return;
88
88
  }
89
89
  const datos = datosDelRepo(repo);
90
- const pasos = pasosTutorial(datos, idioma);
91
- const temas = pasos.map((x, i) => ({ n: i + 1, id: x.id, title: x.titulo }));
90
+ const flujo = pasosTutorial(datos, idioma);
91
+ const pasos = v.studio ? [...flujo, ...pasosStudio(idioma)] : flujo;
92
+ const temas = pasos.map((x, i) => ({ n: i + 1, id: x.id, title: x.titulo, ...(i >= flujo.length ? { studio: true } : {}) }));
92
93
  if (v.list) {
93
94
  if (v.json)
94
95
  return console.log(JSON.stringify({ lang: idioma, topics: temas }, null, 2));
@@ -118,6 +119,7 @@ export async function tutorial(args) {
118
119
  lang: idioma, step: i + 1, total: pasos.length, id: paso.id, title: paso.titulo,
119
120
  next: pasos[i + 1]?.id ?? null, previous: pasos[i - 1]?.id ?? null,
120
121
  markdown: renderMarkdown(paso, enc), demo: paso.demo ?? [],
122
+ ...(i >= flujo.length ? { studio: true } : {}),
121
123
  // the same step done from the desktop app (the app shows both ways)
122
124
  app: appDe(paso) ? renderMarkdown({ ...paso, bloques: appDe(paso).bloques }, enc) : null,
123
125
  screen: appDe(paso)?.pantalla ?? null,
@@ -29,10 +29,10 @@ async function stageBots(repoPath, state) {
29
29
  return [];
30
30
  }
31
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"];
32
+ export const WORKFLOW_COMMANDS = ["list", "qa", "approve", "merged", "cancel", "undo", "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"];
33
33
  /** What people run: the 9 steps (as /orqen:* commands in their agent) and the CLI commands meant for a person. */
34
34
  export const WORKFLOW_HELP = `The 9 steps (run the /orqen:* commands in your agent: it calls the CLI for you):
35
- 1 /orqen:list requests orqen list requests [--json] [--all] [--mine] Everyone's work list, by role (--mine: only your roles)
35
+ 1 /orqen:list requests orqen list requests [--json] [--all] [--mine] [--overdue] Everyone's work list, by role (--mine: only your roles; --overdue: past workflow.sla_hours)
36
36
  2 /orqen:support <KEY> First-line support: answer the client or escalate to the analyst
37
37
  3 /orqen:analyze <KEY> Analysis with the analyst: criteria, lane, spec and the issue
38
38
  4 /orqen:list issues orqen list issues [--json] Development queue (free, taken, came back)
@@ -57,7 +57,8 @@ Request commands for people:
57
57
  <brief.json|-> Alone: the title goes in the brief ("title"), as orqen-studio sends it
58
58
  {title, description} Only that: born in ANALYSIS, then /orqen:analyze asks the person what is missing
59
59
  cancel <KEY> --reason T Close the request without delivering it: closes the PR unmerged, comments both tickets (CANCELLED)
60
- release <KEY> Free a request held by an agent that is no longer working on it
60
+ undo <KEY> --reason T Undo its last move (an /approve by mistake, a cancellation...): back to the previous state with its record as it was; again goes further back
61
+ release <KEY> Free a request held by an agent that is no longer working on it (also one taken in another session)
61
62
  comments <KEY> [--json] Read the request and its conversation with the client
62
63
  comment <KEY> <file|-> Reply to the client on the request (--person NAME)
63
64
  connectors [setup] Show and check the connectors (requests and issues), or set them up
@@ -81,7 +82,7 @@ export const WORKFLOW_INTERNAL_HELP = `Agent-only commands (the /orqen:* command
81
82
  block <KEY> <reason> Escalate to a person on the ticket
82
83
  search <query> Search tickets (precedents, related work)
83
84
 
84
- --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
85
+ --dry-run (complete, pr, approve, cancel, undo, new_worq): runs the command's checks and shows what it would do on the tickets, Git and the PR, without doing it
85
86
 
86
87
  Older names (still work, with a notice): pending → list requests · qa → review
87
88
 
@@ -118,8 +119,10 @@ export async function runWorkflow(cmd, rest) {
118
119
  dry?.finish();
119
120
  } // what it would have done, and the temporary copy is deleted
120
121
  }
122
+ /** 30 → "30 h", 72 → "3 d": how long a worq has been in a state, against its SLA. */
123
+ const hoursText = (h) => (h < 1 ? `${Math.round(h * 60)} min` : h < 48 ? `${Math.round(h * 10) / 10} h` : `${Math.round((h / 24) * 10) / 10} d`);
121
124
  /** 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"]);
125
+ const KNOWN_OPTIONS = new Set(["agent", "all", "analyst", "apply", "changes", "comment", "dir", "dry-run", "every", "expected", "force", "issue", "json", "loop", "matches", "mine", "once", "overdue", "person", "reason", "report", "since", "step", "title", "verdict"]);
123
126
  /**
124
127
  * `<command> --dry-run --json`: {"dry_run": true, "ok", "plan": [{kind, text}], "output": [lines], "errors": [lines]}.
125
128
  * `ok` is false when the command would fail (its checks did not pass): `errors` says why and `plan` is what it got to do.
@@ -230,7 +233,8 @@ async function runCommand(cmd, rest, onDryRun) {
230
233
  `# ${key} — stage ${s}`,
231
234
  "",
232
235
  withHuman
233
- ? "> **You are working with a person.** Before each important step, tell them what you are about to do and wait for their OK. " +
236
+ ? "> **You are working with a person.** Run every command yourself (never ask them to type an `orqen`, `/orqen:*`, `/approve` or shell command). " +
237
+ "Before each decision that is theirs, tell them what you are about to do and wait for their OK; steps that need no decision, just do and report. " +
234
238
  "When in doubt, ask them (concrete options plus your recommendation) instead of assuming. See \"Working with the person\" in AGENTS.md. " +
235
239
  `Talk to them in ${ctx.language === "es" ? "Spanish" : "English"} (their system language).`
236
240
  : "> **Unattended mode: nobody can answer you.** Do not assume. If a doubt changes the outcome, run " +
@@ -321,20 +325,26 @@ async function runCommand(cmd, rest, onDryRun) {
321
325
  const me2 = whoIs(cfg.people, me);
322
326
  board = board.filter((b) => me2.roles.includes(b.role));
323
327
  }
328
+ // --overdue: only the ones past their limit in workflow.sla_hours
329
+ const overdueOnly = has("overdue");
330
+ if (overdueOnly)
331
+ board = board.filter((b) => b.sla?.overdue);
332
+ const late = (b) => b.sla?.overdue ? ` ⚠ ${hoursText(b.sla.hours)} in ${b.state} (SLA ${hoursText(b.sla.limit)})` : "";
333
+ const taken = (b) => b.takenBy ? `taken by ${b.takenBy}${b.takenIn ? ` in another session (${b.takenIn})` : ""}` : "";
324
334
  if (what === "issues") {
325
335
  const q = board.filter((b) => b.state === "DEVELOPMENT");
326
336
  if (json)
327
337
  return console.log(JSON.stringify(q, null, 2));
328
338
  if (!q.length)
329
- return console.log("No issues in development.");
339
+ return console.log(overdueOnly ? "No issues in development past their SLA." : "No issues in development.");
330
340
  for (const b of q)
331
- console.log(` ${b.work.padEnd(12)} ${(b.lane ?? "").padEnd(7)} ${b.estimated_hours !== undefined ? `${b.estimated_hours}h`.padEnd(6) : "".padEnd(6)} ${b.takenBy ? `taken by ${b.takenBy}` : "free"}${b.returned ? ` ↩ ${b.returned.split("\n")[0].slice(0, 80)}` : ""}`);
341
+ console.log(` ${b.work.padEnd(12)} ${(b.lane ?? "").padEnd(7)} ${b.estimated_hours !== undefined ? `${b.estimated_hours}h`.padEnd(6) : "".padEnd(6)} ${taken(b) || "free"}${b.returned ? ` ↩ ${b.returned.split("\n")[0].slice(0, 80)}` : ""}${late(b)}`);
332
342
  return;
333
343
  }
334
344
  if (json)
335
345
  return console.log(JSON.stringify(board, null, 2));
336
346
  if (!board.length)
337
- return console.log("No open requests.");
347
+ return console.log(overdueOnly ? (Object.keys(cfg.sla).length ? "Nothing past its SLA." : "No SLA set: add workflow.sla_hours to orqen/config.yaml (for example CODE_REVIEW: 24, default: 72).") : "No open requests.");
338
348
  const titles = { support: "Support (L1)", analyst: "Analyst (L2)", developer: "Development", qa: "QA", senior: "Senior", client: "Waiting for the client", gate: "Waiting for an approval on the request", blocked: "Blocked", done: "Closed" };
339
349
  for (const role of Object.keys(titles)) {
340
350
  const xs = board.filter((b) => b.role === role);
@@ -342,8 +352,12 @@ async function runCommand(cmd, rest, onDryRun) {
342
352
  continue;
343
353
  console.log(`${titles[role]}:`);
344
354
  for (const b of xs)
345
- 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)"}` : ""}`);
355
+ console.log(` ${b.work.padEnd(12)} ${b.state.padEnd(15)} ${(b.next[0]?.command ?? "").padEnd(28)} ${b.takenBy ? `(${taken(b)} 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)"}` : ""}${late(b)}`);
346
356
  }
357
+ // the warning: what is past its SLA, also when it is in a role that is not the reader's
358
+ const over = board.filter((b) => b.sla?.overdue);
359
+ if (over.length && !overdueOnly)
360
+ console.log(`\n⚠ ${over.length} past their SLA (workflow.sla_hours): ${over.map((b) => `${b.work} ${b.state} ${hoursText(b.sla.hours)}/${hoursText(b.sla.limit)}`).join(" · ")}. Only those: orqen list --overdue`);
347
361
  return;
348
362
  }
349
363
  case "qa": {
@@ -435,6 +449,23 @@ async function runCommand(cmd, rest, onDryRun) {
435
449
  }
436
450
  return;
437
451
  }
452
+ case "undo": {
453
+ try {
454
+ const reasonArg = flag("reason") ?? "";
455
+ const reason = reasonArg === "-" ? readFileSync(0, "utf8") : reasonArg;
456
+ const key = toKey(rest[0]);
457
+ if (!key)
458
+ throw new Error('Usage: orqen undo <KEY> --reason "<why>" [--person NAME] [--dry-run]');
459
+ const r = await flow.undo(key, reason, me || agent, agent, flag("expected"));
460
+ console.log(`✔ ${rest[0]}: ${r.from} → ${r.to} (undone)${r.restored ? "" : " · only the state: that move was recorded by an earlier version of orqen, so its record was not restored"}`);
461
+ console.log(" What happened outside orqen stays: the comments already posted, the commits" + (r.pr ? `, and the PR closed when it was cancelled (reopen it by hand if needed: ${r.pr})` : ", and a PR closed or merged") + ".");
462
+ }
463
+ catch (e) {
464
+ console.error(`✘ ${e.message}`);
465
+ process.exitCode = 1;
466
+ }
467
+ return;
468
+ }
438
469
  case "gate": {
439
470
  const json = has("json");
440
471
  try {
@@ -699,7 +730,7 @@ async function runCommand(cmd, rest, onDryRun) {
699
730
  await flow.block(toKey(rest[0]), rest.slice(1).join(" "), agent);
700
731
  return console.log("✔ blocked");
701
732
  case "release":
702
- flow.release(toKey(rest[0]));
733
+ flow.release(toKey(rest[0]), flag("expected"));
703
734
  return console.log("✔ released");
704
735
  case "search": {
705
736
  const keys = (await connectors.requests.search(rest.join(" "))).slice(0, 20);
@@ -773,13 +804,22 @@ async function runCommand(cmd, rest, onDryRun) {
773
804
  if (rest[0]) {
774
805
  const k = toKey(rest[0]);
775
806
  const item = flow.item(k) ?? await flow.peek(k);
776
- const b = item ? flow.boardItem(item) : undefined;
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));
807
+ if (!item)
808
+ return console.log("null");
809
+ const b = flow.boardItem(item);
810
+ const lastMove = store.get(item.key) ? flow.undoable(item.key) : undefined;
811
+ const canUndo = lastMove?.to === item.state && !(item.origin === "internal" && item.state === "CLOSED" && item.artifacts.devel_pr_merged);
812
+ return console.log(JSON.stringify({
813
+ ...item, role: b.role, next: b.next, qa_status: b.qa, returned: b.returned, sla: b.sla,
814
+ reservation: b.takenBy ? { agent: b.takenBy, since: b.since, elsewhere: b.takenIn } : undefined,
815
+ undo: canUndo ? { stage: lastMove.from, expected: lastMove.ts } : undefined,
816
+ events: store.events(item.key), usage: runUsage(cfg.repoPath, item.key), bots: await stageBots(cfg.repoPath, item.state),
817
+ }, null, 2));
778
818
  }
779
819
  return console.log(JSON.stringify(store.all().map((r) => ({
780
820
  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,
781
821
  change: r.change || undefined, analyst: r.analyst, supporter: r.supporter, lock: r.lock, devel_pr: r.artifacts?.devel_pr,
782
- updated: store.events(r.key).at(-1)?.ts,
822
+ updated: store.events(r.key).at(-1)?.ts, sla: flow.slaOf(r),
783
823
  })), null, 2));
784
824
  }
785
825
  if (rest[0]) {
@@ -810,7 +850,7 @@ async function runCommand(cmd, rest, onDryRun) {
810
850
  return;
811
851
  }
812
852
  }
813
- const r = buildReport(store.all().map((item) => ({ item, events: store.events(item.key) })), { from });
853
+ const r = buildReport(store.all().map((item) => ({ item, events: store.events(item.key) })), { from, sla: cfg.sla });
814
854
  if (json)
815
855
  console.log(JSON.stringify(r, null, 2));
816
856
  else
@@ -262,6 +262,10 @@ export class GithubTracker {
262
262
  async finish(key, reason) {
263
263
  await this.req("PATCH", `/repos/{repo}/issues/${this.n(key)}`, { state: "closed", state_reason: reason });
264
264
  }
265
+ /** Opens the issue again (`orqen undo` of a closed or cancelled request). Idempotent. */
266
+ async reopen(key) {
267
+ await this.req("PATCH", `/repos/{repo}/issues/${this.n(key)}`, { state: "open", state_reason: "reopened" });
268
+ }
265
269
  async project() {
266
270
  if (this.projectCache)
267
271
  return this.projectCache;