@telpin-sistemas/orqen 0.1.15 → 0.1.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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", "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.
@@ -321,20 +324,26 @@ async function runCommand(cmd, rest, onDryRun) {
321
324
  const me2 = whoIs(cfg.people, me);
322
325
  board = board.filter((b) => me2.roles.includes(b.role));
323
326
  }
327
+ // --overdue: only the ones past their limit in workflow.sla_hours
328
+ const overdueOnly = has("overdue");
329
+ if (overdueOnly)
330
+ board = board.filter((b) => b.sla?.overdue);
331
+ const late = (b) => b.sla?.overdue ? ` ⚠ ${hoursText(b.sla.hours)} in ${b.state} (SLA ${hoursText(b.sla.limit)})` : "";
332
+ const taken = (b) => b.takenBy ? `taken by ${b.takenBy}${b.takenIn ? ` in another session (${b.takenIn})` : ""}` : "";
324
333
  if (what === "issues") {
325
334
  const q = board.filter((b) => b.state === "DEVELOPMENT");
326
335
  if (json)
327
336
  return console.log(JSON.stringify(q, null, 2));
328
337
  if (!q.length)
329
- return console.log("No issues in development.");
338
+ return console.log(overdueOnly ? "No issues in development past their SLA." : "No issues in development.");
330
339
  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)}` : ""}`);
340
+ 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
341
  return;
333
342
  }
334
343
  if (json)
335
344
  return console.log(JSON.stringify(board, null, 2));
336
345
  if (!board.length)
337
- return console.log("No open requests.");
346
+ 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
347
  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
348
  for (const role of Object.keys(titles)) {
340
349
  const xs = board.filter((b) => b.role === role);
@@ -342,8 +351,12 @@ async function runCommand(cmd, rest, onDryRun) {
342
351
  continue;
343
352
  console.log(`${titles[role]}:`);
344
353
  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)"}` : ""}`);
354
+ 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
355
  }
356
+ // the warning: what is past its SLA, also when it is in a role that is not the reader's
357
+ const over = board.filter((b) => b.sla?.overdue);
358
+ if (over.length && !overdueOnly)
359
+ 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
360
  return;
348
361
  }
349
362
  case "qa": {
@@ -435,6 +448,22 @@ async function runCommand(cmd, rest, onDryRun) {
435
448
  }
436
449
  return;
437
450
  }
451
+ case "undo": {
452
+ try {
453
+ const reason = flag("reason") ?? "";
454
+ const key = toKey(rest[0]);
455
+ if (!key)
456
+ throw new Error('Usage: orqen undo <KEY> --reason "<why>" [--person NAME] [--dry-run]');
457
+ const r = await flow.undo(key, reason, me || agent, agent);
458
+ 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"}`);
459
+ 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") + ".");
460
+ }
461
+ catch (e) {
462
+ console.error(`✘ ${e.message}`);
463
+ process.exitCode = 1;
464
+ }
465
+ return;
466
+ }
438
467
  case "gate": {
439
468
  const json = has("json");
440
469
  try {
@@ -810,7 +839,7 @@ async function runCommand(cmd, rest, onDryRun) {
810
839
  return;
811
840
  }
812
841
  }
813
- const r = buildReport(store.all().map((item) => ({ item, events: store.events(item.key) })), { from });
842
+ const r = buildReport(store.all().map((item) => ({ item, events: store.events(item.key) })), { from, sla: cfg.sla });
814
843
  if (json)
815
844
  console.log(JSON.stringify(r, null, 2));
816
845
  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;
@@ -47,7 +47,7 @@ export const CONFIG_KEYS = {
47
47
  approvers: { as: "aprobadores", keys: { analysis: "analisis", qa: "qa", code: "codigo", client: "cliente", execution: "ejecucion" } },
48
48
  code_review: { as: "code_review", keys: { gate: "gate", reviewers: "revisores" } },
49
49
  devel_branch: "rama_desarrollo", pr_command: "comando_pr", test_command: "comando_tests", people: "personas",
50
- lock_minutes: "lock_min", interval_seconds: "intervalo_seg",
50
+ lock_minutes: "lock_min", interval_seconds: "intervalo_seg", sla_hours: "sla_horas",
51
51
  },
52
52
  },
