@telpin-sistemas/orqen 0.1.12 → 0.1.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/commands/workflow.js +31 -2
- package/dist/connectors/asana.js +2 -3
- package/dist/connectors/github.js +3 -3
- package/dist/connectors/http.js +92 -0
- package/dist/connectors/index.js +1 -0
- package/dist/connectors/jira.js +2 -3
- package/dist/template/stages/testing.md +2 -1
- package/dist/workflow/dry-run.js +171 -0
- package/dist/workflow/process.js +39 -4
- package/dist/workflow/test-coverage.js +86 -0
- package/package.json +1 -1
|
@@ -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,37 @@ 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
|
+
async function runCommand(cmd, rest, onDryRun) {
|
|
89
101
|
const cfg = loadConfig();
|
|
90
|
-
const store = new Store(cfg.stateDir);
|
|
91
102
|
warnLegacy(cfg);
|
|
92
103
|
const connectors = buildConnectors(cfg.connectors);
|
|
93
|
-
const
|
|
104
|
+
const realStore = new Store(cfg.stateDir);
|
|
105
|
+
const workspace = new GitWorkspace(cfg), openspec = new OpenSpecCli(cfg.openspecCmd, cfg.repoPath);
|
|
106
|
+
// --dry-run: the same command on a copy of the state, with the writes recorded instead of done (see workflow/dry-run.ts)
|
|
107
|
+
const dryAt = rest.indexOf("--dry-run");
|
|
108
|
+
if (dryAt >= 0) {
|
|
109
|
+
rest.splice(dryAt, 1);
|
|
110
|
+
if (!DRY_RUN_COMMANDS.includes(cmd)) {
|
|
111
|
+
console.error(`✘ --dry-run works with: ${DRY_RUN_COMMANDS.filter((c) => c !== "new-worq").join(", ")}. orqen ${cmd} would have run for real, so it was not run.`);
|
|
112
|
+
process.exitCode = 1;
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
const dry = dryAt >= 0 ? new DryRun(cfg, connectors, workspace, openspec, realStore, rest[0]) : undefined;
|
|
117
|
+
if (dry) {
|
|
118
|
+
onDryRun(dry);
|
|
119
|
+
console.log("DRY RUN: nothing is written to the tickets, Git or this machine.\n");
|
|
120
|
+
}
|
|
121
|
+
const store = dry?.store ?? realStore;
|
|
122
|
+
const flow = dry?.flow ?? new Process(cfg, connectors, store, workspace, openspec);
|
|
94
123
|
const flag = (n) => { const i = rest.indexOf(`--${n}`); return i >= 0 ? (rest.splice(i, 2)[1] ?? "") : undefined; };
|
|
95
124
|
const has = (n) => { const i = rest.indexOf(`--${n}`); if (i >= 0)
|
|
96
125
|
rest.splice(i, 1); return i >= 0; };
|
package/dist/connectors/asana.js
CHANGED
|
@@ -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
|
|
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
|
}
|
|
@@ -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
|
|
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
|
}
|
|
@@ -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
|
+
}
|
package/dist/connectors/index.js
CHANGED
|
@@ -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);
|
package/dist/connectors/jira.js
CHANGED
|
@@ -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
|
|
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
|
}
|
|
@@ -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.
|
|
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,171 @@
|
|
|
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
|
+
constructor(cfg, connectors, ws, os, realStore, key) {
|
|
45
|
+
this.cfg = cfg;
|
|
46
|
+
this.state = join(this.dir, "state");
|
|
47
|
+
this.worqs = join(this.dir, "worqs");
|
|
48
|
+
mkdirSync(this.state, { recursive: true });
|
|
49
|
+
mkdirSync(this.worqs, { recursive: true });
|
|
50
|
+
// the state (small files per request) and the folder of this request, as they are now
|
|
51
|
+
if (existsSync(cfg.stateDir))
|
|
52
|
+
for (const f of readdirSync(cfg.stateDir)) {
|
|
53
|
+
const p = join(cfg.stateDir, f);
|
|
54
|
+
if (statSync(p).isFile())
|
|
55
|
+
copyFileSync(p, join(this.state, f));
|
|
56
|
+
}
|
|
57
|
+
const k = key && (realStore.get(key) ? key : realStore.all().find((r) => r.issue?.toUpperCase() === key.toUpperCase())?.key);
|
|
58
|
+
if (k && existsSync(join(cfg.factoryDir, k)))
|
|
59
|
+
cpSync(join(cfg.factoryDir, k), join(this.worqs, k), { recursive: true });
|
|
60
|
+
this.store = new Store(this.state);
|
|
61
|
+
// one object playing both roles (a single system for requests and issues) stays one guarded tracker
|
|
62
|
+
const guarded = new Map();
|
|
63
|
+
const wrap = (t, name) => { if (!guarded.has(t))
|
|
64
|
+
guarded.set(t, this.tracker(t, name)); return guarded.get(t); };
|
|
65
|
+
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));
|
|
66
|
+
}
|
|
67
|
+
tracker(real, name) {
|
|
68
|
+
const fakeKey = (k) => this.fakeTickets.has(k);
|
|
69
|
+
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}` }; };
|
|
70
|
+
const g = guard(real, ["pending", "search", "labelled", "check", "ticket", "comments", "url", "statuses", "projects", "repositories"], {
|
|
71
|
+
comment: async () => { }, setStateLabel: async () => { }, transition: async () => true, addLabel: async () => { }, link: async () => { }, finish: async () => { },
|
|
72
|
+
create: async (t) => { const k = `DRY-${this.fakeTickets.size + 1}`; this.fakeTickets.set(k, t); return k; },
|
|
73
|
+
}, (n, a) => {
|
|
74
|
+
const add = (text) => this.plan.push({ kind: "ticket", text });
|
|
75
|
+
switch (n) {
|
|
76
|
+
case "comment": return add(`comment on ${a[0]} (${name}): "${oneLine(String(a[1]))}"`);
|
|
77
|
+
case "setStateLabel": return add(`state label of ${a[0]} → ${String(a[1]).toLowerCase()} (${name})`);
|
|
78
|
+
case "transition": return add(`move ${a[0]} to "${a[1]}" (${name})`);
|
|
79
|
+
case "addLabel": return add(`add label "${a[1]}" to ${a[0]} (${name})`);
|
|
80
|
+
case "link": return add(`link ${a[0]} with ${a[1]}`);
|
|
81
|
+
case "finish": return add(`close ${a[0]} as ${a[1] === "not_planned" ? "not planned" : "completed"} (${name})`);
|
|
82
|
+
case "create": return add(`create ticket "${a[0].title}" (${name}${a[0].labels?.length ? `, labels ${a[0].labels.join(", ")}` : ""})`);
|
|
83
|
+
default: return add(`${n}(${a.map((x) => JSON.stringify(x)).join(", ").slice(0, 80)}) (${name})`);
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
// tickets that would be created do not exist for real: they are answered from what would be written
|
|
87
|
+
return new Proxy(g, {
|
|
88
|
+
get: (t, prop) => {
|
|
89
|
+
if (prop === "ticket")
|
|
90
|
+
return async (k) => (fakeKey(k) ? stub(k) : t.ticket(k));
|
|
91
|
+
if (prop === "comments")
|
|
92
|
+
return async (k) => (fakeKey(k) ? [] : t.comments(k));
|
|
93
|
+
if (prop === "url")
|
|
94
|
+
return (k) => (fakeKey(k) ? `(dry run) ${k}` : t.url(k));
|
|
95
|
+
return t[prop];
|
|
96
|
+
},
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
workspace(ws) {
|
|
100
|
+
const git = (text) => this.plan.push({ kind: "git", text });
|
|
101
|
+
const pr = (text) => this.plan.push({ kind: "pr", text });
|
|
102
|
+
return guard(ws, ["currentBranch", "remoteBranchExists", "prState", "prChecks", "prReviews", "snapshotOf"], {
|
|
103
|
+
prepareBranch: (k) => branchFor(k), commit: () => true, push: () => { }, openPr: (v) => `https://dry-run.invalid/pr/${v.key}`,
|
|
104
|
+
closePr: () => { }, reviewPr: () => { }, runTests: () => ({ ok: true, output: "(dry run)" }), startEnvironment: async () => ({ ok: true, detail: "dry run" }), stopEnvironment: () => { },
|
|
105
|
+
}, (n, a) => {
|
|
106
|
+
switch (n) {
|
|
107
|
+
case "commit": return git(`commit "${oneLine(String(a[1]), 100)}" (if there is something to commit)`);
|
|
108
|
+
case "push": return git(`push ${a[0]}`);
|
|
109
|
+
case "openPr": return pr(`open PR ${a[0].branch} → ${a[0].base}: "${a[0].title}"`);
|
|
110
|
+
case "closePr": return pr(`close ${a[0]} without merging`);
|
|
111
|
+
case "reviewPr": return pr(`${a[1] === "approve" ? "approve" : "request changes on"} ${a[0]} (review on GitHub)`);
|
|
112
|
+
default: return undefined; // prepareBranch, runTests, environment: nothing to report
|
|
113
|
+
}
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
openspec(os) {
|
|
117
|
+
return guard(os, ["exists", "dir", "validate", "planningComplete", "tasks", "scenarios"], {
|
|
118
|
+
newChange: (id) => id, archive: (id) => ({ archivedAs: `(dry run) ${id}`, totals: {} }),
|
|
119
|
+
}, (n, a) => {
|
|
120
|
+
if (n === "newChange")
|
|
121
|
+
this.plan.push({ kind: "openspec", text: `create change ${a[0]}` });
|
|
122
|
+
if (n === "archive")
|
|
123
|
+
this.plan.push({ kind: "openspec", text: `archive change ${a[0]}` });
|
|
124
|
+
return undefined;
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
/** Everything the command did on the copy: moves of the worq and files of its folder, after the ticket, Git and PR actions. */
|
|
128
|
+
report() {
|
|
129
|
+
const out = [];
|
|
130
|
+
for (const f of readdirSync(this.state).filter((n) => n.endsWith(".log.jsonl")).sort()) {
|
|
131
|
+
const key = f.slice(0, -".log.jsonl".length);
|
|
132
|
+
const before = existsSync(join(this.cfg.stateDir, f)) ? readFileSync(join(this.cfg.stateDir, f), "utf8").split("\n").filter(Boolean).length : 0;
|
|
133
|
+
for (const line of readFileSync(join(this.state, f), "utf8").split("\n").filter(Boolean).slice(before)) {
|
|
134
|
+
const e = JSON.parse(line);
|
|
135
|
+
out.push({ kind: "worq", text: e.from === e.to ? `${key}: ${e.detail}` : `${key}: ${e.from} → ${e.to}${e.detail ? ` (${e.detail})` : ""}` });
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
for (const file of walk(this.worqs)) {
|
|
139
|
+
const rel = relative(this.worqs, file).replaceAll("\\", "/");
|
|
140
|
+
const real = join(this.cfg.factoryDir, rel);
|
|
141
|
+
const now = readFileSync(file);
|
|
142
|
+
if (!existsSync(real))
|
|
143
|
+
out.push({ kind: "file", text: `${relPath(this.cfg, rel)} (new)` });
|
|
144
|
+
else if (!now.equals(readFileSync(real)))
|
|
145
|
+
out.push({ kind: "file", text: `${relPath(this.cfg, rel)} (updated)` });
|
|
146
|
+
}
|
|
147
|
+
return [...out.filter((p) => p.kind === "worq"), ...this.plan, ...out.filter((p) => p.kind === "file")];
|
|
148
|
+
}
|
|
149
|
+
/** Prints what it would have done and deletes the copy. */
|
|
150
|
+
finish(log = console.log) {
|
|
151
|
+
const plan = this.report();
|
|
152
|
+
log("");
|
|
153
|
+
log(plan.length ? "Dry run: this is what it would do (nothing was done):" : "Dry run: it would change nothing.");
|
|
154
|
+
for (const p of plan)
|
|
155
|
+
log(` ${p.kind.padEnd(8)} ${p.text}`);
|
|
156
|
+
// Windows can hold a folder for a moment (antivirus, indexer): retry, and never fail the command over a temp folder
|
|
157
|
+
try {
|
|
158
|
+
rmSync(this.dir, { recursive: true, force: true, maxRetries: 8, retryDelay: 100 });
|
|
159
|
+
}
|
|
160
|
+
catch { /* the system cleans its temp folder */ }
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
const relPath = (cfg, rel) => {
|
|
164
|
+
const base = relative(cfg.repoPath, cfg.factoryDir).replaceAll("\\", "/");
|
|
165
|
+
return `${base.startsWith("..") ? "orqen/worqs" : base}/${rel}`;
|
|
166
|
+
};
|
|
167
|
+
function walk(dir) {
|
|
168
|
+
if (!existsSync(dir))
|
|
169
|
+
return [];
|
|
170
|
+
return readdirSync(dir, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(join(dir, e.name)) : [join(dir, e.name)]));
|
|
171
|
+
}
|
package/dist/workflow/process.js
CHANGED
|
@@ -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)));
|
|
@@ -209,6 +213,12 @@ export class Process {
|
|
|
209
213
|
}
|
|
210
214
|
}
|
|
211
215
|
catch (e) {
|
|
216
|
+
// 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.
|
|
217
|
+
// Blocking it would also tell the client that human intervention is needed.
|
|
218
|
+
if (isTransient(e)) {
|
|
219
|
+
console.error(`[orqen] warning: ${key} was not reviewed (temporary error, the next run tries again): ${e.message.split("\n")[0]}`);
|
|
220
|
+
continue;
|
|
221
|
+
}
|
|
212
222
|
await this.block(key, `Error reviewing the request: ${e.message}`, "process");
|
|
213
223
|
}
|
|
214
224
|
}
|
|
@@ -435,6 +445,13 @@ export class Process {
|
|
|
435
445
|
finally {
|
|
436
446
|
this.ws.stopEnvironment?.();
|
|
437
447
|
}
|
|
448
|
+
const cov = this.untestedFiles(item);
|
|
449
|
+
if (cov.length) {
|
|
450
|
+
item.artifacts.test_coverage = { uncovered: cov };
|
|
451
|
+
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"}.`);
|
|
452
|
+
}
|
|
453
|
+
else
|
|
454
|
+
delete item.artifacts.test_coverage;
|
|
438
455
|
}
|
|
439
456
|
if (state === "DELIVERY" && item.change && !item.artifacts.archive) {
|
|
440
457
|
item.artifacts.archive = this.os.archive(item.change);
|
|
@@ -476,11 +493,25 @@ export class Process {
|
|
|
476
493
|
...(["DEVELOPMENT", "TESTING"].includes(state) ? { tasks: this.tasksOf(item) } : {}),
|
|
477
494
|
...(state === "TESTING" ? { scenarios: this.scenariosOf(item) } : {}),
|
|
478
495
|
test_result: state === "TESTING" ? item.artifacts.test_result : undefined,
|
|
496
|
+
// tests this request declares that no configured suite runs (TESTING did not run them): tell the person, do not edit the configuration
|
|
497
|
+
test_coverage: state === "TESTING" ? item.artifacts.test_coverage : undefined,
|
|
479
498
|
previous_stages: Object.fromEntries(Object.entries(item.artifacts).filter(([k]) => SCHEMAS[k])),
|
|
480
499
|
human_feedback: item.feedback,
|
|
481
500
|
},
|
|
482
501
|
};
|
|
483
502
|
}
|
|
503
|
+
/**
|
|
504
|
+
* Test files this request declares (the tests added in DEVELOPMENT, the test of each scenario) that no suite of
|
|
505
|
+
* orqen/environment.yaml (`tests`, or TEST_COMMAND without it) runs. Empty when it cannot be known, see test-coverage.ts.
|
|
506
|
+
*/
|
|
507
|
+
untestedFiles(item) {
|
|
508
|
+
const refs = [
|
|
509
|
+
...(item.artifacts.DEVELOPMENT?.added_tests ?? []),
|
|
510
|
+
...((item.artifacts.TESTING?.scenarios ?? []).map((s) => s.test ?? "")),
|
|
511
|
+
];
|
|
512
|
+
const configured = Object.values(this.cfg.environment?.tests ?? {}).filter((c) => !!c);
|
|
513
|
+
return testCoverage(refs, configured.length ? configured : [this.cfg.testCommand]).uncovered;
|
|
514
|
+
}
|
|
484
515
|
// ================================================================ pr
|
|
485
516
|
/** Where the request branch would go and whether it can be sent now (used by `orqen pr <KEY>` before writing the explanation). */
|
|
486
517
|
prInfo(key) {
|
|
@@ -802,6 +833,10 @@ export class Process {
|
|
|
802
833
|
return this.commentBoth(item, `Development could not be completed: ${s.blocker}`);
|
|
803
834
|
case "TESTING": {
|
|
804
835
|
const rt = item.artifacts.test_result;
|
|
836
|
+
const untested = this.untestedFiles(item);
|
|
837
|
+
const warning = untested.length
|
|
838
|
+
? `\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"}.`
|
|
839
|
+
: "";
|
|
805
840
|
const table = s.scenarios.map((e) => `- ${e.covered ? "✔" : "✘"} ${e.requirement} › ${e.scenario}${e.test ? ` (${e.test})` : ""}`).join("\n");
|
|
806
841
|
if (s.approved) {
|
|
807
842
|
// testing does not open the PR: the senior reviews the PR to the devel branch (`orqen pr`)
|
|
@@ -811,9 +846,9 @@ export class Process {
|
|
|
811
846
|
: this.cfg.codeReviewGate === "github"
|
|
812
847
|
? "Code review: approve or request changes on the PR in GitHub."
|
|
813
848
|
: "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}`);
|
|
849
|
+
return this.commentBoth(item, `Tests passed and all scenarios are covered:\n${table}${warning}\n\n${pr}\n${decide}`);
|
|
815
850
|
}
|
|
816
|
-
return this.commentBoth(item, `Testing failed (attempt ${item.testingAttempts}). Suite: ${rt?.ok ? "OK" : "FAILED"}\n${table}\n\nDiagnosis: ${s.failure_diagnosis}` +
|
|
851
|
+
return this.commentBoth(item, `Testing failed (attempt ${item.testingAttempts}). Suite: ${rt?.ok ? "OK" : "FAILED"}\n${table}${warning}\n\nDiagnosis: ${s.failure_diagnosis}` +
|
|
817
852
|
(next === "BLOCKED" ? "\nRetries are exhausted. Human review is needed." : "\nReturning to development."));
|
|
818
853
|
}
|
|
819
854
|
case "EXECUTION": {
|
|
@@ -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
|
+
}
|