@telpin-sistemas/orqen 0.1.3 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +10 -7
  2. package/dist/commands/client-chat.js +42 -0
  3. package/dist/commands/environment.js +13 -10
  4. package/dist/commands/eval.js +1 -1
  5. package/dist/commands/init.js +32 -13
  6. package/dist/commands/swarm.js +1 -1
  7. package/dist/commands/tutorial.js +1 -1
  8. package/dist/commands/update.js +150 -37
  9. package/dist/commands/workflow.js +130 -6
  10. package/dist/connectors/asana.js +14 -4
  11. package/dist/connectors/config.js +10 -5
  12. package/dist/connectors/describe.js +2 -2
  13. package/dist/connectors/github.js +7 -2
  14. package/dist/connectors/index.js +3 -0
  15. package/dist/connectors/jira.js +20 -8
  16. package/dist/connectors/legacy.js +1 -0
  17. package/dist/connectors/local.js +104 -0
  18. package/dist/connectors/markup.js +53 -0
  19. package/dist/eval/fake-jira.js +1 -1
  20. package/dist/eval/run.js +3 -3
  21. package/dist/index.js +24 -6
  22. package/dist/lib/agent.js +2 -2
  23. package/dist/lib/config-keys.js +126 -0
  24. package/dist/lib/config.js +76 -13
  25. package/dist/lib/connectors-edit.js +28 -0
  26. package/dist/lib/connectors-setup.js +12 -1
  27. package/dist/lib/kit.js +3 -9
  28. package/dist/lib/proc.js +2 -2
  29. package/dist/lib/provider-credentials.js +17 -6
  30. package/dist/lib/stack.js +1 -1
  31. package/dist/lib/system.js +5 -7
  32. package/dist/lib/tools.js +2 -2
  33. package/dist/lib/transitions-suggest.js +15 -0
  34. package/dist/lib/worqs.js +51 -0
  35. package/dist/practice/practice.js +221 -0
  36. package/dist/practice/scenario.js +186 -0
  37. package/dist/sdd/index.js +1 -1
  38. package/dist/swarm/plan.js +1 -1
  39. package/dist/swarm/run.js +2 -2
  40. package/dist/template/.agents/commands/analyze.md +2 -2
  41. package/dist/template/.agents/commands/approve.md +2 -2
  42. package/dist/template/.agents/commands/ask.md +11 -0
  43. package/dist/template/.agents/commands/implement.md +2 -2
  44. package/dist/template/.agents/commands/review.md +3 -3
  45. package/dist/template/.agents/commands/support.md +1 -1
  46. package/dist/template/.agents/skills/grilling/SKILL.md +1 -1
  47. package/dist/template/AGENTS.md +18 -12
  48. package/dist/template/orqen/worqs/README.md +9 -0
  49. package/dist/template/stages/analysis.md +1 -1
  50. package/dist/template/stages/delivery.md +1 -1
  51. package/dist/template/stages/development.md +3 -3
  52. package/dist/template/stages/support.md +1 -1
  53. package/dist/tutorial/content.js +2 -2
  54. package/dist/ui/logo.js +4 -4
  55. package/dist/workflow/config.js +36 -17
  56. package/dist/workflow/factory.js +13 -7
  57. package/dist/workflow/process.js +165 -42
  58. package/dist/workflow/workspace.js +43 -6
  59. package/package.json +2 -2
  60. package/dist/template/env.example +0 -27
  61. package/dist/template/orqen/work/README.md +0 -3
package/README.md CHANGED
@@ -9,12 +9,12 @@ orqen init # Run from the repository you want to initialize
9
9
 
10
10
  `orqen init [dir]` runs the following setup:
11
11
 
12
- 1. Displays the ORQEN logo and checks Node (20.12 or later), Git, and a package manager. The animation needs a terminal with at least 92 columns and 23 rows. Press Enter to continue. Non-interactive terminals, CI, `--yes`, and `--no-animation` use the static logo.
12
+ 1. Displays the orqen logo and checks Node (20.12 or later), Git, and a package manager. The animation needs a terminal with at least 92 columns and 23 rows. Press Enter to continue. Non-interactive terminals, CI, `--yes`, and `--no-animation` use the static logo.
13
13
  2. Detects components and services from manifests such as `package.json`, `pom.xml`, and `pyproject.toml`, as well as Prisma and `.env.example`, including the command that starts each part (`npm run dev`, `npm start`…).
14
14
  3. Uses an installed AI agent to review a short repository summary in the background. It validates the proposal with Zod. Use `--deep` to let the agent explore the repository or `--no-ai` to use automatic detection only.
15
15
  4. Lets you confirm or edit components, the command that starts each part, tests, migrations, and seed commands.
16
16
  5. Finds a compatible OpenSpec installation (version 2.x), installs it if needed, and runs `openspec init` for the selected tools with English artifact output.
17
- 6. Configures the connectors: the requests system the client sees and an optional issues system for the team (Jira, GitHub or Asana). It asks for the project/filter and the account, checks them against the tool and, if the check fails, lets you fix them, save them anyway or skip (`orqen connectors setup` later). The selection goes to `orqen/config.yaml`; provider accounts go to `~/.orqen/providers.env`, shared across repositories (Enter keeps an existing token). Existing connectors and general settings are kept by default. `orqen connectors` checks the configured resources.
17
+ 6. Configures the connectors: the requests system the client sees and an optional issues system for the team (Jira, GitHub or Asana). It asks for the project/filter and the account, checks them against the tool and, if the check fails, lets you fix them, save them anyway or skip (`orqen connectors setup` later). The selection goes to `orqen/config.yaml`; provider accounts go to `~/.orqen/credentials.env`, shared across repositories (Enter keeps an existing token). Existing connectors and general settings are kept by default. `orqen connectors` checks the configured resources.
18
18
  7. Writes the environment configuration (no Docker in between), agent instructions, plugin, stage guides, and manifest. It merges the OpenSpec workflow rules with the repository's existing configuration.
19
19
 
20
20
  `init` configures an existing project without requesting, cloning or reading the external stack catalog. It reuses any database scripts already installed in the project; new service scripts come from `bootstrap`.