53
53
  // files of earlier versions kept these two in config.yaml
@@ -52,6 +52,11 @@ export const Flujo = z.object({
52
52
  /** Minutes a taken request stays reserved (ORQEN_LOCK_MIN) and seconds between rounds of `orqen cycle --loop` (ORQEN_INTERVAL_SEC). */
53
53
  lock_min: z.number().int().positive().nullish(),
54
54
  intervalo_seg: z.number().int().positive().nullish(),
55
+ /**
56
+ * Hours a worq may stay in a state before `orqen list` and `orqen report` mark it as overdue (ORQEN_SLA_HOURS), by state
57
+ * (CODE_REVIEW: 24) and `default` for the states not listed; 0 = no limit for that state. Wall-clock hours, waiting included.
58
+ */
59
+ sla_horas: z.record(z.string(), z.number().nonnegative()).nullish(),
55
60
  });
56
61
  export const Config = z.object({
57
62
  version: z.literal(1),
@@ -1,5 +1,6 @@
1
1
  import { execFileSync } from "node:child_process";
2
2
  import { existsSync } from "node:fs";
3
+ import { hostname } from "node:os";
3
4
  import { basename, dirname, join, resolve } from "node:path";
4
5
  import { fileURLToPath } from "node:url";
5
6
  import { TEMPLATES_DIR } from "../lib/template-assets.js";
@@ -12,6 +13,14 @@ const env = (k, d = "") => process.env[k] ?? d;
12
13
  const split = (v) => v.split(",").map((s) => s.trim()).filter(Boolean);
13
14
  /** New variable name, falling back to the one used by earlier versions. */
14
15
  const envL = (k, legacy, d = "") => envWithLegacy(process.env, k, legacy, d);
16
+ /** ORQEN_SLA_HOURS="CODE_REVIEW=24, default=48" → { CODE_REVIEW: 24, default: 48 }. */
17
+ export function parseSla(v) {
18
+ return Object.fromEntries(split(v).map((p) => p.split("=").map((s) => s.trim())).filter(([k, h]) => k && h !== undefined && !Number.isNaN(Number(h))).map(([k, h]) => [k, Number(h)]));
19
+ }
20
+ /** The SLA per state with upper-case keys (`default` → DEFAULT), whatever case the file used. */
21
+ export function slaHours(v) {
22
+ return Object.fromEntries(Object.entries(v).filter(([, h]) => typeof h === "number" && h >= 0).map(([k, h]) => [k.trim().toUpperCase(), h]));
23
+ }
15
24
  export function repoRoot() {
16
25
  try {
17
26
  return execFileSync("git", ["rev-parse", "--show-toplevel"], { cwd: process.cwd(), encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
@@ -83,6 +92,8 @@ export function loadConfig(over = {}) {
83
92
  stagesDir: stages ?? join(TEMPLATES_DIR, "stages"),
84
93
  environment: project?.entornos,
85
94
  lockMinutes: Number(envL("ORQEN_LOCK_MIN", "REC_LOCK_MIN") || f?.lock_min || 90),
95
+ session: env("ORQEN_SESSION") || `${hostname()}:${resolve(repoPath).replaceAll("\\", "/")}`,
96
+ sla: slaHours(env("ORQEN_SLA_HOURS") ? parseSla(env("ORQEN_SLA_HOURS")) : f?.sla_horas ?? {}),
86
97
  // Headless agent command for `orqen cycle`. {prompt} is replaced (already escaped).
87
98
  agentCmd: env("AGENT_CMD") || project?.agente.comando || "claude -p --permission-mode acceptEdits",
88
99
  intervalSec: Number(envL("ORQEN_INTERVAL_SEC", "REC_INTERVAL_SEC") || f?.intervalo_seg || 120),
@@ -1,2 +1,2 @@
1
1
  /** The commands that take `--dry-run` (see dry-run.ts). Its own module so process.ts can mark them without importing dry-run.ts. */
2
- export const DRY_RUN_COMMANDS = ["complete", "pr", "approve", "cancel", "new_worq", "new-worq"];
2
+ export const DRY_RUN_COMMANDS = ["complete", "pr", "approve", "cancel", "undo", "new_worq", "new-worq"];
@@ -69,7 +69,7 @@ export class DryRun {
69
69
  const fakeKey = (k) => this.fakeTickets.has(k);
70
70
  const stub = (k) => { const t = this.fakeTickets.get(k); return { key: k, title: t.title, description: t.description, labels: t.labels ?? [], components: [], attachments: [], url: `(dry run) ${k}` }; };
71
71
  const g = guard(real, ["pending", "search", "labelled", "check", "ticket", "comments", "url", "statuses", "projects", "repositories"], {
72
- comment: async () => { }, setStateLabel: async () => { }, transition: async () => true, addLabel: async () => { }, link: async () => { }, finish: async () => { },
72
+ comment: async () => { }, setStateLabel: async () => { }, transition: async () => true, addLabel: async () => { }, link: async () => { }, finish: async () => { }, reopen: async () => { },
73
73
  create: async (t) => { const k = `DRY-${this.fakeTickets.size + 1}`; this.fakeTickets.set(k, t); return k; },
74
74
  }, (n, a) => {
75
75
  const add = (text) => this.plan.push({ kind: "ticket", text });
@@ -80,6 +80,7 @@ export class DryRun {
80
80
  case "addLabel": return add(`add label "${a[1]}" to ${a[0]} (${name})`);
81
81
  case "link": return add(`link ${a[0]} with ${a[1]}`);
82
82
  case "finish": return add(`close ${a[0]} as ${a[1] === "not_planned" ? "not planned" : "completed"} (${name})`);
83
+ case "reopen": return add(`reopen ${a[0]} (${name})`);
83
84
  case "create": return add(`create ticket "${a[0].title}" (${name}${a[0].labels?.length ? `, labels ${a[0].labels.join(", ")}` : ""})`);
84
85
  default: return add(`${n}(${a.map((x) => JSON.stringify(x)).join(", ").slice(0, 80)}) (${name})`);
85
86
  }
@@ -122,9 +122,25 @@ export class Process {
122
122
  internal: item.origin === "internal" || undefined,
123
123
  analyst: item.analyst, supporter: item.supporter, request_url: this.requests.url(item.key),
124
124
  issue_url: item.issue && this.issues ? this.issues.url(item.issue) : undefined,
125
- dir: this.worqRel(item.key), updated: this.store.events(item.key).at(-1)?.ts, next: b.next,
125
+ dir: this.worqRel(item.key), updated: this.store.events(item.key).at(-1)?.ts, next: b.next, sla: b.sla,
126
126
  };
127
127
  }
128
+ /**
129
+ * workflow.sla_hours: how long the worq has been in its current state against the limit for that state (DEFAULT for the
130
+ * ones not listed). Nothing for a closed worq, a state without a limit, or one whose entry into the state was not recorded.
131
+ */
132
+ slaOf(item, now = Date.now()) {
133
+ if (isFinal(item.state) || item.recovered)
134
+ return undefined;
135
+ const limit = this.cfg.sla[item.state] ?? this.cfg.sla.DEFAULT;
136
+ if (!limit)
137
+ return undefined;
138
+ const entered = [...this.store.events(item.key)].reverse().find((e) => e.to === item.state && e.from !== e.to);
139
+ if (!entered)
140
+ return undefined;
141
+ const hours = Math.round(((now - Date.parse(entered.ts)) / 3_600_000) * 10) / 10;
142
+ return { hours, limit, since: entered.ts, overdue: hours > limit };
143
+ }
128
144
  /** Folder of a worq inside the repository, as written in tickets and messages (orqen/worqs/<KEY>); the default when the folder is elsewhere. */
129
145
  worqRel(key) {
130
146
  const rel = relative(this.cfg.repoPath, join(this.cfg.factoryDir, key)).replaceAll("\\", "/");
@@ -256,8 +272,8 @@ export class Process {
256
272
  const lock = this.activeLock(item);
257
273
  return {
258
274
  key: item.key, title: item.title ?? item.artifacts?.ANALYSIS?.summary, issue: item.issue, work: workKey(item), state: item.state, lane: item.lane, route: item.route,
259
- role: roleOf(item, this.cfg), takenBy: lock?.agent, since: lock?.since, returned: returned(item),
260
- estimated_hours: item.artifacts.estimated_hours, pr: item.artifacts.devel_pr,
275
+ role: roleOf(item, this.cfg), takenBy: lock?.agent, since: lock?.since, takenIn: this.elsewhere(lock), returned: returned(item),
276
+ estimated_hours: item.artifacts.estimated_hours, pr: item.artifacts.devel_pr, sla: this.slaOf(item),
261
277
  qa: needsQa(item) && item.state === "QA_REVIEW" ? "pending" : needsQa(item) && item.state === "CODE_REVIEW" ? "approved" : undefined,
262
278
  recovered: item.recovered,
263
279
  next: item.recovered
@@ -509,8 +525,10 @@ export class Process {
509
525
  throw new Error(this.unknownMsg(key));
510
526
  if (item.state !== "ANALYSIS")
511
527
  throw new Error(`${key} is not in ANALYSIS (state: ${item.state}).`);
512
- const lock = this.activeLock(item) ?? (item.lock?.agent === agent ? item.lock : undefined);
513
- if (!lock || lock.agent !== agent)
528
+ const lock = this.activeLock(item) ?? (item.lock && this.holds(item.lock, agent) ? item.lock : undefined);
529
+ if (lock && !this.holds(lock, agent) && lock.agent === agent)
530
+ throw new Error(this.takenMsg(key, lock));
531
+ if (!lock || !this.holds(lock, agent))
514
532
  throw new Error(`Run \`orqen analyze ${key}\` first`);
515
533
  if (!LANES.includes(lane))
516
534
  throw new Error(`Invalid lane "${lane}". Options: ${LANES.join(", ")}`);
@@ -561,7 +579,7 @@ export class Process {
561
579
  if (item.origin === "internal" && item.state === "DELIVERY")
562
580
  throw new Error(`${key} is a worq started by the team: there is no delivery to a client. It closes by itself when its PR is merged (orqen merged ${key} if orqen cannot read it).`);
563
581
  this.assertClaimable(item, agent);
564
- item.lock = { agent, since: new Date().toISOString() };
582
+ item.lock = { agent, since: new Date().toISOString(), session: this.cfg.session };
565
583
  this.store.save(item);
566
584
  const ticket = await this.requests.ticket(key);
567
585
  if (ticket.title && item.title !== ticket.title) {
@@ -803,11 +821,11 @@ export class Process {
803
821
  if (!item || !isAgentState(item.state))
804
822
  return { ok: false, errors: [`${key} is not in an agent stage`] };
805
823
  // an expired lock stays valid while nobody else took the request (the grilling can last longer than ORQEN_LOCK_MIN)
806
- const lock = this.activeLock(item) ?? (item.lock?.agent === agent ? item.lock : undefined);
824
+ const lock = this.activeLock(item) ?? (item.lock && this.holds(item.lock, agent) ? item.lock : undefined);
807
825
  if (!lock)
808
826
  return { ok: false, errors: [`Run \`orqen ${item.state === "ANALYSIS" ? "analyze" : item.state === "SUPPORT" ? "support" : "take"} ${key}\` first`] };
809
- if (lock.agent !== agent)
810
- return { ok: false, errors: [`${key} is taken by "${lock.agent}"`] };
827
+ if (!this.holds(lock, agent))
828
+ return { ok: false, errors: [this.elsewhere(lock) && lock.agent === agent ? this.takenMsg(key, lock) : `${key} is taken by "${lock.agent}"`] };
811
829
  const state = item.state;
812
830
  const parsed = SCHEMAS[state].safeParse(raw);
813
831
  if (!parsed.success)
@@ -1294,7 +1312,7 @@ export class Process {
1294
1312
  description: `${description || t}\n\n${brief}\n\nCreated with orqen (no client request).`,
1295
1313
  });
1296
1314
  }
1297
- const item = { ...newWorkItem(key), state: "ANALYSIS", origin: "internal", title: t, analyst: person, lock: { agent: "internal", since: new Date().toISOString() } };
1315
+ const item = { ...newWorkItem(key), state: "ANALYSIS", origin: "internal", title: t, analyst: person, lock: { agent: "internal", since: new Date().toISOString(), session: this.cfg.session } };
1298
1316
  this.store.save(item);
1299
1317
  let r;
1300
1318
  try {
@@ -1447,6 +1465,78 @@ export class Process {
1447
1465
  await this.move(item, "CANCELLED", `cancelled by ${person}: ${reason.trim()}`, agent, person);
1448
1466
  return { state: item.state, pr, url };
1449
1467
  }
1468
+ // ================================================================ undo
1469
+ /** The move `orqen undo` reverts: the last one that is not an undo nor undone by one, so undoing again goes further back. */
1470
+ undoable(key) {
1471
+ let skip = 0;
1472
+ for (const e of [...this.store.events(key)].reverse()) {
1473
+ if (e.from === e.to)
1474
+ continue; // a note in the log (PR opened, record recovered...), not a move
1475
+ if (e.undo) {
1476
+ skip++;
1477
+ continue;
1478
+ }
1479
+ if (skip) {
1480
+ skip--;
1481
+ continue;
1482
+ }
1483
+ return e;
1484
+ }
1485
+ return undefined;
1486
+ }
1487
+ /**
1488
+ * `orqen undo <KEY> --reason`: takes the worq back to the state it was in before its last move (an /approve by mistake, a
1489
+ * rejection that should not have counted, a cancellation...), with its record as it was then: round, lane, change, issue,
1490
+ * feedback and counters. What happened outside orqen stays as it is: the comments already posted, a PR closed or merged, the
1491
+ * commits. The facts orqen read from outside are kept too (the PR, its merge, the GitHub reviews already handled) so that nothing
1492
+ * is replayed, and the comments before the undo do not count again at a gate. Running it again goes one more move back.
1493
+ */
1494
+ async undo(key, reason, person, agent = "agent") {
1495
+ const item = this.item(key);
1496
+ if (!item)
1497
+ throw new Error(this.unknownMsg(key));
1498
+ if (reason.trim().length < 5)
1499
+ throw new Error("Say why the move is undone (--reason): it goes on the request.");
1500
+ this.assertClaimable(item, agent);
1501
+ const e = this.undoable(key);
1502
+ if (!e)
1503
+ throw new Error(`${key} has no move to undo.`);
1504
+ if (e.to !== item.state)
1505
+ throw new Error(`${key} is in ${item.state} but its last recorded move went to ${e.to}: the record and its log do not agree, so nothing was undone. Look at it with orqen worq ${workKey(item)}.`);
1506
+ const a = item.artifacts;
1507
+ if (item.origin === "internal" && item.state === "CLOSED" && a.devel_pr_merged)
1508
+ throw new Error(`${key} closed because its PR was merged (${a.devel_pr}): back in DELIVERY it would close again by itself. Start a new worq for what is missing (orqen new_worq).`);
1509
+ const back = e.before
1510
+ ? { ...newWorkItem(key), ...structuredClone(e.before), key, state: item.state }
1511
+ : { ...structuredClone(item) }; // a move recorded by an earlier version: only the state goes back
1512
+ // facts read from outside: undoing the move does not undo them, and forgetting them would replay them
1513
+ for (const k of ["devel_pr", "devel_pr_merged", "handled_reviews"])
1514
+ if (a[k] !== undefined)
1515
+ back.artifacts[k] = a[k];
1516
+ if (!back.issue && item.issue) {
1517
+ back.issue = item.issue;
1518
+ back.artifacts.issue_linked = a.issue_linked;
1519
+ }
1520
+ back.title = item.title ?? back.title;
1521
+ delete back.artifacts.sync_pending;
1522
+ delete back.lock;
1523
+ const blockedFrom = back.stateBeforeBlock;
1524
+ const note = item.state === "CANCELLED" && a.cancelled?.pr === "closed" ? `\nThe PR was closed when it was cancelled: reopen it by hand if it is still needed (${a.devel_pr}).` : "";
1525
+ await this.commentBoth(back, `Undone by ${person}: ${item.state} → ${e.from}.\nReason: ${reason.trim()}${note}`);
1526
+ await this.move(back, e.from, `undo by ${person}: ${reason.trim()} (was ${item.state})`, agent, person, { undo: true });
1527
+ // back to BLOCKED: it unblocks to where it was blocked from then, not to the state it is coming back from
1528
+ if (e.from === "BLOCKED" && blockedFrom && back.stateBeforeBlock !== blockedFrom) {
1529
+ back.stateBeforeBlock = blockedFrom;
1530
+ this.store.save(back);
1531
+ }
1532
+ if (isFinal(item.state)) {
1533
+ // the tickets were closed with the worq: open them again (where the column alone does not, see Tracker.reopen)
1534
+ await this.attemptAsync(() => this.requests.reopen?.(key) ?? Promise.resolve());
1535
+ if (back.issue && this.issues)
1536
+ await this.attemptAsync(() => this.issues.reopen?.(back.issue) ?? Promise.resolve());
1537
+ }
1538
+ return { from: item.state, to: e.from, restored: !!e.before, pr: item.state === "CANCELLED" && a.cancelled?.pr === "closed" ? a.devel_pr : undefined };
1539
+ }
1450
1540
  // ================================================================ utilities
1451
1541
  async block(key, reason, agent = "agent") {
1452
1542
  const item = this.item(key) ?? newWorkItem(key);
@@ -1464,8 +1554,21 @@ export class Process {
1464
1554
  }
1465
1555
  assertClaimable(item, agent) {
1466
1556
  const lock = this.activeLock(item);
1467
- if (lock && lock.agent !== agent)
1468
- throw new Error(`${item.key} was already taken by "${lock.agent}" since ${lock.since}.`);
1557
+ if (lock && !this.holds(lock, agent))
1558
+ throw new Error(this.takenMsg(item.key, lock));
1559
+ }
1560
+ /** Whether `agent` in this session holds the lock. A lock of an earlier version (no session) is held by any session of that agent. */
1561
+ holds(lock, agent) {
1562
+ return lock.agent === agent && (!lock.session || lock.session === this.cfg.session);
1563
+ }
1564
+ /** Where the lock was taken, when it is not this session: what `orqen list` shows and the refusals say. */
1565
+ elsewhere(lock) {
1566
+ return lock?.session && lock.session !== this.cfg.session ? lock.session : undefined;
1567
+ }
1568
+ takenMsg(key, lock) {
1569
+ const where = this.elsewhere(lock);
1570
+ return `${key} was already taken by "${lock.agent}"${where ? ` in another session (${where})` : ""} since ${lock.since}.` +
1571
+ (where ? ` If that session is gone, free it with \`orqen release ${key}\`.` : "");
1469
1572
  }
1470
1573
  activeLock(item) {
1471
1574
  if (!item.lock)
@@ -1491,8 +1594,12 @@ export class Process {
1491
1594
  }
1492
1595
  }
1493
1596
  /** `person`: who decided or did it (a person's name), when it was a person; the Worq's Activity shows it. */
1494
- async move(item, to, detail, agent, person) {
1597
+ async move(item, to, detail, agent, person, opts = {}) {
1495
1598
  const from = item.state;
1599
+ // the record as saved before this operation changed it in memory: what `orqen undo` restores
1600
+ const saved = this.store.get(item.key);
1601
+ const base = saved ?? (from === "NEW" ? newWorkItem(item.key) : undefined); // a request nobody had touched: nothing saved yet
1602
+ const before = base && base.state === from ? (({ lock: _l, recovered: _r, ...rest }) => rest)(base) : undefined;
1496
1603
  if (to === "BLOCKED" && from !== "BLOCKED")
1497
1604
  item.stateBeforeBlock = from;
1498
1605
  item.state = to;
@@ -1505,7 +1612,7 @@ export class Process {
1505
1612
  item.lastSeenComment = (ours ?? cs.at(-1))?.id ?? "";
1506
1613
  }
1507
1614
  this.store.save(item);
1508
- this.store.log(item.key, { ts: new Date().toISOString(), from, to, detail, agent, ...(person ? { person } : {}) });
1615
+ this.store.log(item.key, { ts: new Date().toISOString(), from, to, detail, agent, ...(person ? { person } : {}), ...(before ? { before } : {}), ...opts });
1509
1616
  this.fac.record(item, from, to, detail, agent);
1510
1617
  if (item.branch)
1511
1618
  this.attempt(() => this.ws.commit(item.key, `registro ${from} → ${to}`, { path: join(this.cfg.factoryDir, item.key), branch: item.branch }));
@@ -9,7 +9,7 @@ export const median = (xs) => {
9
9
  const s = [...xs].sort((a, b) => a - b), m = Math.floor(s.length / 2);
10
10
  return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
11
11
  };
12
- export function worqReport(item, events, now = new Date()) {
12
+ export function worqReport(item, events, now = new Date(), sla = {}) {
13
13
  if (!events.length)
14
14
  return undefined;
15
15
  const hoursIn = {};
@@ -27,13 +27,16 @@ export function worqReport(item, events, now = new Date()) {
27
27
  const finalEvent = events.find((e) => isFinal(e.to));
28
28
  const started = events[0].ts;
29
29
  const endMs = finalEvent ? Date.parse(finalEvent.ts) : now.getTime();
30
+ const inState = finalEvent ? undefined : round((now.getTime() - Date.parse(entered.ts)) / HOUR);
31
+ const limit = finalEvent ? undefined : sla[item.state] ?? sla.DEFAULT;
30
32
  return {
31
33
  key: item.key, title: item.title, state: item.state, lane: item.route === "operational" ? "operational" : item.lane,
32
34
  internal: item.origin === "internal" || undefined, started, finished: finalEvent?.ts,
33
35
  leadHours: round((endMs - Date.parse(started)) / HOUR),
34
36
  hoursIn: Object.fromEntries(Object.entries(hoursIn).map(([k, v]) => [k, round(v)])),
35
37
  returns, estimatedHours: typeof item.artifacts.estimated_hours === "number" ? item.artifacts.estimated_hours : undefined,
36
- ...(finalEvent ? {} : { inStateHours: round((now.getTime() - Date.parse(entered.ts)) / HOUR) }),
38
+ ...(inState === undefined ? {} : { inStateHours: inState }),
39
+ ...(limit && inState !== undefined ? { slaHours: limit, overdue: inState > limit } : {}),
37
40
  };
38
41
  }
39
42
  /** The report of the worqs that had activity since `from` (all of them without it). */
@@ -41,7 +44,7 @@ export function buildReport(items, o = {}) {
41
44
  const now = o.now ?? new Date();
42
45
  const worqs = items
43
46
  .filter(({ events }) => !o.from || events.some((e) => Date.parse(e.ts) >= o.from.getTime()))
44
- .map(({ item, events }) => worqReport(item, events, now))
47
+ .map(({ item, events }) => worqReport(item, events, now, o.sla))
45
48
  .filter((w) => !!w)
46
49
  .sort((a, b) => a.started.localeCompare(b.started));
47
50
  const byState = new Map();
@@ -59,7 +62,10 @@ export function buildReport(items, o = {}) {
59
62
  lanes.set(w.lane ?? "—", [...(lanes.get(w.lane ?? "—") ?? []), w.leadHours]);
60
63
  const leadByLane = [...lanes].map(([lane, hs]) => ({ lane, closed: hs.length, medianHours: round(median(hs)) }));
61
64
  const est = closed.filter((w) => w.estimatedHours !== undefined && w.hoursIn.DEVELOPMENT !== undefined);
65
+ const overdue = worqs.filter((w) => w.overdue).map((w) => ({ key: w.key, title: w.title, state: w.state, hours: w.inStateHours, limit: w.slaHours }))
66
+ .sort((a, b) => b.hours / b.limit - a.hours / a.limit);
62
67
  return {
68
+ ...(o.sla && Object.keys(o.sla).length ? { overdue } : {}),
63
69
  from: o.from?.toISOString(), until: now.toISOString(), worqs,
64
70
  totals: {
65
71
  worqs: worqs.length, closed: closed.length, cancelled: worqs.filter((w) => w.state === "CANCELLED").length,
@@ -94,6 +100,11 @@ export function printReport(r) {
94
100
  console.log(`\nBack to development: ${t.returns} time(s)${back.length ? ` in ${back.length} worq(s): ${back.sort((a, b) => b.returns - a.returns).slice(0, 5).map((w) => `${w.key} ×${w.returns}`).join(", ")}` : ""}`);
95
101
  if (r.estimate)
96
102
  console.log(`Estimate vs time in development (${r.estimate.worqs} closed): ${fmt(r.estimate.estimatedHours)} estimated · ${fmt(r.estimate.developmentHours)} in DEVELOPMENT (wall clock, waiting included)`);
103
+ if (r.overdue) {
104
+ console.log(r.overdue.length ? `\n⚠ Past their SLA (workflow.sla_hours), the most overdue first:` : "\nNothing past its SLA (workflow.sla_hours).");
105
+ for (const o of r.overdue)
106
+ console.log(` ${o.key.padEnd(10)} ${o.state.padEnd(16)} ${fmt(o.hours).padStart(8)} of ${fmt(o.limit)} ${o.title ?? ""}`.trimEnd());
107
+ }
97
108
  const stuck = r.worqs.filter((w) => !isFinal(w.state)).map((w) => ({ w, h: w.inStateHours ?? 0 })).sort((a, b) => b.h - a.h).slice(0, 5);
98
109
  if (stuck.length) {
99
110
  console.log("\nOpen the longest in their current state:");
@@ -47,6 +47,7 @@ export class RoutedTracker {
47
47
  transition(key, name) { return this.to(key).transition(key, name); }
48
48
  create(t) { return this.own.create(t); }
49
49
  async finish(key, reason) { await this.to(key).finish?.(key, reason); }
50
+ async reopen(key) { await this.to(key).reopen?.(key); }
50
51
  link(from, to) { return this.real.link ? this.real.link(from, to) : Promise.resolve(); }
51
52
  url(key) { return this.to(key).url(key); }
52
53
  check() { return this.real.check(); }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@telpin-sistemas/orqen",
3
- "version": "0.1.15",
3
+ "version": "0.1.16",
4
4
  "description": "orqen multi-agent orchestration on OpenSpec, from customer request to production.",
5
5
  "type": "module",
6
6
  "bin": {