@telpin-sistemas/orqen 0.1.11 → 0.1.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -58,6 +58,16 @@ export class LocalTracker {
58
58
  }
59
59
  });
60
60
  }
61
+ async addLabel(key, label) {
62
+ const t = this.read(key);
63
+ if (!t.labels.includes(label)) {
64
+ t.labels.push(label);
65
+ this.write(t);
66
+ }
67
+ }
68
+ async labelled(label) {
69
+ return (await this.pending()).filter((k) => this.read(k).labels.includes(label));
70
+ }
61
71
  async search(query) {
62
72
  const q = query.toLowerCase().trim();
63
73
  return this.keys().filter((k) => {
@@ -44,6 +44,46 @@ export function toMarkdown(text) {
44
44
  out.push("```"); // an unclosed block must not swallow what follows
45
45
  return out.join("\n");
46
46
  }
47
+ /**
48
+ * Plain text for tools that show comments as typed (Asana's `text`): the Jira markup goes away without losing structure.
49
+ * `*bold*` → bold, `* item` → `• item`, `# item` → `1. item`, `h2. Title` → Title, `{{x}}` → x, `[text|url]` → text (url),
50
+ * `{code}` blocks keep their lines, indented. Text with no markup is returned as it is.
51
+ */
52
+ export function toPlain(text) {
53
+ const out = [];
54
+ let fence = false, numbered = 0;
55
+ for (const raw of text.replace(/\r\n/g, "\n").split("\n")) {
56
+ if (/^\s*\{(?:code|noformat)(?::[\w+-]+)?\}\s*$/.test(raw)) {
57
+ fence = !fence;
58
+ continue;
59
+ }
60
+ if (fence) {
61
+ out.push(` ${raw}`);
62
+ continue;
63
+ }
64
+ const n = raw.match(/^#\s+(.*)$/);
65
+ if (n) {
66
+ numbered++;
67
+ out.push(`${numbered}. ${plainInline(n[1])}`);
68
+ continue;
69
+ }
70
+ numbered = 0;
71
+ const h = raw.match(/^h[1-6]\.\s+(.*)$/);
72
+ if (h) {
73
+ out.push(plainInline(h[1]));
74
+ continue;
75
+ }
76
+ const b = raw.match(/^\*\s+(.*)$/);
77
+ out.push(b ? `• ${plainInline(b[1])}` : plainInline(raw));
78
+ }
79
+ return out.join("\n");
80
+ }
81
+ function plainInline(line) {
82
+ return line
83
+ .replace(/(?<![*\w])\*(?=\S)([^*\n]+?)(?<=\S)\*(?![*\w])/g, "$1")
84
+ .replace(/\{\{([^}\n]+)\}\}/g, "$1")
85
+ .replace(/\[([^\]|\n]+)\|(https?:\/\/[^\]\s]+)\]/g, "$1 ($2)");
86
+ }
47
87
  function inline(line) {
48
88
  return line
49
89
  // *bold* → **bold** (not when it is already **bold**, nor a * inside a word)
@@ -15,6 +15,8 @@ export const isBotComment = (body) => [BOT_MARK, ...LEGACY_BOT_MARKS].some((m) =
15
15
  /** Prefix of the label that mirrors the orqen state on the ticket (e.g. orqen-state-development). */
16
16
  export const STATE_LABEL = "orqen-state-";
17
17
  export const LEGACY_STATE_LABELS = ["rec-state-"];
18
+ /** Label of the issue of a worq started by the team (`orqen new_worq`): any machine finds it and knows it has no client request. */
19
+ export const WORQ_LABEL = "orqen-worq";
18
20
  /** Readable detail of a failed check: Node's fetch only says "fetch failed" and leaves the reason in `cause`. */
19
21
  export function checkFailure(e, host) {
20
22
  const err = e;
package/dist/lib/kit.js CHANGED
@@ -7,11 +7,12 @@
7
7
  * - Skip files already up to date.
8
8
  * - Replace files that match the saved hash.
9
9
  * - Ask the user how to handle local edits.
10
+ * - Delete the kit files that the kit no longer ships (a command that was renamed or removed), unless the team edited them.
10
11
  * Manage only the marked AGENTS.md block.
11
12
  * Merge additions into OpenSpec config, CLAUDE.md, .gitignore, and marketplace.json.
12
13
  */
13
14
  import { createHash } from "node:crypto";
14
- import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
15
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
15
16
  import { dirname, join, relative } from "node:path";
16
17
  import { VERSION_CLI } from "./system.js";
17
18
  import { TEMPLATES_DIR } from "./template-assets.js";
@@ -143,6 +144,8 @@ export function claudeSettings(actual, mk) {
143
144
  j.enabledPlugins = { ...(j.enabledPlugins ?? {}), [`orqen@${mk}`]: true };
144
145
  return JSON.stringify(j, null, 2) + "\n";
145
146
  }
147
+ /** Folders whose files belong to the kit: what it stops shipping there can be deleted. */
148
+ const KIT_OWNED = /^orqen\/(plugin|stages)\//;
146
149
  export function planificar(repo, vars, o = {}) {
147
150
  const manifest = leerManifest(repo);
148
151
  const cambios = [];
@@ -161,6 +164,14 @@ export function planificar(repo, vars, o = {}) {
161
164
  accion = "conflicto";
162
165
  cambios.push({ ruta, modo: "archivo", accion, nuevo, actual, hashNuevo: h });
163
166
  }
167
+ // Files of an earlier kit that this one no longer ships, only inside the folders the kit owns.
168
+ for (const ruta of Object.keys(manifest.archivos)) {
169
+ if (ruta in archivos || !KIT_OWNED.test(ruta))
170
+ continue;
171
+ const actual = leer(join(repo, ruta));
172
+ const editado = actual !== undefined && manifest.archivos[ruta] !== hash(actual);
173
+ cambios.push({ ruta, modo: "archivo", accion: editado ? "obsoleto" : "borrar", nuevo: "", actual });
174
+ }
164
175
  // Managed AGENTS.md block
165
176
  {
166
177
  const ruta = "AGENTS.md", clave = "AGENTS.md#orqen";
@@ -211,6 +222,13 @@ export async function aplicar(repo, cambios, resolver) {
211
222
  out.push({ ruta: c.ruta, accion: "igual" });
212
223
  continue;
213
224
  }
225
+ if (c.accion === "borrar" || c.accion === "obsoleto") {
226
+ if (c.accion === "borrar")
227
+ rmSync(join(repo, c.ruta), { force: true });
228
+ delete manifest.archivos[clave];
229
+ out.push({ ruta: c.ruta, accion: c.accion });
230
+ continue;
231
+ }
214
232
  if (c.accion === "conflicto") {
215
233
  const d = await resolver(c);
216
234
  if (d === "mantener") {
@@ -56,14 +56,21 @@ function leerPuertos(repo) {
56
56
  return {};
57
57
  }
58
58
  }
59
- /** Can this port be listened on now? */
60
- export function puertoLibre(puerto) {
59
+ /** Can this port be listened on on that host? An IPv6 host on a machine without IPv6 does not count against it. */
60
+ function sePuedeEscuchar(puerto, host) {
61
61
  return new Promise((ok) => {
62
62
  const s = createServer();
63
- s.once("error", () => ok(false));
64
- s.listen({ port: puerto, host: "127.0.0.1", exclusive: true }, () => s.close(() => ok(true)));
63
+ s.once("error", (e) => ok(host === "::" && ["EAFNOSUPPORT", "EADDRNOTAVAIL"].includes(e.code ?? "")));
64
+ s.listen({ port: puerto, host, exclusive: true }, () => s.close(() => ok(true)));
65
65
  });
66
66
  }
67
+ /**
68
+ * Can this port be listened on now? Checks IPv4 and IPv6 and that nothing answers on it: on Windows a server listening
69
+ * on `::` (Node's default) does not stop a bind on 127.0.0.1, so binding only there would hand the same port to two worktrees.
70
+ */
71
+ export async function puertoLibre(puerto) {
72
+ return await sePuedeEscuchar(puerto, "127.0.0.1") && await sePuedeEscuchar(puerto, "::") && !(await puertoAbierto(puerto, 300));
73
+ }
67
74
  /** The ports in use by this worktree: the assigned one of each dynamic process, the fixed one of the rest. */
68
75
  export function puertosActuales(repo, procesos, variables = {}) {
69
76
  const guardados = leerPuertos(repo);
@@ -1,10 +1,12 @@
1
1
  ---
2
- description: Start a worq the team itself needs (no client request, no support or analysis): creates its issue in the connector and takes it to development
3
- argument-hint: <title>
2
+ description: Start a worq the team itself needs (no client request, no support or analysis): creates its issue in the connector, or takes an existing one, and takes it to development
3
+ argument-hint: <title> | <ISSUE-KEY>
4
4
  allowed-tools: Bash(orqen:*), AskUserQuestion
5
5
  ---
6
6
 
7
- Use the title in `$ARGUMENTS`. If it is missing, ask the person for it. This is work the team starts itself: there is no client or request, so support and analysis are skipped. orqen creates the issue in the connector the project uses (the issues connector, or the requests one when there is none).
7
+ `$ARGUMENTS` is the title of the work, or the key of an issue that already exists (e.g. `GH-12`, `DEV-34`). If it is missing, ask the person for it. This is work the team starts itself: there is no client or request, so support and analysis are skipped. orqen creates the issue in the connector the project uses (the issues connector, or the requests one when there is none), or takes the existing one.
8
+
9
+ If it is an existing issue, read it first (`orqen comments <KEY>` shows its title, description and comments) and start the brief from what it says.
8
10
 
9
11
  Talk with the person briefly, in their language, until you have what `orqen new_worq` needs. Ask only what you cannot infer, one question at a time with your recommendation:
10
12
  - **description**: what to do and why, in a few sentences.
@@ -12,10 +14,19 @@ Talk with the person briefly, in their language, until you have what `orqen new_
12
14
  - **plan**: the steps, each ending with its estimate in hours, e.g. `Unify the entry point (2h)`.
13
15
  - **estimated_hours**: the total.
14
16
 
15
- Show the person the brief and get their explicit OK, because the issue is created in the tracker right away. Then write it as JSON in a temporary file outside the repository and run, from the repository root:
17
+ Recognise the kind of work and propose its usual criteria, so the person confirms or adjusts instead of writing them from scratch:
18
+ - **Refactor**: the behaviour does not change (the existing tests pass without editing them); what was duplicated or tangled has one place; no public API changes unless agreed.
19
+ - **Technical debt / cleanup**: the dead code, warning or workaround named in the description is gone; the build and the tests stay green.
20
+ - **Dependency upgrade**: the new version is in the manifest and the lock file; the tests pass; the breaking changes of the changelog that affect the project are handled (name them).
21
+ - **Bug the team found**: a test that reproduces the bug fails before the fix and passes after it; nearby behaviour stays the same.
22
+ - **Tooling / CI / scripts**: the new command or job runs from a clean checkout; the README or the docs say how to use it.
23
+ - **Performance**: the operation is measured before and after with the same data, and the target is a number.
24
+
25
+ Show the person the brief and get their explicit OK, because the issue is created (or labelled and commented) in the tracker right away. Then write it as JSON in a temporary file outside the repository and run, from the repository root:
16
26
 
17
- `orqen new_worq "<title>" <brief.json>`
27
+ - new issue: `orqen new_worq "<title>" <brief.json>`
28
+ - existing issue: `orqen new_worq --issue <KEY> <brief.json>` (the title is the issue's; pass `"<title>"` before the file to use another)
18
29
 
19
- The brief is `{ "description": "...", "acceptance_criteria": ["..."], "plan": ["... (2h)"], "estimated_hours": 4 }`. orqen validates it, creates the issue in the connector and starts the worq with that issue's key (`<KEY>`), in DEVELOPMENT, direct lane. If it reports the brief is invalid, nothing was created: fix what it names and run it again.
30
+ The brief is `{ "description": "...", "acceptance_criteria": ["..."], "plan": ["... (2h)"], "estimated_hours": 4 }`. orqen validates it and starts the worq with the issue's key (`<KEY>`), in DEVELOPMENT, direct lane. If it reports the brief is invalid, nothing was created: fix what it names and run it again. If it says the issue was created but the worq could not start, fix that and run the `--issue` command it prints, so no second issue is created.
20
31
 
21
32
  Then continue with `/orqen:implement <KEY>`. The rest of the flow is the usual one (testing, `/orqen:pr`, senior `/orqen:approve`) without QA. There is no delivery or client acceptance: when a person merges the PR by hand, orqen detects it and closes the worq and its issue.
@@ -30,7 +30,7 @@ The 9 steps, one command each (the person runs it; you follow it):
30
30
 
31
31
  ### Working with the person
32
32
 
33
- Development the team starts itself (no client, no request) skips support and analysis: `/orqen:new_worq <title>` (or `orqen new_worq "<title>" <brief.json>`) creates the issue in the connector in use and a worq with its key in DEVELOPMENT, direct lane, with the brief as its analysis. It follows implement → testing → PR → senior review, without QA, and closes by itself when a person merges the PR (there is no delivery or client acceptance). Its issue is created in the issues connector (or the requests one when there is none) and closed with the worq.
33
+ Development the team starts itself (no client, no request) skips support and analysis: `/orqen:new_worq <title>` (or `orqen new_worq "<title>" <brief.json>`) creates the issue in the connector in use (or takes an existing one with `--issue <KEY>`) and a worq with its key in DEVELOPMENT, direct lane, with the brief as its analysis. It follows implement → testing → PR → senior review, without QA, and closes by itself when a person merges the PR (there is no delivery or client acceptance). Its issue is created in the issues connector (or the requests one when there is none) and closed with the worq.
34
34
 
35
35
  In any stage, use `/orqen:ask <KEY> <question>` to ask the requester directly on the original request. The requester can reply with an ordinary comment. To read the replies and refresh `orqen/worqs/<KEY>/conversation.json`, run `orqen conversation <KEY>`. Both commands accept the request key or its linked issue key and preserve the current stage.
36
36
 
@@ -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,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
+ }
@@ -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 } 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)));
@@ -100,7 +104,10 @@ export class Process {
100
104
  const state = label ? label.slice(prefix.length).toUpperCase() : "";
101
105
  if (!(state in State) || state === "NEW")
102
106
  return newWorkItem(key);
103
- const item = { ...newWorkItem(key), state: state, title: ticket.title, recovered: "label" };
107
+ const item = {
108
+ ...newWorkItem(key), state: state, title: ticket.title, recovered: "label",
109
+ ...(ticket.labels.includes(WORQ_LABEL) || this.requests.isTeamWorq(key) ? { origin: "internal" } : {}),
110
+ };
104
111
  this.fromLabels.set(key, item);
105
112
  return item;
106
113
  }
@@ -122,6 +129,33 @@ export class Process {
122
129
  const rel = relative(this.cfg.repoPath, join(this.cfg.factoryDir, key)).replaceAll("\\", "/");
123
130
  return rel.startsWith("..") || /^[a-zA-Z]:/.test(rel) ? `orqen/worqs/${key}` : rel;
124
131
  }
132
+ branchOnOrigin = new Map();
133
+ /**
134
+ * A worq this machine knows only from its ticket's label: fetch its branch to recover it, or, when the branch is not on
135
+ * origin yet (whoever started it has not pushed), say so instead of suggesting a fetch that fails. Asked once per branch.
136
+ */
137
+ recoveredHint(key) {
138
+ const branch = branchFor(key);
139
+ if (!this.branchOnOrigin.has(branch)) {
140
+ let on;
141
+ try {
142
+ on = this.ws.remoteBranchExists?.(branch);
143
+ }
144
+ catch {
145
+ on = undefined;
146
+ }
147
+ this.branchOnOrigin.set(branch, on);
148
+ }
149
+ if (this.branchOnOrigin.get(branch) === false)
150
+ return {
151
+ command: "", what: `Its branch ${branch} is not on origin yet: it appears once whoever started it pushes it (orqen pr)`,
152
+ text: `The state is read from the ticket's label: this machine has no record, and its branch ${branch} is not on origin yet. It appears once whoever started it pushes it (orqen pr); then git fetch origin ${branch} recovers the worq.`,
153
+ };
154
+ return {
155
+ command: `git fetch origin ${branch}`, what: "The state comes from the ticket only: fetch the request branch so orqen recovers its full record, then continue",
156
+ text: `The state is read from the ticket's label: this machine has no record. Fetch its branch to recover the worq (git fetch origin ${branch}).`,
157
+ };
158
+ }
125
159
  fetchHint(key) {
126
160
  return `If someone worked on it elsewhere, fetch its branch (git fetch origin ${branchFor(key)}) so orqen can recover its worq from ${this.worqRel(key)}/state.json.`;
127
161
  }
@@ -179,6 +213,12 @@ export class Process {
179
213
  }
180
214
  }
181
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
+ }
182
222
  await this.block(key, `Error reviewing the request: ${e.message}`, "process");
183
223
  }
184
224
  }
@@ -210,7 +250,7 @@ export class Process {
210
250
  qa: needsQa(item) && item.state === "QA_REVIEW" ? "pending" : needsQa(item) && item.state === "CODE_REVIEW" ? "approved" : undefined,
211
251
  recovered: item.recovered,
212
252
  next: item.recovered
213
- ? [{ step: 0, role: roleOf(item, this.cfg), command: `git fetch origin ${branchFor(item.key)}`, what: "The state comes from the ticket only: fetch the request branch so orqen recovers its full record, then continue" }]
253
+ ? (({ command, what }) => [{ step: 0, role: roleOf(item, this.cfg), command, what }])(this.recoveredHint(item.key))
214
254
  : nextSteps(item, this.cfg),
215
255
  updated: this.store.events(item.key).at(-1)?.ts,
216
256
  merge: item.state === "DELIVERY" && item.artifacts.devel_pr ? (item.artifacts.devel_pr_merged ? "merged" : "pending") : undefined,
@@ -405,6 +445,13 @@ export class Process {
405
445
  finally {
406
446
  this.ws.stopEnvironment?.();
407
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;
408
455
  }
409
456
  if (state === "DELIVERY" && item.change && !item.artifacts.archive) {
410
457
  item.artifacts.archive = this.os.archive(item.change);
@@ -446,11 +493,25 @@ export class Process {
446
493
  ...(["DEVELOPMENT", "TESTING"].includes(state) ? { tasks: this.tasksOf(item) } : {}),
447
494
  ...(state === "TESTING" ? { scenarios: this.scenariosOf(item) } : {}),
448
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,
449
498
  previous_stages: Object.fromEntries(Object.entries(item.artifacts).filter(([k]) => SCHEMAS[k])),
450
499
  human_feedback: item.feedback,
451
500
  },
452
501
  };
453
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
+ }
454
515
  // ================================================================ pr
455
516
  /** Where the request branch would go and whether it can be sent now (used by `orqen pr <KEY>` before writing the explanation). */
456
517
  prInfo(key) {
@@ -772,6 +833,10 @@ export class Process {
772
833
  return this.commentBoth(item, `Development could not be completed: ${s.blocker}`);
773
834
  case "TESTING": {
774
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
+ : "";
775
840
  const table = s.scenarios.map((e) => `- ${e.covered ? "✔" : "✘"} ${e.requirement} › ${e.scenario}${e.test ? ` (${e.test})` : ""}`).join("\n");
776
841
  if (s.approved) {
777
842
  // testing does not open the PR: the senior reviews the PR to the devel branch (`orqen pr`)
@@ -781,9 +846,9 @@ export class Process {
781
846
  : this.cfg.codeReviewGate === "github"
782
847
  ? "Code review: approve or request changes on the PR in GitHub."
783
848
  : "Code review: comment */approve* or */reject <reason>*.";
784
- 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}`);
785
850
  }
786
- 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}` +
787
852
  (next === "BLOCKED" ? "\nRetries are exhausted. Human review is needed." : "\nReturning to development."));
788
853
  }
789
854
  case "EXECUTION": {
@@ -1006,9 +1071,24 @@ export class Process {
1006
1071
  * use (issues, or requests when there is none) and skips support and analysis: the brief (description, acceptance criteria and plan)
1007
1072
  * takes the place of the analysis and the worq, keyed by that issue, is born in DEVELOPMENT, direct lane (implement → testing → PR →
1008
1073
  * senior). It closes when its PR is merged.
1074
+ * With `existing` (`--issue <KEY>`) it takes an issue that is already there (created by a person, or left by an attempt that failed)
1075
+ * instead of creating one: the title defaults to the issue's.
1009
1076
  */
1010
- async newWorq(title, raw, person) {
1011
- const t = title.trim();
1077
+ async newWorq(title, raw, person, existing) {
1078
+ const own = this.requests.ownSystem;
1079
+ let current;
1080
+ if (existing) {
1081
+ const was = this.item(existing);
1082
+ if (was)
1083
+ throw new Error(`${existing} is already a worq (${was.state}): see it with orqen status ${existing}`);
1084
+ try {
1085
+ current = await own.ticket(existing);
1086
+ }
1087
+ catch (e) {
1088
+ throw new Error(`${existing} could not be read in ${own.label}: ${e.message.split("\n")[0]}`);
1089
+ }
1090
+ }
1091
+ const t = title.trim() || current?.title?.trim() || "";
1012
1092
  if (t.length < 5)
1013
1093
  throw new Error("A title for the worq is required (at least 5 characters).");
1014
1094
  const b = (raw ?? {});
@@ -1016,7 +1096,9 @@ export class Process {
1016
1096
  const analysis = {
1017
1097
  summary: typeof b.summary === "string" && b.summary.trim() ? b.summary.trim() : description || t,
1018
1098
  type: "change", acceptance_criteria: b.acceptance_criteria, affected_capabilities: [], open_questions: [], risks: Array.isArray(b.risks) ? b.risks : [],
1019
- ready: true, analyst_ok: true, route: "development", lane: "direct", lane_rationale: "Started by the team: no client request, direct lane.",
1099
+ ready: true, analyst_ok: true, route: "development", lane: "direct", lane_rationale: existing
1100
+ ? `Taken by orqen as a worq of the team (no client request), started by ${person}: direct lane.`
1101
+ : "Started by the team: no client request, direct lane.",
1020
1102
  plan: b.plan, estimated_hours: b.estimated_hours,
1021
1103
  };
1022
1104
  // validated before creating anything: an invalid brief must not leave an issue behind
@@ -1024,18 +1106,27 @@ export class Process {
1024
1106
  if (!parsed.success)
1025
1107
  throw new Error(`The brief is not valid:\n${parsed.error.issues.map((i) => ` ${i.path.join(".") || "(root)"}: ${i.message}`).join("\n")}`);
1026
1108
  const s = parsed.data;
1027
- const key = await this.requests.create({
1028
- title: t, route: "development", labels: ["orqen", "lane-direct"],
1029
- description: `${description || t}\n\n*Acceptance criteria:*\n${bullets(s.acceptance_criteria)}\n\n*Plan:*\n${bullets(s.plan ?? [])}\n\n` +
1030
- `*Estimate:* ${s.estimated_hours ?? "?"} h\n*Started by:* ${person}\n\nCreated with orqen (no client request).`,
1031
- });
1109
+ const brief = `*Acceptance criteria:*\n${bullets(s.acceptance_criteria)}\n\n*Plan:*\n${bullets(s.plan ?? [])}\n\n*Estimate:* ${s.estimated_hours ?? "?"} h\n*Started by:* ${person}`;
1110
+ let key;
1111
+ if (existing) {
1112
+ key = existing;
1113
+ // the label lets any machine find it; without addLabel (Asana) only the machines that know it do
1114
+ await this.attemptAsync(() => own.addLabel?.(key, WORQ_LABEL) ?? Promise.resolve());
1115
+ }
1116
+ else {
1117
+ key = await this.requests.create({
1118
+ title: t, route: "development", labels: [WORQ_LABEL, "lane-direct"],
1119
+ description: `${description || t}\n\n${brief}\n\nCreated with orqen (no client request).`,
1120
+ });
1121
+ }
1032
1122
  const item = { ...newWorkItem(key), state: "ANALYSIS", origin: "internal", title: t, analyst: person, lock: { agent: "internal", since: new Date().toISOString() } };
1033
1123
  this.store.save(item);
1034
1124
  const r = await this.complete(key, analysis, "internal");
1035
1125
  if (!r.ok) {
1036
1126
  this.store.remove(key);
1037
1127
  rmSync(this.fac.dirOf(key), { recursive: true, force: true });
1038
- throw new Error(`The issue ${key} was created, but the worq could not start:\n${r.errors.map((e) => " " + e).join("\n")}`);
1128
+ throw new Error(`The issue ${key} ${existing ? "is there" : "was created"}, but the worq could not start:\n${r.errors.map((e) => " " + e).join("\n")}\n` +
1129
+ `Fix it and take that issue with: orqen new_worq --issue ${key} <brief.json>`);
1039
1130
  }
1040
1131
  if (description)
1041
1132
  this.fac.write(item, "brief.md", `# ${key} — ${t}\n\n${description}\n`);