@@ -40,7 +40,9 @@ For non-interactive first use of `bootstrap`, pass `--tools-repo @company/tools`
40
40
 
41
41
  ## Update an installation
42
42
 
43
- `orqen update [dir]` checks for a newer CLI, a compatible OpenSpec update, and kit changes. The kit updates files that still match the manifest. For edited files, you can keep the existing version, replace it, or write a copy with the `.orqen-new` suffix.
43
+ Run `orqen update` from any directory to update the CLI. In an orqen project, the same command continues with OpenSpec and the kit using the newly installed CLI. Use `--cli-only` to update just the CLI from inside a project, or `orqen update --desktop` to update the global npm desktop app.
44
+
45
+ The kit updates files that still match the manifest. For edited files, you can keep the existing version, replace it, or write a copy with the `.orqen-new` suffix.
44
46
 
45
47
  Use `--no-cli`, `--no-openspec`, or `--no-kit` to skip a step. Run `orqen init` again when you need to detect the stack or regenerate the environment.
46
48
 
@@ -49,12 +51,12 @@ Use `--no-cli`, `--no-openspec`, or `--no-kit` to skip a step. Run `orqen init`
49
51
  ```sh
50
52
  orqen env setup
51
53
  orqen env up [--all]
52
- orqen env test [unitarios|integracion|e2e|visual]
54
+ orqen env test [unit|integration|e2e|visual]
53
55
  orqen env status
54
56
  orqen env down
55
57
  ```
56
58
 
57
- `up` starts the processes in `entornos.procesos` in the background (`--all` includes the `cuando: e2e` ones, such as the frontend), waits until each one responds on its port, URL, or log line, then runs migrations and seed commands. `down` stops what orqen started; `status` shows what is running and where each log is (`orqen/state/logs/`). The test commands receive variables from `entornos.variables` in `orqen/config.yaml`. The values `unitarios` and `integracion` select unit and integration tests.
59
+ `up` starts the `processes` of `orqen/environment.yaml` in the background (`--all` includes the `when: e2e` ones, such as the frontend), waits until each one responds on its port, URL, or log line, then runs migrations and seed commands. `down` stops what orqen started; `status` shows what is running and where each log is (`orqen/state/logs/`). The test commands receive the `variables` of `orqen/environment.yaml`. `orqen env test unit|integration|e2e|visual` runs one suite (`unitarios` and `integracion` still work).
58
60
 
59
61
  ## Split a task across a swarm of agents
60
62
 
@@ -72,6 +74,7 @@ A planner model (default Opus) splits the task into a dependency graph of small
72
74
  orqen list requests
73
75
  orqen analyze SOP-1234
74
76
  orqen status DEV-442
77
+ orqen worqs # the worqs on this machine: orqen's unit of work, one per request (orqen/worqs/)
75
78
  orqen take DEV-442
76
79
  orqen complete DEV-442 output.json
77
80
  orqen cycle --loop
@@ -81,9 +84,9 @@ orqen cycle --loop
81
84
 
82
85
  In `TESTING`, taking the stage starts the full environment, runs the configured suite, and shuts everything down. `orqen cycle --loop` dispatches eligible requests using `AGENT_CMD`. Analysis always requires an analyst.
83
86
 
84
- In the full lane, QA runs `/orqen:review <KEY>` in `QA_REVIEW` and records the decision with `orqen review <KEY> approve|reject`; the direct and light lanes skip QA. Run `orqen pr <KEY>` to inspect the integration target or add an explanation file to open the PR to `DEVEL_BRANCH`; testing opens no PR, so this is the PR the senior reviews. In `CODE_REVIEW`, the senior runs `/orqen:code-review <KEY>`, and `orqen code-review <KEY> <report.md> --verdict <approve|minor|reject>` records the report under `orqen/work/<KEY>/round-N/` and comments it on the internal ticket (or the external one) without changing the stage.
87
+ In the full lane, QA runs `/orqen:review <KEY>` in `QA_REVIEW` and records the decision with `orqen review <KEY> approve|reject`; the direct and light lanes skip QA. Run `orqen pr <KEY>` to inspect the integration target or add an explanation file to open the PR to `DEVEL_BRANCH`; testing opens no PR, so this is the PR the senior reviews. In `CODE_REVIEW`, the senior runs `/orqen:code-review <KEY>`, and `orqen code-review <KEY> <report.md> --verdict <approve|minor|reject>` records the report under `orqen/worqs/<KEY>/round-N/` and comments it on the internal ticket (or the external one) without changing the stage.
85
88
 
86
- For an existing checkout, the CLI also reads `cli/.env` and its local state under `cli/.state/`. Use `template/env.example` as the starting point for that configuration.
89
+ For an existing checkout, the CLI also reads `cli/.env` and its local state under `cli/.state/`. The flow settings (approvers, code review gate, integration branch) live under `workflow` in `orqen/config.yaml` (English keys; the Spanish ones of earlier versions are still read); a variable such as `APPROVERS_CODE` or `DEVEL_BRANCH` in `.env` or the environment overrides them.
87
90
 
88
91
  ## Develop locally
89
92
 
