@telpin-sistemas/orqen 0.1.12 → 0.1.14

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.
@@ -12,6 +12,7 @@ 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";
@@ -63,6 +64,8 @@ export const WORKFLOW_INTERNAL_HELP = `Agent-only commands (the /orqen:* command
63
64
  block <KEY> <reason> Escalate to a person on the ticket
64
65
  search <query> Search tickets (precedents, related work)
65
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
+
66
69
  Older names (still work, with a notice): pending → list requests · qa → review
67
70
 
68
71
  JSON for tools (orqen-studio):
@@ -86,11 +89,45 @@ export function quienSoy(repo) {
86
89
  }
87
90
  }
88
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
+ /** 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). */
101
+ const KNOWN_OPTIONS = new Set(["agent", "all", "analyst", "apply", "changes", "comment", "dir", "dry-run", "force", "issue", "json", "loop", "person", "reason", "report", "since", "step", "title", "verdict"]);
102
+ async function runCommand(cmd, rest, onDryRun) {
103
+ const unknown = rest.filter((a) => /^--[A-Za-z]/.test(a) && !KNOWN_OPTIONS.has(a.slice(2).split("=")[0]));
104
+ if (unknown.length) {
105
+ console.error(`✘ Unknown option${unknown.length > 1 ? "s" : ""}: ${unknown.join(", ")}. Nothing was run. Valid options: ${[...KNOWN_OPTIONS].map((o) => `--${o}`).join(", ")}.`);
106
+ process.exitCode = 1;
107
+ return;
108
+ }
89
109
  const cfg = loadConfig();
90
- const store = new Store(cfg.stateDir);
91
110
  warnLegacy(cfg);
92
111
  const connectors = buildConnectors(cfg.connectors);
93
- const flow = new Process(cfg, connectors, store, new GitWorkspace(cfg), new OpenSpecCli(cfg.openspecCmd, cfg.repoPath));
112
+ const realStore = new Store(cfg.stateDir);
113
+ const workspace = new GitWorkspace(cfg), openspec = new OpenSpecCli(cfg.openspecCmd, cfg.repoPath);
114
+ // --dry-run: the same command on a copy of the state, with the writes recorded instead of done (see workflow/dry-run.ts)
115
+ const dryAt = rest.indexOf("--dry-run");
116
+ if (dryAt >= 0) {
117
+ rest.splice(dryAt, 1);
118
+ if (!DRY_RUN_COMMANDS.includes(cmd)) {
119
+ 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.`);
120
+ process.exitCode = 1;
121
+ return;
122
+ }
123
+ }
124
+ const dry = dryAt >= 0 ? new DryRun(cfg, connectors, workspace, openspec, realStore, rest[0]) : undefined;
125
+ if (dry) {
126
+ onDryRun(dry);
127
+ console.log("DRY RUN: nothing is written to the tickets, Git or this machine.\n");
128
+ }
129
+ const store = dry?.store ?? realStore;
130
+ const flow = dry?.flow ?? new Process(cfg, connectors, store, workspace, openspec);
94
131
  const flag = (n) => { const i = rest.indexOf(`--${n}`); return i >= 0 ? (rest.splice(i, 2)[1] ?? "") : undefined; };
95
132
  const has = (n) => { const i = rest.indexOf(`--${n}`); if (i >= 0)
96
133
  rest.splice(i, 1); return i >= 0; };
@@ -4,6 +4,7 @@
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";
7
8
  import { toPlain } from "./markup.js";
8
9
  import { BOT_MARK, checkFailure } from "./types.js";
9
10
  const API = "https://app.asana.com/api/1.0";