@@ -0,0 +1,42 @@
1
+ /**
2
+ * The conversation with the client: the comments of the request's ticket in the requests system.
3
+ * orqen comments <KEY> [--json] the ticket and its comments (client on one side, the team/orqen on the other)
4
+ * orqen comment <KEY> <file|-> answers the client: a comment signed with the person's name
5
+ * The team's comments carry the orqen mark, so the gates never take them as the client's answer.
6
+ */
7
+ import { isBotComment, BOT_MARK, LEGACY_BOT_MARKS } from "../connectors/types.js";
8
+ import { nombreHerramienta } from "../connectors/describe.js";
9
+ /** "[orqen] **Mateo:** hola" → { author: "Mateo", text: "hola" }; orqen's own messages → author "orqen". */
10
+ export function parseTeamComment(body) {
11
+ let t = body;
12
+ for (const m of [BOT_MARK, ...LEGACY_BOT_MARKS])
13
+ if (t.startsWith(m)) {
14
+ t = t.slice(m.length);
15
+ break;
16
+ }
17
+ t = t.replace(/^\s+/, "");
18
+ const m = t.match(/^\*{1,2}([^*\n]{1,60}?):\*{1,2}\s*/);
19
+ return m ? { author: m[1].trim(), text: t.slice(m[0].length) } : { author: "orqen", text: t };
20
+ }
21
+ export function toMessage(c) {
22
+ if (isBotComment(c.body)) {
23
+ const p = parseTeamComment(c.body);
24
+ return { id: c.id, from: "team", author: p.author, text: p.text, created: c.created };
25
+ }
26
+ return { id: c.id, from: "client", author: c.authorName || c.author, text: c.body, created: c.created };
27
+ }
28
+ export async function readClientChat(t, key) {
29
+ const [ticket, comments] = await Promise.all([t.ticket(key), t.comments(key)]);
30
+ const first = ticket.description.trim()
31
+ ? [{ id: "description", from: "client", author: ticket.reportedBy ?? "", text: ticket.description.trim(), created: "" }] : [];
32
+ return {
33
+ key, title: ticket.title, tool: nombreHerramienta(t.kind), url: ticket.url, status: ticket.status,
34
+ messages: [...first, ...comments.map(toMessage)],
35
+ };
36
+ }
37
+ export async function replyToClient(t, key, text, person) {
38
+ const body = text.trim();
39
+ if (!body)
40
+ throw new Error("Empty message: nothing was sent.");
41
+ await t.comment(key, person ? `**${person}:** ${body}` : body);
42
+ }
@@ -3,7 +3,7 @@
3
3
  * setup install dependencies (entornos.preparar)
4
4
  * up [--all] start the processes (npm run dev, npm start…) and wait until they are ready; then migrations and seed.
5
5
  * --all: also the processes that are only for e2e / visual tests (e.g. the frontend)
6
- * test [type...] unitarios / integracion / e2e / visual with the variables in entornos.variables
6
+ * test [type...] unit / integration / e2e / visual with the variables of orqen/environment.yaml
7
7
  * `-- <args>`: appended to the command of the requested type (e.g. only the e2e of a change)
8
8
  * status which processes are running
9
9
  * down stop the processes orqen started
@@ -14,6 +14,9 @@ import { ejecutarLinea } from "../lib/proc.js";
14
14
  import { bajarProcesos, estadoProcesos, levantarProcesos } from "../lib/processes.js";
15
15
  import { pc } from "../ui/console.js";
16
16
  const TIPOS = ["unitarios", "integracion", "e2e", "visual"];
17
+ /** Test types as people write them (orqen/environment.yaml uses unit / integration); the Spanish names still work. */
18
+ const NOMBRE = { unitarios: "unit", integracion: "integration", e2e: "e2e", visual: "visual" };
19
+ const tipoDe = (s) => (Object.entries(NOMBRE).find(([, en]) => en === s)?.[0] ?? s);
17
20
  const titulo = (s) => console.log(`\n${pc.bold(pc.magenta("▸"))} ${pc.bold(s)}`);
18
21
  async function correr(repo, cfg, lineas, etiqueta) {
19
22
  const env = { ...process.env, ...cfg.entornos.variables };
@@ -40,7 +43,7 @@ export async function entorno(sub, resto, o) {
40
43
  break;
41
44
  case "up": {
42
45
  if (!e.procesos.length)
43
- console.log(pc.dim("No processes configured in orqen/config.yaml (entornos.procesos)."));
46
+ console.log(pc.dim("No processes configured in orqen/environment.yaml (processes)."));
44
47
  const r = await levantarProcesos(repo, e.procesos, e.variables, { todos: o.todos, alAvanzar: (m) => titulo(m) });
45
48
  if (!r.ok) {
46
49
  console.error(pc.red(`✘ ${r.detalle}`));
@@ -60,12 +63,12 @@ export async function entorno(sub, resto, o) {
60
63
  break;
61
64
  }
62
65
  case "test": {
63
- const pedidos = (resto.length ? resto : TIPOS.filter((t) => e.tests[t]));
66
+ const pedidos = (resto.length ? resto.map(tipoDe) : TIPOS.filter((t) => e.tests[t]));
64
67
  const invalidos = pedidos.filter((t) => !TIPOS.includes(t));
65
68
  if (invalidos.length)
66
- throw new Error(`Invalid test type: ${invalidos.join(", ")}. Options: ${TIPOS.join(", ")}`);
69
+ throw new Error(`Invalid test type: ${invalidos.join(", ")}. Options: ${Object.values(NOMBRE).join(", ")}`);
67
70
  if (!pedidos.length)
68
- throw new Error("No test commands are configured in orqen/config.yaml (entornos.tests).");
71
+ throw new Error("No test commands are configured in orqen/environment.yaml (tests).");
69
72
  const extra = o.extra ?? [];
70
73
  if (extra.length && !resto.length)
71
74
  throw new Error("Name the test type the arguments after `--` are for, e.g. orqen env test e2e -- tests/login.spec.ts");
@@ -73,13 +76,13 @@ export async function entorno(sub, resto, o) {
73
76
  for (const t of pedidos) {
74
77
  const cmd = e.tests[t];
75
78
  if (!cmd) {
76
- resultados.push([t, null]);
79
+ resultados.push([NOMBRE[t], null]);
77
80
  continue;
78
81
  }
79
82
  const linea = extra.length ? `${cmd} ${extra.map(citar).join(" ")}` : cmd;
80
- resultados.push([t, await correr(repo, cfg, [linea], `tests ${t}`)]);
83
+ resultados.push([NOMBRE[t], await correr(repo, cfg, [linea], `tests ${NOMBRE[t]}`)]);
81
84
  }
82
- console.log("\n" + resultados.map(([t, r]) => `${r === null ? pc.yellow("–") : r ? pc.green("✔") : pc.red("✘")} ${t}${r === null ? pc.dim(" (no command configured in orqen/config.yaml)") : ""}`).join("\n"));
85
+ console.log("\n" + resultados.map(([t, r]) => `${r === null ? pc.yellow("–") : r ? pc.green("✔") : pc.red("✘")} ${t}${r === null ? pc.dim(" (no command configured in orqen/environment.yaml)") : ""}`).join("\n"));
83
86
  ok = resultados.every(([, r]) => r !== false);
84
87
  break;
85
88
  }
@@ -90,7 +93,7 @@ export async function entorno(sub, resto, o) {
90
93
  break;
91
94
  }
92
95
  if (!st.length)
93
- console.log(pc.dim("No processes configured in orqen/config.yaml (entornos.procesos)."));
96
+ console.log(pc.dim("No processes configured in orqen/environment.yaml (processes)."));
94
97
  for (const x of st)
95
98
  console.log(`${x.corriendo ? pc.green("●") : pc.dim("○")} ${x.nombre.padEnd(16)} ${pc.dim(x.comando)}${x.puerto ? pc.dim(` :${x.puerto}`) : ""}${x.cuando === "e2e" ? pc.dim(" (e2e only)") : ""}${x.log ? pc.dim(`\n log: ${x.log}`) : ""}`);
96
99
  break;
@@ -105,7 +108,7 @@ export async function entorno(sub, resto, o) {
105
108
  "Usage: orqen env <command>",
106
109
  " setup install dependencies (entornos.preparar)",
107
110
  " up [--all] start the processes and wait until they are ready, then migrate and seed (--all: include e2e-only processes)",
108
- " test [type...] unitarios | integracion | e2e | visual (default: all configured tests)",
111
+ " test [type...] unit | integration | e2e | visual (default: all configured tests)",
109
112
  " -- <args>: appended to that type's command, e.g. orqen env test e2e -- tests/login.spec.ts",
110
113
  " status show which processes are running and where their logs are",
111
114
  " down stop the processes orqen started",
@@ -12,7 +12,7 @@ import { EVAL_STEPS, loadCases } from "../eval/cases.js";
12
12
  import { runCase } from "../eval/run.js";
13
13
  import { loadConfig } from "../workflow/config.js";
14
14
  export const EVAL_HELP = ` eval [case|step...] Run the agent on test tickets and check its work (orqen/evals/*.yaml, or the built-in cases)
15
- --agent "<cmd>" Headless agent (default: agente.comando of orqen/config.yaml)
15
+ --agent "<cmd>" Headless agent (default: agent.command of orqen/config.yaml)
16
16
  --judge "<cmd>" Also ask a judge agent whether the output made facts up ("" = the same agent)
17
17
  --no-lessons Without the team's lessons (orqen/knowledge): compare how much they help
18
18
  --keep Keep the test projects · --json Machine-readable result
@@ -6,9 +6,8 @@
6
6
  */
7
7
  import { basename, resolve } from "node:path";
8
8
  import { agentesInstalados, comandoRapido, explorarConAgente, explorarRapidoAislado } from "../lib/agent.js";
9
- import { ARCHIVO_CONFIG, entornosDesdeStack, escribirConfig, existeConfig, leerConfig } from "../lib/config.js";
9
+ import { ARCHIVO_CONFIG, ARCHIVO_ENTORNO, entornosDesdeStack, escribirConfig, existeConfig, leerConfig } from "../lib/config.js";
10
10
  import { detectar } from "../lib/detect.js";
11
- import { escribirEnv, leerEnv, RUTA_ENV } from "../lib/env.js";
12
11
  import { checkSummary, missingSecrets, setupConnectorsStep } from "../lib/connectors-setup.js";
13
12
  import { checkDraft, parseDraft } from "../lib/connectors-edit.js";
14
13
  import { providerEnv, providerFile, saveProviders } from "../lib/provider-credentials.js";
@@ -20,6 +19,7 @@ import { ProcesoEntorno } from "../lib/processes.js";
20
19
  import { PROCESO_DB } from "../lib/tools.js";
21
20
  import { mostrarLogo } from "../ui/logo.js";
22
21
  import { azul, confirmar, diffColoreado, elegir, elegirVarios, gris, interactivo, magenta, p, pc, salirSiCancela, texto, tick, } from "../ui/console.js";
22
+ import { execFileSync } from "node:child_process";
23
23
  import { readFileSync, existsSync } from "node:fs";
24
24
  import { join } from "node:path";
25
25
  const HERRAMIENTAS_OPENSPEC = [
@@ -121,7 +121,6 @@ export async function init(o) {
121
121
  openspecCfg = await prepararOpenSpec(repo, agentes.map((a) => a.id), o.herramientas, yes);
122
122
  const rama = await texto("Base branch for request branches and pull requests", ramaBase(repo), yes);
123
123
  const previous = existeConfig(repo) ? leerConfig(repo) : undefined;
124
- const datosEnv = leerEnv(repo) ? undefined : {};
125
124
  // Connectors: what goes in config.yaml (project, filter…) and the provider accounts, shared by this user's repositories.
126
125
  const conectores = await prepararConectores(repo, previous?.conectores, o, yes);
127
126
  // 4. Review the proposal.
@@ -158,6 +157,8 @@ export async function init(o) {
158
157
  stack,
159
158
  ...(conectores?.conectores ?? previous?.conectores ? { conectores: conectores?.conectores ?? previous?.conectores } : {}),
160
159
  ...(previous?.general ? { general: previous.general } : {}),
160
+ // how the flow works (shared): kept as is, or the defaults written out so the team sees what can be set
161
+ flujo: previous?.flujo ?? { soporte: false, aprobadores: { analisis: [], qa: [], codigo: [], cliente: [], ejecucion: [] }, code_review: { gate: "github", revisores: [] }, rama_desarrollo: "desarrollo" },
161
162
  entornos: pre ? pre.entornos : entornosDesdeStack(stack),
162
163
  };
163
164
  const vars = { RESUMEN_STACK: resumenStack(stack), BASE_BRANCH: config.proyecto.rama_base, AGENT_CMD: comandoAgente ? `${comandoAgente}` : "claude -p --permission-mode acceptEdits" };
@@ -179,31 +180,48 @@ export async function init(o) {
179
180
  }
180
181
  escribirConfig(repo, config);
181
182
  const res = await aplicar(repo, plan, (c) => resolverConflicto(c, yes));
182
- if (datosEnv) {
183
- escribirEnv(repo, readFileSync(join(repo, "orqen", ".env.example"), "utf8"), datosEnv);
184
- p.log.success(`${RUTA_ENV} created ${gris("(ignored by Git)")}`);
185
- }
186
183
  const env = providerEnv(repo);
187
184
  const faltanEnv = config.conectores ? missingSecrets(config.conectores, env) : [];
188
185
  const lado = res.filter((r) => r.accion === "guardado-al-lado");
189
- p.log.success(`${ARCHIVO_CONFIG} and kit v${VERSION_CLI} installed`);
186
+ p.log.success(`${ARCHIVO_CONFIG}, ${ARCHIVO_ENTORNO} and kit v${VERSION_CLI} installed`);
190
187
  for (const r of lado)
191
188
  p.log.warn(`${r.ruta}: the proposed version is in ${r.detalle} for you to merge`);
189
+ const commiteado = await commitInstall(repo, o.commit, yes);
192
190
  const mk = marketplace(existsSync(join(repo, MARKETPLACE)) ? readFileSync(join(repo, MARKETPLACE), "utf8") : undefined).nombre;
193
191
  const pasos = [
194
192
  ...(!config.conectores ? [`Connect where the tickets live: ${pc.cyan("orqen connectors setup")} (Jira, GitHub or Asana).`] : []),
195
193
  ...(faltanEnv.length ? [`Complete the provider accounts with ${pc.cyan("orqen connectors setup")}: missing ${faltanEnv.join(", ")}. These accounts are shared across your repositories.`] : []),
196
- `Review ${pc.cyan(ARCHIVO_CONFIG)}, then try: ${pc.cyan("orqen env up")} · ${pc.cyan("orqen env test")} · ${pc.cyan("orqen env down")}`,
194
+ `Review ${pc.cyan(ARCHIVO_CONFIG)} and ${pc.cyan(ARCHIVO_ENTORNO)}, then try: ${pc.cyan("orqen env up")} · ${pc.cyan("orqen env test")} · ${pc.cyan("orqen env down")}`,
197
195
  `Open Claude Code in this folder (restart it if it was open) and accept ${pc.bold("Trust this folder")}: ` +
198
196
  `the commands appear as ${pc.cyan("/orqen:tutorial")} (start here if you are new), ${pc.cyan("/orqen:support")}, ${pc.cyan("/orqen:analyze")}, ${pc.cyan("/orqen:list")}, ${pc.cyan("/orqen:implement")}, ${pc.cyan("/orqen:pr")}, ${pc.cyan("/orqen:review")} (QA), ${pc.cyan("/orqen:approve")} ` +
199
197
  gris(`(type /orqen: to list them; check with /plugin → orqen@${mk})`),
200
- `Commit the changes (orqen/, .claude/, .claude-plugin/, AGENTS.md, CLAUDE.md, openspec/) so the team gets the same commands.`,
198
+ ...(!commiteado ? [`Commit the changes (orqen/, .claude/, .claude-plugin/, AGENTS.md, CLAUDE.md, openspec/) so the team gets the same commands: ${pc.cyan('git add -A && git commit -m "Install orqen"')}`] : []),
201
199
  ];
202
200
  if (o.sinLogo)
203
201
  return; // `orqen bootstrap` shows its own next steps
204
202
  p.note(pasos.map((x, i) => `${pc.bold(`${i + 1}.`)} ${x}`).join("\n"), "Next steps");
205
203
  p.outro(`${magenta("//")} ${pc.bold("From request to production.")}`);
206
204
  }
205
+ const INSTALLED = ["orqen", ".claude", ".claude-plugin", "AGENTS.md", "CLAUDE.md", ".gitignore", "openspec"];
206
+ /**
207
+ * Commits what init wrote (the team gets the same commands, and the first `orqen take` can switch branches). Only those
208
+ * paths: nothing else the person had changed or staged. Asks when interactive; --yes only does it with --commit.
209
+ */
210
+ async function commitInstall(repo, commit, yes) {
211
+ if (!commit && (yes || !(await confirmar("Commit the files orqen just wrote (orqen/, .claude/, AGENTS.md…)?", true, false))))
212
+ return false;
213
+ const paths = INSTALLED.filter((x) => existsSync(join(repo, x)));
214
+ try {
215
+ execFileSync("git", ["add", "--", ...paths], { cwd: repo, stdio: "pipe" });
216
+ execFileSync("git", ["commit", "-q", "-m", "Install orqen", "--", ...paths], { cwd: repo, stdio: "pipe" });
217
+ p.log.success("Committed: Install orqen");
218
+ return true;
219
+ }
220
+ catch (e) {
221
+ p.log.warn(`Could not commit (${(e.stderr?.toString() || e.message).trim().split("\n")[0]}): commit the files by hand.`);
222
+ return false;
223
+ }
224
+ }
207
225
  /** Connectors step: from --connectors (JSON), interactively, or kept as they were (--yes, --no-connectors). */
208
226
  async function prepararConectores(repo, prev, o, yes) {
209
227
  if (o.sinConectores)
@@ -256,7 +274,7 @@ async function revisarStack(stack, yes, hayAgente) {
256
274
  const comps = await elegirVarios("Components to include", stack.componentes.map((c) => ({ value: c.nombre, label: `${c.nombre} ${gris(`(${c.ruta})`)}`, hint: [c.tipo, c.framework ?? c.lenguaje].join(" · ") })), stack.componentes.map((c) => c.nombre), false);
257
275
  const tests = { ...stack.tests };
258
276
  for (const k of ["unitarios", "integracion", "e2e", "visual"]) {
259
- tests[k] = (await texto(`Test command for ${k} (leave blank to skip)`, tests[k] ?? "", false)) || undefined;
277
+ tests[k] = (await texto(`Test command for ${{ unitarios: "unit", integracion: "integration" }[k] ?? k} tests (leave blank to skip)`, tests[k] ?? "", false)) || undefined;
260
278
  }
261
279
  const migraciones = (await texto("Migration command (leave blank to skip)", stack.migraciones ?? "", false)) || undefined;
262
280
  const seed = (await texto("Seed command for test data (leave blank to skip)", stack.seed ?? "", false)) || undefined;
@@ -273,7 +291,7 @@ async function revisarProcesos(e, yes) {
273
291
  const linea = (x) => `${x.nombre}: ${x.comando}${x.ruta !== "." ? gris(` (in ${x.ruta})`) : ""}${x.puerto ? gris(` → :${x.puerto}`) : ""}${x.cuando === "e2e" ? gris(" [e2e only]") : ""}`;
274
292
  p.note(e.procesos.length
275
293
  ? e.procesos.map(linea).join("\n") + "\n\n" + gris("orqen starts them when needed (orqen take / orqen env up) and stops them afterwards.")
276
- : gris("Could not find how to start the project (no dev/start script). You can add it under entornos.procesos in orqen/config.yaml."), "How the project starts");
294
+ : gris("Could not find how to start the project (no dev/start script). You can add it under processes in orqen/environment.yaml."), "How the project starts");
277
295
  if (yes || !e.procesos.length)
278
296
  return e;
279
297
  if (!(await confirmar("Do you want to change any command?", false, false)))
@@ -344,7 +362,8 @@ async function prepararOpenSpec(repo, agentes, herramientasPedidas, yes) {
344
362
  function resumenPlan(plan, config) {
345
363
  const icono = { crear: pc.green("+"), actualizar: pc.yellow("~"), igual: gris("="), conflicto: pc.red("!") };
346
364
  const filas = [
347
- `${pc.green("+")} ${ARCHIVO_CONFIG}`,
365
+ `${pc.green("+")} ${ARCHIVO_CONFIG} ${gris("(the flow: project, connectors, workflow)")}`,
366
+ `${pc.green("+")} ${ARCHIVO_ENTORNO} ${gris("(stack, how each part starts, tests)")}`,
348
367
  ...plan.filter((c) => c.accion !== "igual" && !c.ruta.startsWith("orqen/stages/") && !c.ruta.startsWith("orqen/plugin/"))
349
368
  .map((c) => `${icono[c.accion]} ${c.ruta}${c.accion === "conflicto" ? pc.red(" (local edits require review)") : ""}`),
350
369
  ];
@@ -24,7 +24,7 @@ export const SWARM_HELP = ` swarm "<task>" Split a task into small sub
24
24
  --small "<cmd>" Small model for subtasks (default: ${SWARM_DEFAULTS.small})
25
25
  --large "<cmd>" Larger model after the small one fails (default: ${SWARM_DEFAULTS.large})
26
26
  --small-attempts <n> --large-attempts <n> Attempts per tier (default 2 and 2)
27
- --test "<cmd>" Final verification when the plan has none (default: entornos.tests.unitarios)
27
+ --test "<cmd>" Final verification when the plan has none (default: tests.unit of orqen/environment.yaml)
28
28
  --setup "<cmd>" Run in each worktree before the agent (default: entornos.preparar); --no-setup
29
29
  --apply Integrate a successful result into the starting branch (fast-forward only)
30
30
  --plan <file.json> Use an existing plan instead of planning · --plan-only Only write the plan
@@ -57,7 +57,7 @@ export function datosDelRepo(repo, plataforma = process.platform) {
57
57
  ramaDevel: env.DEVEL_BRANCH || "desarrollo",
58
58
  windows: plataforma === "win32",
59
59
  db: existsSync(join(repo, "orqen", "tools", "db.mjs")),
60
- conectado: c.requests.kind === "jira" ? !!(real(c.requests.url) && real(c.requests.token)) : c.requests.kind === "github" ? !!c.requests.repo : !!(c.requests.project && c.requests.token),
60
+ conectado: c.requests.kind === "jira" ? !!(real(c.requests.url) && real(c.requests.token)) : c.requests.kind === "github" ? !!c.requests.repo : c.requests.kind === "local" ? true : !!(c.requests.project && c.requests.token),
61
61
  };
62
62
  }
63
63
  export function buscarPaso(pasos, valor) {
@@ -1,18 +1,112 @@
1
- /** Update the CLI, compatible OpenSpec installation, and managed kit files. */
2
- import { resolve } from "node:path";
1
+ /** Update the CLI or desktop app, and refresh OpenSpec and managed kit files in an orqen project. */
2
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
3
+ import { join, resolve } from "node:path";
3
4
  import semver from "semver";
4
- import { actualizarVersiones, escribirConfig, leerConfig } from "../lib/config.js";
5
+ import { actualizarVersiones, ARCHIVO_CONFIG, ARCHIVO_ENTORNO, configVieja, escribirConfig, existeConfig, leerConfig } from "../lib/config.js";
5
6
  import { leerEnv } from "../lib/env.js";
6
7
  import { legacyToYaml, legacyVarsIn } from "../connectors/legacy.js";
7
8
  import { aplicar, leerManifest, planificar } from "../lib/kit.js";
8
9
  import { actualizarArchivosOpenSpec, estadoOpenSpec, instalarOpenSpec, RANGO_OPENSPEC, ultimaVersionOpenSpec, } from "../lib/openspec.js";
9
- import { ejecutar } from "../lib/proc.js";
10
- import { comandoActualizarCli, ultimaVersionCli, VERSION_CLI } from "../lib/system.js";
10
+ import { ejecutar, ejecutarAsync } from "../lib/proc.js";
11
+ import { gestorCli, PAQUETE_CLI, ultimaVersionPaquete, VERSION_CLI } from "../lib/system.js";
11
12
  import { resumenStack } from "../lib/stack.js";
12
13
  import { mostrarLogo } from "../ui/logo.js";
13
14
  import { azul, confirmar, gris, interactivo, magenta, p, pc } from "../ui/console.js";
14
15
  import { resolverConflicto } from "./init.js";
16
+ import { moveWorkToWorqs } from "../lib/worqs.js";
17
+ const PAQUETE_DESKTOP = "@telpin-sistemas/orqen-desktop";
18
+ const DESKTOP_REPO = "sistemas-telpin/orqen-gui";
19
+ function paqueteGlobal(gestor, paquete) {
20
+ const r = ejecutar(gestor, ["root", "-g"], { timeoutMs: 20_000 });
21
+ if (r.codigo !== 0 || !r.stdout.trim())
22
+ throw new Error(r.stderr.trim() || r.error?.message || `Could not locate global packages for ${gestor}.`);
23
+ return join(r.stdout.trim(), paquete);
24
+ }
25
+ async function actualizarPaquete(gestor, paquete, actual, yes, objetivo) {
26
+ const ultima = objetivo ?? ultimaVersionPaquete(gestor, paquete);
27
+ if (!ultima)
28
+ return { status: "unavailable", version: actual };
29
+ if (!semver.gt(ultima, actual))
30
+ return { status: "current", version: actual };
31
+ if (!await confirmar(`Update ${paquete} from ${actual} to ${ultima}?`, true, yes))
32
+ return { status: "skipped", version: actual };
33
+ const r = await ejecutarAsync(gestor, [gestor === "pnpm" ? "add" : "install", "-g", `${paquete}@${ultima}`], { timeoutMs: 10 * 60_000 });
34
+ if (r.codigo !== 0)
35
+ throw new Error(`Update failed for ${paquete}: ${(r.stderr || r.stdout || r.error?.message || `exit code ${r.codigo}`).trim().slice(-1500)}`);
36
+ return { status: "installed", version: ultima };
37
+ }
38
+ function versionDesktop() {
39
+ const manifest = join(paqueteGlobal("npm", PAQUETE_DESKTOP), "package.json");
40
+ if (!existsSync(manifest))
41
+ throw new Error("Install orqen Desktop globally with npm before updating it.");
42
+ const launcher = process.env.ORQEN_DESKTOP_NPM_MANIFEST;
43
+ if (launcher && realpathSync(launcher) !== realpathSync(manifest)) {
44
+ throw new Error("The running desktop app is outside the active global npm installation.");
45
+ }
46
+ const { version } = JSON.parse(readFileSync(manifest, "utf8"));
47
+ if (typeof version !== "string" || !semver.valid(version))
48
+ throw new Error("Invalid installed desktop version.");
49
+ return version;
50
+ }
51
+ async function githubDesktop(path) {
52
+ const api = `repos/${DESKTOP_REPO}/${path}`;
53
+ try {
54
+ const response = await fetch(`https://api.github.com/${api}`, {
55
+ headers: { Accept: "application/vnd.github+json" },
56
+ signal: AbortSignal.timeout(5_000),
57
+ });
58
+ if (response.ok)
59
+ return await response.json();
60
+ }
61
+ catch { /* Try the locally authenticated GitHub CLI. */ }
62
+ const authenticated = await ejecutarAsync("gh", ["api", api], {
63
+ timeoutMs: 5_000, env: { ...process.env, GH_PROMPT_DISABLED: "1" },
64
+ });
65
+ if (authenticated.codigo !== 0)
66
+ throw new Error("Desktop release metadata is unavailable.");
67
+ return JSON.parse(authenticated.stdout);
68
+ }
69
+ /** Read-only discovery for the desktop app. Installation is a separate, pinned action. */
70
+ export async function desktopRelease(installed) {
71
+ if (!semver.valid(installed))
72
+ throw new Error("Invalid running desktop version.");
73
+ const actual = versionDesktop();
74
+ if (semver.gt(actual, installed)) {
75
+ return console.log(JSON.stringify({ status: "installed", version: actual }));
76
+ }
77
+ const version = ultimaVersionPaquete("npm", PAQUETE_DESKTOP);
78
+ if (!version)
79
+ throw new Error("Could not check npm for orqen Desktop updates.");
80
+ if (!semver.gt(version, installed))
81
+ return console.log(JSON.stringify({ status: "current", version: installed }));
82
+ const range = `v${installed}...v${version}`;
83
+ const [release, comparison] = await Promise.allSettled([
84
+ githubDesktop(`releases/tags/v${version}`), githubDesktop(`compare/${range}?per_page=100`),
85
+ ]);
86
+ const notes = release.status === "fulfilled" && typeof release.value.body === "string" ? release.value.body.trim() : "";
87
+ const commits = comparison.status === "fulfilled" && Array.isArray(comparison.value.commits)
88
+ ? comparison.value.commits.map((c) => c.commit?.message?.split("\n")[0]).filter(Boolean)
89
+ : [];
90
+ console.log(JSON.stringify({
91
+ status: "available", version, notes, commits, url: `https://github.com/${DESKTOP_REPO}/compare/${range}`,
92
+ }));
93
+ }
15
94
  export async function update(o) {
95
+ if (o.target !== undefined && (!o.desktop || !semver.valid(o.target)))
96
+ throw new Error("--target requires --desktop and a valid version.");
97
+ if (o.desktop) {
98
+ const actual = versionDesktop();
99
+ const result = await actualizarPaquete("npm", PAQUETE_DESKTOP, actual, !!o.yes || !interactivo(), o.target);
100
+ if (result.status === "unavailable")
101
+ throw new Error("Could not check npm for orqen Desktop updates.");
102
+ if (o.json)
103
+ console.log(JSON.stringify(result));
104
+ else if (result.status === "installed")
105
+ console.log(`orqen Desktop ${result.version} installed. Restart the app to use it.`);
106
+ else if (result.status === "current")
107
+ console.log(`orqen Desktop ${result.version} is up to date.`);
108
+ return;
109
+ }
16
110
  const repo = resolve(o.dir ?? process.cwd());
17
111
  let yes = !!o.yes;
18
112
  await mostrarLogo(!o.sinAnimacion && !o.yes);
@@ -21,41 +115,40 @@ export async function update(o) {
21
115
  p.log.warn("Non-interactive terminal. Using defaults as with --yes.");
22
116
  yes = true;
23
117
  }
24
- let config;
25
- try {
26
- config = leerConfig(repo);
27
- }
28
- catch (e) {
29
- p.cancel(e.message);
30
- process.exitCode = 1;
31
- return;
32
- }
33
- const s = p.spinner();
34
- // 1. CLI
118
+ const config = !o.cliOnly && (o.dir !== undefined || o.sinCli || existeConfig(repo)) ? leerConfig(repo) : undefined;
35
119
  if (!o.sinCli) {
36
- s.start("Checking for orqen updates…");
37
- const ultima = ultimaVersionCli();
38
- if (!ultima)
39
- s.stop(gris("Could not reach npm. Using the installed version."));
40
- else if (semver.gt(ultima, VERSION_CLI)) {
41
- s.stop(`orqen update available: ${pc.bold(VERSION_CLI)} → ${pc.green(ultima)}`);
42
- const [cmd, args] = comandoActualizarCli();
43
- if (await confirmar(`Update the CLI? (${cmd} ${args.join(" ")})`, true, yes)) {
44
- s.start(`Installing orqen@${ultima}…`);
45
- const r = ejecutar(cmd, args, { timeoutMs: 10 * 60_000 });
46
- if (r.codigo !== 0) {
47
- s.error(`Update failed:\n${(r.stderr || r.stdout).trim().slice(-1500)}`);
48
- process.exitCode = 1;
49
- return;
50
- }
51
- s.stop(`orqen ${ultima} installed`);
52
- p.outro(`Run ${pc.cyan("orqen update")} again to update the kit with version ${ultima}.`);
120
+ const gestor = gestorCli();
121
+ p.log.step("Checking for orqen updates…");
122
+ const result = await actualizarPaquete(gestor, PAQUETE_CLI, VERSION_CLI, yes);
123
+ if (result.status === "unavailable") {
124
+ if (!config)
125
+ throw new Error("Could not check npm for orqen updates.");
126
+ p.log.warn("Could not reach npm. Using the installed CLI to update this project.");
127
+ }
128
+ if (result.status === "current")
129
+ p.log.success(`orqen ${result.version} is up to date`);
130
+ if (result.status === "installed") {
131
+ p.log.success(`orqen ${result.version} installed`);
132
+ if (config) {
133
+ const cli = join(paqueteGlobal(gestor, PAQUETE_CLI), "dist", "index.js");
134
+ const args = [cli, "update", "--dir", repo, "--no-cli", "--no-animation"];
135
+ if (yes)
136
+ args.push("--yes");
137
+ if (o.sinOpenspec)
138
+ args.push("--no-openspec");
139
+ if (o.sinKit)
140
+ args.push("--no-kit");
141
+ const r = ejecutar(process.execPath, args, { heredar: true });
142
+ if (r.error)
143
+ throw r.error;
144
+ process.exitCode = r.codigo;
53
145
  return;
54
146
  }
55
147
  }
56
- else
57
- s.stop(`orqen ${VERSION_CLI} is up to date`);
58
148
  }
149
+ if (!config)
150
+ return;
151
+ const s = p.spinner();
59
152
  // 2. OpenSpec
60
153
  if (!o.sinOpenspec) {
61
154
  s.start("Checking OpenSpec…");
@@ -82,10 +175,22 @@ export async function update(o) {
82
175
  }
83
176
  catch (e) {
84
177
  s.error(e.message);
178
+ process.exitCode = 1;
85
179
  }
86
180
  }
87
181
  }
88
182
  }
183
+ // 2b. The worqs (the record of each request): orqen/work/ of earlier versions → orqen/worqs/
184
+ if (existsSync(join(repo, "orqen", "work")) && !existsSync(join(repo, "orqen", "worqs"))) {
185
+ p.log.info("The worqs (orqen's unit of work: one folder per request) are now in orqen/worqs/; this repository still has them in orqen/work/.");
186
+ if (await confirmar("Move orqen/work/ to orqen/worqs/ (git mv)? Branches of requests in progress keep their old path and are still read", true, yes)) {
187
+ const m = moveWorkToWorqs(repo);
188
+ if (m.moved)
189
+ p.log.success(`${m.detail} ${gris("(commit the move with the rest of the update)")}`);
190
+ else
191
+ p.log.warn(m.detail);
192
+ }
193
+ }
89
194
  // 3. Kit
90
195
  if (!o.sinKit) {
91
196
  const manifest = leerManifest(repo);
@@ -116,11 +221,19 @@ export async function update(o) {
116
221
  if (!config.conectores && viejas.length) {
117
222
  const bloque = legacyToYaml(env);
118
223
  p.log.info(`orqen/.env uses variables of an earlier version: ${viejas.join(", ")}`);
119
- if (await confirmar("Move where the tickets live to orqen/config.yaml (conectores)? orqen/.env is not modified", true, yes)) {
224
+ if (await confirmar("Move where the tickets live to orqen/config.yaml (connectors)? orqen/.env is not modified", true, yes)) {
120
225
  const actual = leerConfig(repo);
121
226
  actual.conectores = bloque;
122
227
  escribirConfig(repo, actual);
123
- p.log.success(`conectores written in orqen/config.yaml ${gris("(you can delete REC_JQL and SIS_* from orqen/.env)")}`);
228
+ p.log.success(`connectors written in orqen/config.yaml ${gris("(you can delete REC_JQL and SIS_* from orqen/.env)")}`);
229
+ }
230
+ }
231
+ // 5. Format of earlier versions: Spanish keys and the stack/environment inside config.yaml
232
+ if (configVieja(repo)) {
233
+ p.log.info(`${ARCHIVO_CONFIG} uses the format of an earlier version (Spanish keys, stack and environment in the same file).`);
234
+ if (await confirmar(`Rewrite it with English keys and move the stack and environment to ${ARCHIVO_ENTORNO}? (comments in the file are not kept)`, true, yes)) {
235
+ escribirConfig(repo, leerConfig(repo));
236
+ p.log.success(`${ARCHIVO_CONFIG} rewritten · ${ARCHIVO_ENTORNO} created`);
124
237
  }
125
238
  }
126
239
  actualizarVersiones(repo, { cli: VERSION_CLI });