@@ -20,13 +21,11 @@ export class AsanaTracker {
20
21
  async requestPage(method, path, body) {
21
22
  if (!this.s.token)
22
23
  throw new Error("Asana connector without token: set ASANA_TOKEN in orqen/.env");
23
- const r = await fetch(this.api + path, {
24
+ const r = await request("Asana", `${method} ${path}`, this.api + path, {
24
25
  method,
25
26
  headers: { Authorization: `Bearer ${this.s.token}`, Accept: "application/json", "Content-Type": "application/json" },
26
27
  body: body === undefined ? undefined : JSON.stringify({ data: body }),
27
28
  });
28
- if (!r.ok)
29
- throw new Error(`Asana ${method} ${path}: ${r.status} ${await r.text()}`);
30
29
  const t = await r.text();
31
30
  return t ? JSON.parse(t) : { data: {} };
32
31
  }
@@ -36,14 +35,25 @@ export class AsanaTracker {
36
35
  gid = (key) => idOf(this.s.prefix, key);
37
36
  needProject() { if (!this.s.project)
38
37
  throw new Error("Asana connector without project (conectores.*.proyecto: project gid)"); return this.s.project; }
38
+ /** Every task of a listing: Asana pages them (100 at most) and a request past the first page would never be seen. */
39
+ async allPages(path) {
40
+ const out = [];
41
+ let offset;
42
+ do {
43
+ const page = await this.requestPage("GET", offset ? `${path}&offset=${encodeURIComponent(offset)}` : path);
44
+ out.push(...(page.data ?? []));
45
+ offset = page.next_page?.offset;
46
+ } while (offset);
47
+ return out;
48
+ }
39
49
  async pending() {
40
- const tasks = await this.req("GET", `/projects/${this.needProject()}/tasks?completed_since=now&limit=100&opt_fields=tags.name`);
50
+ const tasks = await this.allPages(`/projects/${this.needProject()}/tasks?completed_since=now&limit=100&opt_fields=tags.name`);
41
51
  const tag = this.s.tag.toLowerCase();
42
52
  return tasks.filter((t) => (t.tags ?? []).some((g) => g.name?.toLowerCase() === tag)).map((t) => keyOf(this.s.prefix, t.gid));
43
53
  }
44
54
  /** Text search inside the project (name and notes). */
45
55
  async search(query) {
46
- const tasks = await this.req("GET", `/projects/${this.needProject()}/tasks?limit=100&opt_fields=name,notes`);
56
+ const tasks = await this.allPages(`/projects/${this.needProject()}/tasks?limit=100&opt_fields=name,notes`);
47
57
  const q = query.toLowerCase();
48
58
  return tasks.filter((t) => `${t.name} ${t.notes ?? ""}`.toLowerCase().includes(q)).map((t) => keyOf(this.s.prefix, t.gid));
49
59
  }
@@ -5,6 +5,7 @@
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";
@@ -80,13 +81,12 @@ export class GithubTracker {
80
81
  async req(method, path, body) {
81
82
  if (!this.s.repo && path.includes("{repo}"))
82
83
  throw new Error("GitHub connector without repo (conectores.*.repo: owner/name)");
83
- 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, {
84
86
  method,
85
87
  headers: { Authorization: `Bearer ${this.auth()}`, Accept: "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28", "Content-Type": "application/json" },
86
88
  body: body === undefined ? undefined : JSON.stringify(body),
87
89
  });
88
- if (!r.ok)
89
- throw new Error(`GitHub ${method} ${path.replace("{repo}", this.s.repo)}: ${r.status} ${await r.text()}`);
90
90
  const t = await r.text();
91
91
  return t ? JSON.parse(t) : {};
92
92
  }
@@ -227,9 +227,18 @@ export class GithubTracker {
227
227
  }
228
228
  async create(t) {
229
229
  const i = await this.req("POST", "/repos/{repo}/issues", { title: t.title.slice(0, 250), body: toMarkdown(t.description), labels: [...this.s.labels, ...(t.labels ?? [])] });
230
- if (this.s.project)
231
- await this.addToProject(i.node_id);
232
- return keyOf(this.s.prefix, i.number);
230
+ const key = keyOf(this.s.prefix, i.number);
231
+ if (this.s.project) {
232
+ // the issue exists already: losing its key here would leave it orphaned and the next attempt would create a second one. The
233
+ // project column is set again by the first transition (transition() adds the issue to the project if it is not there).
234
+ try {
235
+ await this.addToProject(i.node_id);
236
+ }
237
+ catch (e) {
238
+ console.error(`[orqen] warning: ${key} was created but could not be added to the GitHub project (${e.message.split("\n")[0]}); it is added at its next move`);
239
+ }
240
+ }
241
+ return key;
233
242
  }
234
243
  /** Without a project: "closed"/"open" close or reopen the issue. With a project: moves it to that option of the field (Status). */
235
244
  async transition(key, name) {
@@ -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,13 +42,11 @@ 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
  }
@@ -55,8 +54,23 @@ export class JiraTracker {
55
54
  labelled(label) { return this.search(`${this.s.project ? `project = "${this.s.project}" AND ` : ""}labels = "${label}" AND statusCategory != Done`); }
56
55
  async search(jql) {
57
56
  const path = this.s.deployment === "cloud" ? "/rest/api/3/search/jql" : "/rest/api/2/search";
58
- const r = await this.req("GET", path, undefined, { jql, fields: "key", maxResults: 100 });
59
- return (r.issues ?? []).map((i) => this.alias(i.key));
57
+ // every page: with more than 100 results the rest would never be seen (a request past the first 100 would wait forever)
58
+ const keys = [];
59
+ const cloud = this.s.deployment === "cloud";
60
+ let token;
61
+ for (let page = 0; page < 100; page++) {
62
+ const r = await this.req("GET", path, undefined, {
63
+ jql, fields: "key", maxResults: 100,
64
+ ...(cloud ? (token ? { nextPageToken: token } : {}) : { startAt: keys.length }),
65
+ });
66
+ const issues = r.issues ?? [];
67
+ keys.push(...issues.map((i) => this.alias(i.key)));
68
+ token = r.nextPageToken;
69
+ const more = cloud ? !!token && r.isLast !== true : issues.length > 0 && keys.length < (r.total ?? 0);
70
+ if (!more)
71
+ break;
72
+ }
73
+ return keys;
60
74
  }
61
75
  async ticket(key) {
62
76
  const r = await this.req("GET", `/rest/api/2/issue/${this.native(key)}`, undefined, {
@@ -8,4 +8,5 @@ orqen already started the complete environment, ran every configured test type (
8
8
  2. Return one entry per item with the same `scenario` text, plus `covered` and `test` (`file::name`). `orqen complete` rejects missing entries.
9
9
  3. If the suite failed, describe the probable cause in `failure_diagnosis` and give the developer actionable `suggestions`. Say whether each failure is in a test of this change or a regression in an unrelated test, and whether it looks flaky.
10
10
  4. Set `coverage_ok: true` only when every scenario is covered.
11
- 5. Leave repository files as they are.
11
+ 5. If `test_coverage.uncovered` lists files, those tests (declared by this change) are not run by any suite in `orqen/environment.yaml`, so the regression above did not execute them. Do not add them yourself (the configuration is not part of a request): add the line to `suggestions` and tell the person which tests and that they have to be added to `tests` in `orqen/environment.yaml`. This is a warning: it does not fail the stage.
12
+ 6. Leave repository files as they are.
@@ -0,0 +1,188 @@
1
+ /**
2
+ * `--dry-run`: runs a command with its real logic (validations included) but writes nothing outside a temporary copy of the
3
+ * state, and reports what it would have done. Reading is real (tickets, PR state, the repository); everything else is recorded
4
+ * instead of executed:
5
+ * - the tickets (comments, labels, moves, new tickets), Git (commit, push), the PR (open, close, review) and OpenSpec (new
6
+ * change, archive) go through guards that only let the reads through, so a method nobody listed is recorded, never executed;
7
+ * - the state and the worq folder are a copy in a temp folder, which is deleted at the end.
8
+ */
9
+ import { copyFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs";
10
+ import { tmpdir } from "node:os";
11
+ import { join, relative } from "node:path";
12
+ import { Process } from "./process.js";
13
+ import { Store } from "./store.js";
14
+ import { branchFor } from "./workspace.js";
15
+ export const DRY_RUN_COMMANDS = ["complete", "pr", "approve", "cancel", "new_worq", "new-worq"];
16
+ const oneLine = (s, n = 110) => {
17
+ const first = s.split("\n").map((l) => l.trim()).find(Boolean) ?? "";
18
+ return first.length > n || s.trim().includes("\n") ? `${first.slice(0, n)}…` : first;
19
+ };
20
+ /** A proxy that lets `reads` and plain properties through, answers `fake` for the rest and records what `describe` says. */
21
+ function guard(real, reads, fake, describe) {
22
+ return new Proxy(real, {
23
+ get(target, prop) {
24
+ if (typeof prop !== "string" || !(prop in target))
25
+ return undefined; // optional methods stay optional
26
+ const v = target[prop];
27
+ if (typeof v !== "function")
28
+ return v;
29
+ if (reads.includes(prop))
30
+ return v.bind(target);
31
+ return (...args) => { describe(prop, args); return fake[prop]?.(...args); };
32
+ },
33
+ });
34
+ }
35
+ export class DryRun {
36
+ cfg;
37
+ plan = [];
38
+ flow;
39
+ store;
40
+ dir = mkdtempSync(join(tmpdir(), "orqen-dry-"));
41
+ state;
42
+ worqs;
43
+ fakeTickets = new Map();
44
+ fakeReviews = [];
45
+ constructor(cfg, connectors, ws, os, realStore, key) {
46
+ this.cfg = cfg;
47
+ this.state = join(this.dir, "state");
48
+ this.worqs = join(this.dir, "worqs");
49
+ mkdirSync(this.state, { recursive: true });
50
+ mkdirSync(this.worqs, { recursive: true });
51
+ // the state (small files per request) and the folder of this request, as they are now
52
+ if (existsSync(cfg.stateDir))
53
+ for (const f of readdirSync(cfg.stateDir)) {
54
+ const p = join(cfg.stateDir, f);
55
+ if (statSync(p).isFile())
56
+ copyFileSync(p, join(this.state, f));
57
+ }
58
+ const k = key && (realStore.get(key) ? key : realStore.all().find((r) => r.issue?.toUpperCase() === key.toUpperCase())?.key);
59
+ if (k && existsSync(join(cfg.factoryDir, k)))
60
+ cpSync(join(cfg.factoryDir, k), join(this.worqs, k), { recursive: true });
61
+ this.store = new Store(this.state);
62
+ // one object playing both roles (a single system for requests and issues) stays one guarded tracker
63
+ const guarded = new Map();
64
+ const wrap = (t, name) => { if (!guarded.has(t))
65
+ guarded.set(t, this.tracker(t, name)); return guarded.get(t); };
66
+ this.flow = new Process({ ...cfg, stateDir: this.state, factoryDir: this.worqs }, { requests: wrap(connectors.requests, "requests"), issues: connectors.issues && wrap(connectors.issues, "issues") }, this.store, this.workspace(ws), this.openspec(os));
67
+ }
68
+ tracker(real, name) {
69
+ const fakeKey = (k) => this.fakeTickets.has(k);
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
+ 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 () => { },
73
+ create: async (t) => { const k = `DRY-${this.fakeTickets.size + 1}`; this.fakeTickets.set(k, t); return k; },
74
+ }, (n, a) => {
75
+ const add = (text) => this.plan.push({ kind: "ticket", text });
76
+ switch (n) {
77
+ case "comment": return add(`comment on ${a[0]} (${name}): "${oneLine(String(a[1]))}"`);
78
+ case "setStateLabel": return add(`state label of ${a[0]} → ${String(a[1]).toLowerCase()} (${name})`);
79
+ case "transition": return add(`move ${a[0]} to "${a[1]}" (${name})`);
80
+ case "addLabel": return add(`add label "${a[1]}" to ${a[0]} (${name})`);
81
+ case "link": return add(`link ${a[0]} with ${a[1]}`);
82
+ case "finish": return add(`close ${a[0]} as ${a[1] === "not_planned" ? "not planned" : "completed"} (${name})`);
83
+ case "create": return add(`create ticket "${a[0].title}" (${name}${a[0].labels?.length ? `, labels ${a[0].labels.join(", ")}` : ""})`);
84
+ default: return add(`${n}(${a.map((x) => JSON.stringify(x)).join(", ").slice(0, 80)}) (${name})`);
85
+ }
86
+ });
87
+ // tickets that would be created do not exist for real: they are answered from what would be written
88
+ return new Proxy(g, {
89
+ get: (t, prop) => {
90
+ if (prop === "ticket")
91
+ return async (k) => (fakeKey(k) ? stub(k) : t.ticket(k));
92
+ if (prop === "comments")
93
+ return async (k) => (fakeKey(k) ? [] : t.comments(k));
94
+ if (prop === "url")
95
+ return (k) => (fakeKey(k) ? `(dry run) ${k}` : t.url(k));
96
+ return t[prop];
97
+ },
98
+ });
99
+ }
100
+ workspace(ws) {
101
+ const git = (text) => this.plan.push({ kind: "git", text });
102
+ const pr = (text) => this.plan.push({ kind: "pr", text });
103
+ const g = guard(ws, ["currentBranch", "remoteBranchExists", "prState", "prChecks", "prReviews", "snapshotOf"], {
104
+ prepareBranch: (k) => branchFor(k), commit: () => true, push: () => { }, openPr: (v) => `https://dry-run.invalid/pr/${v.key}`,
105
+ closePr: () => { },
106
+ // the review that would be posted: the gate reads the PR's reviews right after posting, so it has to find this one there
107
+ reviewPr: (_url, action, body) => {
108
+ this.fakeReviews.push({ id: `dry-${this.fakeReviews.length + 1}`, author: this.cfg.githubReviewers[0] ?? "dry-run", state: action === "approve" ? "APPROVED" : "CHANGES_REQUESTED", commit: "", body });
109
+ },
110
+ runTests: () => ({ ok: true, output: "(dry run)" }), startEnvironment: async () => ({ ok: true, detail: "dry run" }), stopEnvironment: () => { },
111
+ }, (n, a) => {
112
+ switch (n) {
113
+ case "commit": return git(`commit "${oneLine(String(a[1]), 100)}" (if there is something to commit)`);
114
+ case "push": return git(`push ${a[0]}`);
115
+ case "openPr": return pr(`open PR ${a[0].branch} → ${a[0].base}: "${a[0].title}"`);
116
+ case "closePr": return pr(`close ${a[0]} without merging`);
117
+ case "reviewPr": return pr(`${a[1] === "approve" ? "approve" : "request changes on"} ${a[0]} (review on GitHub)`);
118
+ default: return undefined; // prepareBranch, runTests, environment: nothing to report
119
+ }
120
+ });
121
+ // the PR's reviews are the real ones plus the one this run would post, on the PR's current head
122
+ return new Proxy(g, {
123
+ get: (t, prop) => {
124
+ if (prop === "prReviews" && ws.prReviews)
125
+ return (url) => {
126
+ const snap = ws.prReviews(url);
127
+ return { head: snap.head, reviews: [...snap.reviews, ...this.fakeReviews.map((r) => ({ ...r, commit: snap.head }))] };
128
+ };
129
+ return t[prop];
130
+ },
131
+ });
132
+ }
133
+ openspec(os) {
134
+ return guard(os, ["exists", "dir", "validate", "planningComplete", "tasks", "scenarios"], {
135
+ newChange: (id) => id, archive: (id) => ({ archivedAs: `(dry run) ${id}`, totals: {} }),
136
+ }, (n, a) => {
137
+ if (n === "newChange")
138
+ this.plan.push({ kind: "openspec", text: `create change ${a[0]}` });
139
+ if (n === "archive")
140
+ this.plan.push({ kind: "openspec", text: `archive change ${a[0]}` });
141
+ return undefined;
142
+ });
143
+ }
144
+ /** Everything the command did on the copy: moves of the worq and files of its folder, after the ticket, Git and PR actions. */
145
+ report() {
146
+ const out = [];
147
+ for (const f of readdirSync(this.state).filter((n) => n.endsWith(".log.jsonl")).sort()) {
148
+ const key = f.slice(0, -".log.jsonl".length);
149
+ const before = existsSync(join(this.cfg.stateDir, f)) ? readFileSync(join(this.cfg.stateDir, f), "utf8").split("\n").filter(Boolean).length : 0;
150
+ for (const line of readFileSync(join(this.state, f), "utf8").split("\n").filter(Boolean).slice(before)) {
151
+ const e = JSON.parse(line);
152
+ out.push({ kind: "worq", text: e.from === e.to ? `${key}: ${e.detail}` : `${key}: ${e.from} → ${e.to}${e.detail ? ` (${e.detail})` : ""}` });
153
+ }
154
+ }
155
+ for (const file of walk(this.worqs)) {
156
+ const rel = relative(this.worqs, file).replaceAll("\\", "/");
157
+ const real = join(this.cfg.factoryDir, rel);
158
+ const now = readFileSync(file);
159
+ if (!existsSync(real))
160
+ out.push({ kind: "file", text: `${relPath(this.cfg, rel)} (new)` });
161
+ else if (!now.equals(readFileSync(real)))
162
+ out.push({ kind: "file", text: `${relPath(this.cfg, rel)} (updated)` });
163
+ }
164
+ return [...out.filter((p) => p.kind === "worq"), ...this.plan, ...out.filter((p) => p.kind === "file")];
165
+ }
166
+ /** Prints what it would have done and deletes the copy. */
167
+ finish(log = console.log) {
168
+ const plan = this.report();
169
+ log("");
170
+ log(plan.length ? "Dry run: this is what it would do (nothing was done):" : "Dry run: it would change nothing.");
171
+ for (const p of plan)
172
+ log(` ${p.kind.padEnd(8)} ${p.text}`);
173
+ // Windows can hold a folder for a moment (antivirus, indexer): retry, and never fail the command over a temp folder
174
+ try {
175
+ rmSync(this.dir, { recursive: true, force: true, maxRetries: 8, retryDelay: 100 });
176
+ }
177
+ catch { /* the system cleans its temp folder */ }
178
+ }
179
+ }
180
+ const relPath = (cfg, rel) => {
181
+ const base = relative(cfg.repoPath, cfg.factoryDir).replaceAll("\\", "/");
182
+ return `${base.startsWith("..") ? "orqen/worqs" : base}/${rel}`;
183
+ };
184
+ function walk(dir) {
185
+ if (!existsSync(dir))
186
+ return [];
187
+ return readdirSync(dir, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(join(dir, e.name)) : [join(dir, e.name)]));
188
+ }
@@ -19,7 +19,10 @@ export class OpenSpecCli {
19
19
  run(args) {
20
20
  const win = process.platform === "win32"; // with a shell (cmd) arguments containing spaces must be quoted
21
21
  const a = win ? args.map((x) => (/[\s"]/.test(x) ? `"${x.replace(/"/g, '\\"')}"` : x)) : args;
22
- const p = spawnSync(this.cmd, a, { cwd: this.repoPath, encoding: "utf8", shell: win });
22
+ // the same for the program: a path like C:\Program Files\nodejs\openspec.cmd breaks at its first space in cmd
23
+ // (only when it is a path that exists: OPENSPEC_CMD may also be a command with arguments, like `npx openspec`)
24
+ const cmd = win && /\s/.test(this.cmd) && existsSync(this.cmd) ? `"${this.cmd}"` : this.cmd;
25
+ const p = spawnSync(cmd, a, { cwd: this.repoPath, encoding: "utf8", shell: win });
23
26
  if (p.error)
24
27
  throw new Error(`Could not run "${this.cmd}": ${p.error.message}. Is OpenSpec installed? (npm i -g @fission-ai/openspec)`);
25
28
  try {
@@ -16,9 +16,10 @@ import { detectarIdioma } from "../lib/lang.js";
16
16
  import { SCHEMAS } from "./schemas.js";
17
17
  import { LANES, State, GATES, isAgentState, isFinal, isGate, nextStateAfterStage, } from "./states.js";
18
18
  import { Factory } from "./factory.js";
19
- import { canLinkNatively, isBotComment, LEGACY_STATE_LABELS, STATE_LABEL, WORQ_LABEL } from "../connectors/index.js";
19
+ import { canLinkNatively, isBotComment, isTransient, LEGACY_STATE_LABELS, STATE_LABEL, WORQ_LABEL } from "../connectors/index.js";
20
20
  import { hoursOf } from "./openspec.js";
21
21
  import { reviewSql } from "./sql.js";
22
+ import { testCoverage } from "./test-coverage.js";
22
23
  import { RoutedTracker } from "./routed.js";
23
24
  import { newWorkItem } from "./store.js";
24
25
  import { needsQa, nextSteps, returned, roleOf, workKey } from "./board.js";
@@ -89,10 +90,13 @@ export class Process {
89
90
  if (local)
90
91
  return local;
91
92
  let ticket;
93
+ // a ticket that cannot be read for a moment is not a new request: its state label may say otherwise
92
94
  try {
93
95
  ticket = await this.requests.ticket(key);
94
96
  }
95
- catch {
97
+ catch (e) {
98
+ if (isTransient(e))
99
+ throw e;
96
100
  return newWorkItem(key);
97
101
  }
98
102
  const prefix = [STATE_LABEL, ...LEGACY_STATE_LABELS].find((p) => ticket.labels.some((l) => l.startsWith(p)));
@@ -188,7 +192,12 @@ export class Process {
188
192
  // ================================================================ review
189
193
  async review() {
190
194
  const pending = [];
191
- for (const key of await this.requests.pending()) {
195
+ await this.resync();
196
+ // The queue of the requests system is a filter (a JQL, a tag): a request whose ticket leaves it (someone moves it to another column
197
+ // while it waits for the decision) would wait forever. The ones this machine has waiting on a decision are looked at anyway.
198
+ const queue = await this.requests.pending();
199
+ const waiting = this.store.all().filter((i) => !queue.includes(i.key) && (isGate(i.state) || i.state === "BLOCKED" || i.state === "DELIVERY")).map((i) => i.key);
200
+ for (const key of [...queue, ...waiting]) {
192
201
  try {
193
202
  const item = await this.known(key);
194
203
  if (item.recovered)
@@ -209,6 +218,17 @@ export class Process {
209
218
  }
210
219
  }
211
220
  catch (e) {
221
+ // a cut, the API's rate limit or a gateway error says nothing about the request: it stays as it is and the next run looks again.
222
+ // Blocking it would also tell the client that human intervention is needed.
223
+ if (isTransient(e)) {
224
+ console.error(`[orqen] warning: ${key} was not reviewed (temporary error, the next run tries again): ${e.message.split("\n")[0]}`);
225
+ continue;
226
+ }
227
+ // not in the queue: it is here only because this machine has it waiting; if its ticket cannot be read it is reported, not blocked
228
+ if (waiting.includes(key)) {
229
+ console.error(`[orqen] warning: ${key} was not reviewed: ${e.message.split("\n")[0]}`);
230
+ continue;
231
+ }
212
232
  await this.block(key, `Error reviewing the request: ${e.message}`, "process");
213
233
  }
214
234
  }
@@ -315,7 +335,7 @@ export class Process {
315
335
  if (!this.ws.reviewPr)
316
336
  throw new Error("This workspace cannot review PRs; use CODE_REVIEW_GATE=ticket.");
317
337
  this.ws.reviewPr(url, action === "approve" ? "approve" : "request-changes", body.trim() || `Approved by ${person} with orqen.`);
318
- await this.reviewCodeOnPr(item);
338
+ await this.reviewCodeOnPr(item, force);
319
339
  const after = this.item(key);
320
340
  if (after.state === "CODE_REVIEW")
321
341
  throw new Error(`The review was posted on ${url} but did not count${this.cfg.githubReviewers.length ? ` (GITHUB_REVIEWERS: ${this.cfg.githubReviewers.join(", ")})` : ""}. Check it on GitHub.`);
@@ -333,13 +353,27 @@ export class Process {
333
353
  }
334
354
  return { state: item.state, url, onGitHub: false, warning };
335
355
  }
356
+ /**
357
+ * Where `support` and `analyze` start from: this machine's record; for a request it has no record of, a new one, unless its ticket's
358
+ * label says it already went on (it is being worked on from another machine): starting from NEW would restart the work, and the
359
+ * first comment and label would overwrite what the other machine did.
360
+ */
361
+ async startable(key) {
362
+ const local = this.item(key);
363
+ if (local)
364
+ return local;
365
+ const known = await this.known(key);
366
+ if (known.recovered)
367
+ throw new Error(`${key} is already in ${known.state} according to its ticket's label, and this machine has no record of it: starting it here would restart the work. ${this.recoveredHint(key).text}`);
368
+ return known;
369
+ }
336
370
  // ================================================================ support
337
371
  /**
338
372
  * Opens (or resumes) the first-line handling of a request (available even with SUPPORT_STAGE=off: that variable only decides whether new requests are routed here). The support person drives it; the agent helps them
339
373
  * find an answer. The stage ends resolved (the client confirms in ACCEPTANCE) or escalated to the analyst.
340
374
  */
341
375
  async support(key, agent = "agent", person = agent) {
342
- const item = this.item(key) ?? newWorkItem(key);
376
+ const item = await this.startable(key);
343
377
  if (item.state !== "NEW" && item.state !== "SUPPORT")
344
378
  throw new Error(`${key} is not waiting for support (state: ${item.state}).${item.state === "ANALYSIS" ? " It was escalated to the analyst: use `orqen analyze`." : ""}`);
345
379
  this.assertClaimable(item, agent);
@@ -355,7 +389,7 @@ export class Process {
355
389
  // ================================================================ analyze
356
390
  /** Opens (or resumes) the analysis of a request. An analyst drives it; the agent does the grilling with them. */
357
391
  async analyze(key, agent = "agent", analyst = agent) {
358
- const item = this.item(key) ?? newWorkItem(key);
392
+ const item = await this.startable(key);
359
393
  if (item.state === "WAITING_CLIENT")
360
394
  throw new Error(`${key} is waiting for client answers on the ticket. When they reply it goes back to ANALYSIS (\`orqen list requests\`).`);
361
395
  if (item.state !== "NEW" && item.state !== "SUPPORT" && item.state !== "ANALYSIS")
@@ -399,6 +433,25 @@ export class Process {
399
433
  }
400
434
  // ================================================================ take
401
435
  async take(key, agent = "agent", fromAnalyze = false) {
436
+ const before = this.item(key)?.lock;
437
+ try {
438
+ return await this.takeWork(key, agent, fromAnalyze);
439
+ }
440
+ catch (e) {
441
+ // a failure after the lock was set (switching branches, reading the ticket...) must not leave the request held by an agent
442
+ // that never started: nobody else could take it until the lock expires
443
+ const item = this.item(key);
444
+ if (item?.lock && item.lock.agent === agent && JSON.stringify(item.lock) !== JSON.stringify(before)) {
445
+ if (before)
446
+ item.lock = before;
447
+ else
448
+ delete item.lock;
449
+ this.store.save(item);
450
+ }
451
+ throw e;
452
+ }
453
+ }
454
+ async takeWork(key, agent, fromAnalyze) {
402
455
  const item = this.item(key);
403
456
  if (!item)
404
457
  throw new Error(`${key} has no work for an agent (state: unknown). Run \`orqen list requests\`. ${this.fetchHint(key)}`);
@@ -435,6 +488,13 @@ export class Process {
435
488
  finally {
436
489
  this.ws.stopEnvironment?.();
437
490
  }
491
+ const cov = this.untestedFiles(item);
492
+ if (cov.length) {
493
+ item.artifacts.test_coverage = { uncovered: cov };
494
+ console.error(`[orqen] warning: ${cov.join(", ")} ${cov.length === 1 ? "is" : "are"} not run by any suite in orqen/environment.yaml (tests): TESTING did not run ${cov.length === 1 ? "it" : "them"}.`);
495
+ }
496
+ else
497
+ delete item.artifacts.test_coverage;
438
498
  }
439
499
  if (state === "DELIVERY" && item.change && !item.artifacts.archive) {
440
500
  item.artifacts.archive = this.os.archive(item.change);
@@ -476,11 +536,25 @@ export class Process {
476
536
  ...(["DEVELOPMENT", "TESTING"].includes(state) ? { tasks: this.tasksOf(item) } : {}),
477
537
  ...(state === "TESTING" ? { scenarios: this.scenariosOf(item) } : {}),
478
538
  test_result: state === "TESTING" ? item.artifacts.test_result : undefined,
539
+ // tests this request declares that no configured suite runs (TESTING did not run them): tell the person, do not edit the configuration
540
+ test_coverage: state === "TESTING" ? item.artifacts.test_coverage : undefined,
479
541
  previous_stages: Object.fromEntries(Object.entries(item.artifacts).filter(([k]) => SCHEMAS[k])),
480
542
  human_feedback: item.feedback,
481
543
  },
482
544
  };
483
545
  }
546
+ /**
547
+ * Test files this request declares (the tests added in DEVELOPMENT, the test of each scenario) that no suite of
548
+ * orqen/environment.yaml (`tests`, or TEST_COMMAND without it) runs. Empty when it cannot be known, see test-coverage.ts.
549
+ */
550
+ untestedFiles(item) {
551
+ const refs = [
552
+ ...(item.artifacts.DEVELOPMENT?.added_tests ?? []),
553
+ ...((item.artifacts.TESTING?.scenarios ?? []).map((s) => s.test ?? "")),
554
+ ];
555
+ const configured = Object.values(this.cfg.environment?.tests ?? {}).filter((c) => !!c);
556
+ return testCoverage(refs, configured.length ? configured : [this.cfg.testCommand]).uncovered;
557
+ }
484
558
  // ================================================================ pr
485
559
  /** Where the request branch would go and whether it can be sent now (used by `orqen pr <KEY>` before writing the explanation). */
486
560
  prInfo(key) {
@@ -530,6 +604,10 @@ export class Process {
530
604
  throw new Error(`The PR was not opened. Output: ${out || "(none)"}`);
531
605
  item.artifacts.devel_pr = url;
532
606
  this.store.save(item);
607
+ // the snapshot on the branch is what another machine recovers the worq from: without this it would not know the PR exists
608
+ this.fac.record(item, item.state, item.state, `PR to ${info.base}: ${url}`, agent);
609
+ this.attempt(() => this.ws.commit(key, `PR url ${url}`, { path: join(this.cfg.factoryDir, key), branch: item.branch }));
610
+ this.attempt(() => this.ws.push(item.branch));
533
611
  await this.commentBoth(item, `PR to *${info.base}* opened from branch \`${item.branch}\`: ${url}`);
534
612
  this.store.log(key, { ts: new Date().toISOString(), from: item.state, to: item.state, detail: `PR to ${info.base}: ${url}`, agent });
535
613
  return { url, created: true, base: info.base };
@@ -640,6 +718,18 @@ export class Process {
640
718
  const errors = this.validateAgainstOpenSpec(item, state, s);
641
719
  if (errors.length)
642
720
  return { ok: false, errors };
721
+ // the development is committed on the active branch: it has to be the request's (`orqen pr` checks the same)
722
+ if (state === "DEVELOPMENT" && s.completed && item.branch) {
723
+ let current;
724
+ try {
725
+ current = this.ws.currentBranch();
726
+ }
727
+ catch {
728
+ current = undefined;
729
+ }
730
+ if (current !== undefined && current !== item.branch)
731
+ return { ok: false, errors: [`The repo is on "${current}", not on the request branch "${item.branch}": the commit of this development would go to the wrong branch. Switch to it (git checkout ${item.branch}) and complete again.`] };
732
+ }
643
733
  // --- counters and decision
644
734
  if (state === "ANALYSIS") {
645
735
  item.route = s.route;
@@ -802,6 +892,10 @@ export class Process {
802
892
  return this.commentBoth(item, `Development could not be completed: ${s.blocker}`);
803
893
  case "TESTING": {
804
894
  const rt = item.artifacts.test_result;
895
+ const untested = this.untestedFiles(item);
896
+ const warning = untested.length
897
+ ? `\n\n⚠ Not run by any suite in orqen/environment.yaml, so TESTING did not run ${untested.length === 1 ? "it" : "them"}:\n${bullets(untested)}\nAdd ${untested.length === 1 ? "it" : "them"} to \`tests\` there so the regression includes ${untested.length === 1 ? "it" : "them"}.`
898
+ : "";
805
899
  const table = s.scenarios.map((e) => `- ${e.covered ? "✔" : "✘"} ${e.requirement} › ${e.scenario}${e.test ? ` (${e.test})` : ""}`).join("\n");
806
900
  if (s.approved) {
807
901
  // testing does not open the PR: the senior reviews the PR to the devel branch (`orqen pr`)
@@ -811,9 +905,9 @@ export class Process {
811
905
  : this.cfg.codeReviewGate === "github"
812
906
  ? "Code review: approve or request changes on the PR in GitHub."
813
907
  : "Code review: comment */approve* or */reject <reason>*.";
814
- return this.commentBoth(item, `Tests passed and all scenarios are covered:\n${table}\n\n${pr}\n${decide}`);
908
+ return this.commentBoth(item, `Tests passed and all scenarios are covered:\n${table}${warning}\n\n${pr}\n${decide}`);
815
909
  }
816
- return this.commentBoth(item, `Testing failed (attempt ${item.testingAttempts}). Suite: ${rt?.ok ? "OK" : "FAILED"}\n${table}\n\nDiagnosis: ${s.failure_diagnosis}` +
910
+ return this.commentBoth(item, `Testing failed (attempt ${item.testingAttempts}). Suite: ${rt?.ok ? "OK" : "FAILED"}\n${table}${warning}\n\nDiagnosis: ${s.failure_diagnosis}` +
817
911
  (next === "BLOCKED" ? "\nRetries are exhausted. Human review is needed." : "\nReturning to development."));
818
912
  }
819
913
  case "EXECUTION": {
@@ -867,7 +961,7 @@ export class Process {
867
961
  * "dismiss stale approvals"), each review is handled once, and with GITHUB_REVIEWERS set only those GitHub logins count.
868
962
  * Changes requested win over approvals. If GitHub cannot be read, the request keeps waiting (it is not blocked).
869
963
  */
870
- async reviewCodeOnPr(item) {
964
+ async reviewCodeOnPr(item, force = false) {
871
965
  const url = item.artifacts.devel_pr;
872
966
  if (!url)
873
967
  return this.store.save(item); // no PR yet: nothing to decide on (`/orqen:pr` opens it)
@@ -887,17 +981,31 @@ export class Process {
887
981
  const authorized = this.cfg.githubReviewers;
888
982
  const latest = new Map(); // last decisive review per author, on the current head
889
983
  for (const r of snap.reviews) {
890
- if (!["APPROVED", "CHANGES_REQUESTED"].includes(r.state) || r.commit !== snap.head || handled.has(r.id))
984
+ if (!["APPROVED", "CHANGES_REQUESTED"].includes(r.state) || r.commit !== snap.head)
891
985
  continue;
892
986
  if (authorized.length && !authorized.includes(r.author))
893
987
  continue;
894
988
  latest.set(r.author, r);
895
989
  }
896
- const decisive = [...latest.values()];
990
+ // the handled ones go out only after taking each author's last review: an approval that came before a rejection already
991
+ // handled is not their opinion any more, and must not come back as a new decision
992
+ const decisive = [...latest.values()].filter((r) => !handled.has(r.id));
897
993
  const rejected = decisive.filter((r) => r.state === "CHANGES_REQUESTED");
898
994
  const approved = decisive.filter((r) => r.state === "APPROVED");
899
995
  if (!rejected.length && !approved.length)
900
996
  return this.store.save(item);
997
+ // an approval is held, like `orqen approve` does, while the PR is red, still running its CI or has conflicts (it is not marked as
998
+ // handled: the next run looks again). Unknown (no gh...) never holds it.
999
+ if (!rejected.length && !force) {
1000
+ const h = this.prHealth(url);
1001
+ const problem = h.conflicts ? `it has conflicts with ${this.cfg.develBranch}`
1002
+ : h.ci === "failing" ? `its CI is failing${h.detail ? ` (${h.detail})` : ""}`
1003
+ : h.ci === "pending" ? `its CI is still running${h.detail ? ` (${h.detail})` : ""}` : "";
1004
+ if (problem) {
1005
+ console.error(`[orqen] warning: ${item.key}: the PR ${url} is approved on GitHub but ${problem}; it stays in CODE_REVIEW and is looked at again on the next run (orqen approve ${workKey(item)} --force overrides this).`);
1006
+ return this.store.save(item);
1007
+ }
1008
+ }
901
1009
  const used = rejected.length ? rejected : approved;
902
1010
  item.artifacts.handled_reviews = [...handled, ...used.map((r) => r.id)];
903
1011
  if (rejected.length) {
@@ -1086,7 +1194,17 @@ export class Process {
1086
1194
  }
1087
1195
  const item = { ...newWorkItem(key), state: "ANALYSIS", origin: "internal", title: t, analyst: person, lock: { agent: "internal", since: new Date().toISOString() } };
1088
1196
  this.store.save(item);
1089
- const r = await this.complete(key, analysis, "internal");
1197
+ let r;
1198
+ try {
1199
+ r = await this.complete(key, analysis, "internal");
1200
+ }
1201
+ catch (e) {
1202
+ // an error of the connector halfway (the comment, the label...) leaves the same: the issue exists and the worq did not start, so
1203
+ // `--issue` has to be able to take it. Once it moved on it is a worq, and the error is shown as it is.
1204
+ if (this.store.get(key)?.state !== "ANALYSIS")
1205
+ throw e;
1206
+ r = { ok: false, errors: [e.message.split("\n")[0]] };
1207
+ }
1090
1208
  if (!r.ok) {
1091
1209
  this.store.remove(key);
1092
1210
  rmSync(this.fac.dirOf(key), { recursive: true, force: true });
@@ -1252,14 +1370,25 @@ export class Process {
1252
1370
  item.state = to;
1253
1371
  delete item.lock;
1254
1372
  if (isGate(to) || to === "BLOCKED") { // when entering a gate, ignore earlier comments
1373
+ // up to orqen's own last comment (the one that asks for the answer), not up to the last comment there is: a client who answers
1374
+ // between that comment and this read would otherwise have their answer taken as already seen, and the request would wait forever
1255
1375
  const cs = await this.requests.comments(item.key);
1256
- item.lastSeenComment = cs.at(-1)?.id ?? "";
1376
+ const ours = [...cs].reverse().find((c) => isBotComment(c.body));
1377
+ item.lastSeenComment = (ours ?? cs.at(-1))?.id ?? "";
1257
1378
  }
1258
1379
  this.store.save(item);
1259
1380
  this.store.log(item.key, { ts: new Date().toISOString(), from, to, detail, agent });
1260
1381
  this.fac.record(item, from, to, detail, agent);
1261
1382
  if (item.branch)
1262
1383
  this.attempt(() => this.ws.commit(item.key, `registro ${from} → ${to}`, { path: join(this.cfg.factoryDir, item.key), branch: item.branch }));
1384
+ await this.syncRemote(item, to);
1385
+ }
1386
+ /**
1387
+ * The state on the tickets: the label, the column or transition and, for a finished request, closing them. Everything here is
1388
+ * idempotent. When it fails the local state has already moved, so the worq is marked (`sync_pending`) and every run of
1389
+ * `orqen list` tries again until the tickets say the same as orqen (a cancelled request must not stay open there).
1390
+ */
1391
+ async syncRemote(item, to) {
1263
1392
  try {
1264
1393
  await this.requests.setStateLabel(item.key, to);
1265
1394
  // CANCELLED falls back to the CLOSED destination when the connector has no own "CANCELLED" transition
@@ -1279,9 +1408,30 @@ export class Process {
1279
1408
  if (item.issue)
1280
1409
  await this.issues?.finish?.(item.issue, reason);
1281
1410
  }
1411
+ if (item.artifacts.sync_pending) {
1412
+ delete item.artifacts.sync_pending;
1413
+ this.store.save(item);
1414
+ }
1415
+ return true;
1282
1416
  }
1283
1417
  catch (e) {
1284
- console.error(`[orqen] could not update the state on ${this.requests.label}: ${e.message}`);
1418
+ console.error(`[orqen] could not update the state on ${this.requests.label}: ${e.message}${isFinal(to) ? " (orqen tries again on the next `orqen list`)" : ""}`);
1419
+ if (item.artifacts.sync_pending !== to) {
1420
+ item.artifacts.sync_pending = to;
1421
+ this.store.save(item);
1422
+ }
1423
+ return false;
1424
+ }
1425
+ }
1426
+ /** Finishes what a failed update of the tickets left behind (see syncRemote). Runs at the start of every review. */
1427
+ async resync() {
1428
+ for (const item of this.store.all()) {
1429
+ if (item.artifacts.sync_pending === item.state)
1430
+ await this.syncRemote(item, item.state);
1431
+ else if (item.artifacts.sync_pending) {
1432
+ delete item.artifacts.sync_pending;
1433
+ this.store.save(item);
1434
+ } // it moved on since: the later move wrote the tickets
1285
1435
  }
1286
1436
  }
1287
1437
  }
@@ -12,8 +12,26 @@ export class Store {
12
12
  mkdirSync(dir, { recursive: true });
13
13
  }
14
14
  path = (key) => join(this.dir, `${key}.json`);
15
+ /**
16
+ * The saved record, or nothing when there is none. A file that is not valid JSON (a crash while writing it, an editor, a bad
17
+ * merge) is set aside as <KEY>.json.corrupt and treated as missing, so orqen recovers the request from its snapshot or its
18
+ * ticket instead of failing every command that lists requests.
19
+ */
15
20
  get(key) {
16
- return existsSync(this.path(key)) ? migrate(JSON.parse(readFileSync(this.path(key), "utf8"))) : undefined;
21
+ const file = this.path(key);
22
+ if (!existsSync(file))
23
+ return undefined;
24
+ try {
25
+ return migrate(JSON.parse(readFileSync(file, "utf8")));
26
+ }
27
+ catch (e) {
28
+ console.error(`[orqen] warning: the record of ${key} is not valid JSON (${e.message.split("\n")[0]}): kept as ${key}.json.corrupt and recovered from its snapshot or its ticket if possible`);
29
+ try {
30
+ renameSync(file, file + ".corrupt");
31
+ }
32
+ catch { /* read-only folder: it is ignored anyway */ }
33
+ return undefined;
34
+ }
17
35
  }
18
36
  save(rec) {
19
37
  const tmp = this.path(rec.key) + ".tmp";
@@ -26,7 +44,15 @@ export class Store {
26
44
  log(key, ev) { appendFileSync(join(this.dir, `${key}.log.jsonl`), JSON.stringify(ev) + "\n"); }
27
45
  events(key) {
28
46
  const f = join(this.dir, `${key}.log.jsonl`);
29
- return existsSync(f) ? readFileSync(f, "utf8").trim().split("\n").filter(Boolean).map((l) => JSON.parse(l)) : [];
47
+ if (!existsSync(f))
48
+ return [];
49
+ // a line cut by a crash must not hide the rest of the history
50
+ return readFileSync(f, "utf8").trim().split("\n").filter(Boolean).flatMap((l) => { try {
51
+ return [JSON.parse(l)];
52
+ }
53
+ catch {
54
+ return [];
55
+ } });
30
56
  }
31
57
  all() {
32
58
  // only request records: other tools (the desktop app) may keep their own files in this folder
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Tests that a request adds but no suite of orqen/environment.yaml runs. TESTING runs only the configured suites, so a test
3
+ * written in DEVELOPMENT that none of them reaches passes the regression without ever being executed.
4
+ *
5
+ * It only says so when it is sure. A suite like `npm test` or `pytest` runs whatever the project decides, so it cannot be known
6
+ * from the command: if any suite is like that, nothing is reported. A suite names its files only when its command has paths or globs
7
+ * (`node --test scripts/a.test.cjs`, `vitest run test/**`, `pytest tests/`).
8
+ */
9
+ /** The file of a reference to a test: `a/b.test.ts::name`, `a/b.test.ts (name)`, `./a\b.test.ts`. Undefined for free text. */
10
+ export function testFile(ref) {
11
+ const head = ref.split(/::|\s›\s|\s\(|#/)[0].trim().replace(/\\/g, "/").replace(/^\.\//, "");
12
+ return /^[\w@.\-/]+\.\w+$/.test(head) ? head : undefined;
13
+ }
14
+ const SPLIT_COMMANDS = /\s*(?:&&|\|\||;)\s*/;
15
+ // flags whose value is a helper (setup file, config, reporter), not a test to run
16
+ const FLAGS_WITH_VALUE = new Set(["--import", "--require", "-r", "--loader", "--config", "-c", "--env-file", "--reporter", "--setupFiles", "--tsconfig", "--project"]);
17
+ const FILE_EXT = /\.(?:[cm]?[jt]sx?|py|go|rb|php|java|cs|rs|kt|exs?|dart)$/;
18
+ function words(s) {
19
+ return (s.match(/"[^"]*"|'[^']*'|\S+/g) ?? []).map((w) => w.replace(/^["']|["']$/g, ""));
20
+ }
21
+ /** Paths and globs a suite command names (relative to the repository), or [] when it names none. */
22
+ export function suiteTargets(command) {
23
+ const out = [];
24
+ let dir = "";
25
+ for (const part of command.split(SPLIT_COMMANDS)) {
26
+ const w = words(part);
27
+ if (w[0] === "cd" && w[1]) {
28
+ dir = w[1].replace(/\\/g, "/").replace(/^\.\//, "").replace(/\/$/, "");
29
+ continue;
30
+ }
31
+ w.forEach((t, i) => {
32
+ if (t.startsWith("-") || i === 0 || (i > 0 && FLAGS_WITH_VALUE.has(w[i - 1])))
33
+ return;
34
+ const p = t.replace(/\\/g, "/").replace(/^\.\//, "");
35
+ if (p.includes("/") || p.includes("*") || FILE_EXT.test(p))
36
+ out.push(dir && !p.startsWith("/") ? `${dir}/${p}` : p);
37
+ });
38
+ }
39
+ return out;
40
+ }
41
+ function globToRegExp(glob) {
42
+ let re = "";
43
+ for (let i = 0; i < glob.length; i++) {
44
+ const c = glob[i];
45
+ if (c === "*") {
46
+ if (glob[i + 1] === "*") {
47
+ re += glob[i + 2] === "/" ? "(?:.*/)?" : ".*";
48
+ i += glob[i + 2] === "/" ? 2 : 1;
49
+ }
50
+ else
51
+ re += "[^/]*";
52
+ }
53
+ else if (c === "?")
54
+ re += "[^/]";
55
+ else if (c === "{") {
56
+ const end = glob.indexOf("}", i);
57
+ if (end < 0)
58
+ re += "\\{";
59
+ else {
60
+ re += `(?:${glob.slice(i + 1, end).split(",").map(escape).join("|")})`;
61
+ i = end;
62
+ }
63
+ }
64
+ else
65
+ re += escape(c);
66
+ }
67
+ return new RegExp(`^${re}$`);
68
+ }
69
+ const escape = (s) => s.replace(/[.+^$()|[\]\\]/g, "\\$&");
70
+ /** Whether a suite target (file, glob or folder) reaches the file. */
71
+ export function reaches(target, file) {
72
+ if (target === file)
73
+ return true;
74
+ if (/[*?{]/.test(target))
75
+ return globToRegExp(target).test(file);
76
+ return file.startsWith(target.replace(/\/$/, "") + "/");
77
+ }
78
+ /** `refs`: the tests the request declares (`added_tests` of DEVELOPMENT, the `test` of each scenario); `commands`: the configured suites. */
79
+ export function testCoverage(refs, commands) {
80
+ const files = [...new Set(refs.map(testFile).filter((f) => !!f))];
81
+ const suites = commands.map((c) => c.trim()).filter(Boolean).map(suiteTargets);
82
+ const known = suites.length > 0 && suites.every((t) => t.length > 0);
83
+ if (!known)
84
+ return { files, uncovered: [], known: false };
85
+ return { files, uncovered: files.filter((f) => !suites.some((targets) => targets.some((t) => reaches(t, f)))), known: true };
86
+ }
@@ -66,6 +66,10 @@ export class GitWorkspace {
66
66
  catch { /* no remote */ }
67
67
  if (this.git("branch", "--list", branch))
68
68
  this.git("checkout", branch);
69
+ else if (this.git("branch", "-r", "--list", `origin/${branch}`)) {
70
+ // someone started this request on another machine (or this clone is new): continue from their branch, not from the base
71
+ this.git("checkout", "-b", branch, "--track", `origin/${branch}`);
72
+ }
69
73
  else if (this.linkedWorktree()) {
70
74
  // the base branch is usually checked out in the main worktree, where git does not let us check it out again
71
75
  const base = this.git("branch", "-r", "--list", `origin/${this.cfg.baseBranch}`) ? `origin/${this.cfg.baseBranch}` : this.cfg.baseBranch;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@telpin-sistemas/orqen",
3
- "version": "0.1.12",
3
+ "version": "0.1.14",
4
4
  "description": "orqen multi-agent orchestration on OpenSpec, from customer request to production.",
5
5
  "type": "module",
6
6
  "bin": {