@telpin-sistemas/orqen 0.1.8 → 0.1.11

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/README.md CHANGED
@@ -17,27 +17,11 @@ orqen init # Run from the repository you want to initialize
17
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
- `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`.
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.
21
21
 
22
22
 
23
23
  Other options include `--agent "<command>"`, `--tools claude,codex`, `--no-openspec`, `--no-connectors` (skip the step), and `--connectors <file|->` (connectors as JSON, same format as `orqen connectors set`, for non-interactive runs; `--yes` alone keeps the current ones). Non-interactive runs use the defaults. If a managed file conflicts, `--yes` writes the proposed version alongside the original.
24
24
 
25
- ## Create a new project
26
-
27
- ```sh
28
- orqen bootstrap "Payments Platform" [--tools-repo @company/tools] [--stack <id>] [--dir ./payments] [--yes]
29
- orqen bootstrap --list
30
- ```
31
-
32
- Asks the name, folder and stack; checks the stack requirements and asks its parameters (ports, Java package); creates the
33
- folder and Git repository; generates the code (official generators plus the stack skeleton); copies the environment scripts
34
- to `orqen/tools/` (e.g. `orqen/tools/db.mjs`, the database in Docker); runs `orqen init` with the stack and environments already known;
35
- and offers the initial commit.
36
-
37
- On first use, `bootstrap` asks for your GitHub stack repository (for example `@company/stacks`); its name can be anything. Git clones it into `cli/tools/` beside this CLI installation using your own HTTPS credential helper or SSH key. You need access to that repository. The clone is reused, ignored by Git and excluded from the npm package; no catalog is bundled. Each stack has `<id>/tool.yaml` and its scaffold, with shared scripts in `_shared/`.
38
-
39
- For non-interactive first use of `bootstrap`, pass `--tools-repo @company/tools` or set `ORQEN_TOOLS_REPO`. HTTPS and SSH GitHub URLs are also accepted. To refresh it, use `git -C tools pull --ff-only` from the CLI installation directory. To select a different repository, move the existing clone aside first.
40
-
41
25
  ## Update an installation
42
26
 
43
27
  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.
@@ -37,17 +37,16 @@ const HERRAMIENTAS_OPENSPEC = [
37
37
  export async function init(o) {
38
38
  const repo = resolve(o.dir ?? process.cwd());
39
39
  let yes = !!o.yes;
40
- if (!o.sinLogo)
41
- await mostrarLogo({
42
- animar: !o.sinAnimacion && !o.yes, esperarTecla: true,
43
- bienvenida: [
44
- "Initialization will:",
45
- " • Detect the stack and propose environments with your AI agent",
46
- " • Install and configure OpenSpec",
47
- " • Connect where the requests and issues live (Jira, GitHub or Asana)",
48
- " • Prepare the repository for agents to work independently",
49
- ],
50
- });
40
+ await mostrarLogo({
41
+ animar: !o.sinAnimacion && !o.yes, esperarTecla: true,
42
+ bienvenida: [
43
+ "Initialization will:",
44
+ " • Detect the stack and propose environments with your AI agent",
45
+ " • Install and configure OpenSpec",
46
+ " • Connect where the requests and issues live (Jira, GitHub or Asana)",
47
+ " • Prepare the repository for agents to work independently",
48
+ ],
49
+ });
51
50
  p.intro(`${azul("orqen")} ${magenta("init")} ${gris(`v${VERSION_CLI} · ${repo}`)}`);
52
51
  if (!yes && !interactivo()) {
53
52
  p.log.warn("Non-interactive terminal. Using defaults as with --yes.");
@@ -197,8 +196,6 @@ export async function init(o) {
197
196
  gris(`(type /orqen: to list them; check with /plugin → orqen@${mk})`),
198
197
  ...(!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"')}`] : []),
199
198
  ];
200
- if (o.sinLogo)
201
- return; // `orqen bootstrap` shows its own next steps
202
199
  p.note(pasos.map((x, i) => `${pc.bold(`${i + 1}.`)} ${x}`).join("\n"), "Next steps");
203
200
  p.outro(`${magenta("//")} ${pc.bold("From request to production.")}`);
204
201
  }
@@ -15,14 +15,14 @@ import { azul, confirmar, gris, interactivo, magenta, p, pc } from "../ui/consol
15
15
  import { resolverConflicto } from "./init.js";
16
16
  import { moveWorkToWorqs } from "../lib/worqs.js";
17
17
  const PAQUETES_DESKTOP = ["@telpin-sistemas/orqen-studio", "@telpin-sistemas/orqen-desktop"];
18
- const DESKTOP_REPO = "sistemas-telpin/orqen-gui";
18
+ const DESKTOP_REPO = "sistemas-telpin/orqen-studio";
19
19
  function paqueteGlobal(gestor, paquete) {
20
20
  const r = ejecutar(gestor, ["root", "-g"], { timeoutMs: 20_000 });
21
21
  if (r.codigo !== 0 || !r.stdout.trim())
22
22
  throw new Error(r.stderr.trim() || r.error?.message || `Could not locate global packages for ${gestor}.`);
23
23
  return join(r.stdout.trim(), paquete);
24
24
  }
25
- async function actualizarPaquete(gestor, paquete, actual, yes, objetivo) {
25
+ async function actualizarPaquete(gestor, paquete, actual, yes, objetivo, desktop = false) {
26
26
  const ultima = objetivo ?? ultimaVersionPaquete(gestor, paquete);
27
27
  if (!ultima)
28
28
  return { status: "unavailable", version: actual };
@@ -30,7 +30,15 @@ async function actualizarPaquete(gestor, paquete, actual, yes, objetivo) {
30
30
  return { status: "current", version: actual };
31
31
  if (!await confirmar(`Update ${paquete} from ${actual} to ${ultima}?`, true, yes))
32
32
  return { status: "skipped", version: actual };
33
- const r = await ejecutarAsync(gestor, [gestor === "pnpm" ? "add" : "install", "-g", `${paquete}@${ultima}`], { timeoutMs: 10 * 60_000 });
33
+ const args = [gestor === "pnpm" ? "add" : "install", "-g", `${paquete}@${ultima}`];
34
+ if (desktop) {
35
+ const binario = `@telpin-sistemas/orqen-desktop-${process.platform}-${process.arch}@${ultima}`;
36
+ const descarga = await ejecutarAsync(gestor, ["cache", "add", binario, "--prefer-online", "--fetch-retries=0"], { timeoutMs: 60_000 });
37
+ if (descarga.codigo !== 0)
38
+ throw new Error("The platform build is still unavailable on npm. Your current installation is intact. Try again in a few minutes.");
39
+ args.push("--include=optional", binario);
40
+ }
41
+ const r = await ejecutarAsync(gestor, args, { timeoutMs: 10 * 60_000 });
34
42
  if (r.codigo !== 0)
35
43
  throw new Error(`Update failed for ${paquete}: ${(r.stderr || r.stdout || r.error?.message || `exit code ${r.codigo}`).trim().slice(-1500)}`);
36
44
  return { status: "installed", version: ultima };
@@ -100,7 +108,7 @@ export async function update(o) {
100
108
  throw new Error("--target requires --desktop and a valid version.");
101
109
  if (o.desktop) {
102
110
  const { paquete, version: actual } = instalacionDesktop();
103
- const result = await actualizarPaquete("npm", paquete, actual, !!o.yes || !interactivo(), o.target);
111
+ const result = await actualizarPaquete("npm", paquete, actual, !!o.yes || !interactivo(), o.target, true);
104
112
  if (result.status === "unavailable")
105
113
  throw new Error("Could not check npm for orqen Desktop updates.");
106
114
  if (o.json)
@@ -16,7 +16,7 @@ import { OpenSpecCli } from "../workflow/openspec.js";
16
16
  import { Process } from "../workflow/process.js";
17
17
  import { Store } from "../workflow/store.js";
18
18
  import { GitWorkspace } from "../workflow/workspace.js";
19
- export const WORKFLOW_COMMANDS = ["list", "qa", "approve", "merged", "cancel", "pending", "support", "analyze", "ask", "conversation", "lane", "take", "complete", "pr", "review", "code-review", "schema", "block", "release", "search", "status", "worqs", "worq", "cycle", "connectors", "comments", "comment"];
19
+ export const WORKFLOW_COMMANDS = ["list", "qa", "approve", "merged", "cancel", "new_worq", "pending", "support", "analyze", "ask", "conversation", "lane", "take", "complete", "pr", "review", "code-review", "schema", "block", "release", "search", "status", "worqs", "worq", "cycle", "connectors", "comments", "comment"];
20
20
  /** What people run: the 9 steps (as /orqen:* commands in their agent) and the CLI commands meant for a person. */
21
21
  export const WORKFLOW_HELP = `The 9 steps (run the /orqen:* commands in your agent: it calls the CLI for you):
22
22
  1 /orqen:list requests orqen list requests [--json] [--all] Everyone's work list, by role (takes nothing)
@@ -36,6 +36,7 @@ Request commands for people:
36
36
  worqs [--all] [--json] The worqs on this machine: orqen's unit of work, one per request (request + issue + branch + PR + record)
37
37
  worq <KEY> [--json] One worq: state, request, issue, branch, PR and the files of its record in orqen/worqs/<KEY>/
38
38
  merged <KEY> [--person N] Confirm the hand merge of an approved PR when orqen cannot read it from GitHub
39
+ new_worq "<title>" <brief.json|-> Worq with no request: creates its issue in the connector, skips support and analysis, born in DEVELOPMENT
39
40
  cancel <KEY> --reason T Close the request without delivering it: closes the PR unmerged, comments both tickets (CANCELLED)
40
41
  release <KEY> Free a request held by an agent that is no longer working on it
41
42
  comments <KEY> [--json] Read the request and its conversation with the client
@@ -44,7 +45,7 @@ Request commands for people:
44
45
  cycle [--loop] Unattended mode (cron/CI/server): agent stages only, never support or analysis
45
46
 
46
47
  Agent-only commands (the /orqen:* commands run them) and JSON for tools: orqen help internal`;
47
- /** What only the agent runs (inside the /orqen:* commands) and the JSON commands for tools such as orqen-gui. */
48
+ /** What only the agent runs (inside the /orqen:* commands) and the JSON commands for tools such as orqen-studio. */
48
49
  export const WORKFLOW_INTERNAL_HELP = `Agent-only commands (the /orqen:* commands run them; a person does not need them):
49
50
  support <KEY> [--person NAME] 2 · Open or resume first-line support and print the context
50
51
  analyze <KEY> [--analyst NAME] 3 · Open or resume the analysis and print the context
@@ -61,12 +62,11 @@ export const WORKFLOW_INTERNAL_HELP = `Agent-only commands (the /orqen:* command
61
62
 
62
63
  Older names (still work, with a notice): pending → list requests · qa → review
63
64
 
64
- JSON for tools (orqen-gui):
65
+ JSON for tools (orqen-studio):
65
66
  status [KEY] --json · list requests|issues|prs --json · usage --json · tutorial --step <n> --json
66
67
  spec [KEY|change] --json [--dir <worktree>] the spec in the neutral model of src/sdd (any SDD tool)
67
68
  connectors get|check <json>|set <json>|general-get|general-set [--json]
68
- connectors github-choices <json|-> <requests|issues> <repositories|projects|statuses>
69
- bootstrap --list --json · bootstrap --describe <stack> --json`;
69
+ connectors github-choices <json|-> <requests|issues> <repositories|projects|statuses>`;
70
70
  /** The person at this machine: Git's user.name for this repository, otherwise the system user. */
71
71
  export function quienSoy(repo) {
72
72
  try {
@@ -278,6 +278,23 @@ export async function runWorkflow(cmd, rest) {
278
278
  }
279
279
  return;
280
280
  }
281
+ case "new_worq": {
282
+ try {
283
+ const title = rest[0] ?? "";
284
+ const src = rest[1];
285
+ if (!title || !src)
286
+ throw new Error('Usage: orqen new_worq "<title>" <brief.json|-> [--person NAME] (brief: {"description", "acceptance_criteria": [...], "plan": [...], "estimated_hours"})');
287
+ const raw = JSON.parse(src === "-" ? readFileSync(0, "utf8") : readFileSync(src, "utf8"));
288
+ const r = await flow.newWorq(title, raw, me || agent);
289
+ console.log(`✔ ${r.key} created in ${r.state}: issue ${r.url} (no client request) · worq: ${r.dir}/`);
290
+ console.log(` Next: /orqen:implement ${r.key}`);
291
+ }
292
+ catch (e) {
293
+ console.error(`✘ ${e.message}`);
294
+ process.exitCode = 1;
295
+ }
296
+ return;
297
+ }
281
298
  case "cancel": {
282
299
  try {
283
300
  const reason = flag("reason") ?? "";
@@ -583,7 +600,7 @@ export async function runWorkflow(cmd, rest) {
583
600
  return;
584
601
  }
585
602
  case "connectors": {
586
- // JSON for tools such as orqen-gui: {"conectores": {...}, "env": {"JIRA_TOKEN": "..."}} on stdin or in a file
603
+ // JSON for tools such as orqen-studio: {"conectores": {...}, "env": {"JIRA_TOKEN": "..."}} on stdin or in a file
587
604
  const draftInput = () => JSON.parse(!rest[1] || rest[1] === "-" ? readFileSync(0, "utf8") : readFileSync(rest[1], "utf8"));
588
605
  if (rest[0] === "general-get" || rest[0] === "general-set") {
589
606
  const { leerConfig, escribirConfig } = await import("../lib/config.js");
@@ -596,7 +613,7 @@ export async function runWorkflow(cmd, rest) {
596
613
  escribirConfig(cfg.repoPath, updated);
597
614
  return console.log(JSON.stringify({ general: updated.general, hasHistory }));
598
615
  }
599
- // a connectors editor (orqen-gui): current values (tokens masked) and a check of a draft before saving it
616
+ // a connectors editor (orqen-studio): current values (tokens masked) and a check of a draft before saving it
600
617
  if (rest[0] === "get") {
601
618
  const { connectorsView } = await import("../lib/connectors-edit.js");
602
619
  const { existeConfig, leerConfig } = await import("../lib/config.js");
@@ -6,7 +6,7 @@
6
6
  * { key, title, description, reportedBy, status, labels, created, comments: [{id, author, authorName, body, created}], clientSeen }
7
7
  */
8
8
  import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
9
- import { join } from "node:path";
9
+ import { dirname, join } from "node:path";
10
10
  import { pathToFileURL } from "node:url";
11
11
  import { BOT_MARK, LEGACY_STATE_LABELS, STATE_LABEL } from "./types.js";
12
12
  /** States of a local ticket that are no longer pending. */
@@ -28,8 +28,8 @@ export class LocalTracker {
28
28
  }
29
29
  /** Atomic write: the app and the CLI read the same files every few seconds. */
30
30
  write(t) {
31
- mkdirSync(this.s.dir, { recursive: true });
32
31
  const f = this.file(t.key);
32
+ mkdirSync(dirname(f), { recursive: true });
33
33
  const tmp = `${f}.${process.pid}.tmp`;
34
34
  writeFileSync(tmp, JSON.stringify(t, null, 2) + "\n");
35
35
  renameSync(tmp, f);
package/dist/index.js CHANGED
@@ -2,7 +2,6 @@
2
2
  /** orqen command-line entry point. */
3
3
  import { parseArgs } from "node:util";
4
4
  import { entorno } from "./commands/environment.js";
5
- import { bootstrap } from "./commands/bootstrap.js";
6
5
  import { init } from "./commands/init.js";
7
6
  import { WORKFLOW_HELP, WORKFLOW_INTERNAL_HELP, WORKFLOW_COMMANDS, runWorkflow } from "./commands/workflow.js";
8
7
  import { desktopRelease, update } from "./commands/update.js";
@@ -16,7 +15,7 @@ import { SPEC_HELP, specCommand } from "./commands/spec.js";
16
15
  import { practice } from "./practice/practice.js";
17
16
  const AYUDA = `
18
17
  Usage: orqen <command> [options]
19
- orqen This help (the desktop app is a separate project: github.com/sistemas-telpin/orqen-gui)
18
+ orqen This help (the desktop app is a separate project: github.com/sistemas-telpin/orqen-studio)
20
19
 
21
20
  Commands:
22
21
  init [dir] Initialize orqen in a repository (default: current directory)
@@ -30,12 +29,6 @@ Commands:
30
29
  --no-connectors Skip the connectors step (keep the current ones; set them later with \`orqen connectors setup\`)
31
30
  --commit Commit what init wrote ("Install orqen"); interactively it asks, with --yes it only does it with this flag
32
31
  --connectors <file> Connectors as JSON ({"conectores": …, "env": …}, like \`orqen connectors set\`; "-" = stdin)
33
- bootstrap [name] Create a new project from a stack (code, tools to run it, and orqen ready)
34
- --tools-repo <repo> GitHub stack catalog (any repo name), cloned inside cli/tools
35
- --list List the stacks from your catalog
36
- --stack <id> Stack from your private catalog (orqen bootstrap --list lists them)
37
- --dir <folder> Where to create it (default: ./<name>)
38
- --params '<json>' Parameter values, e.g. '{"PORT":"8081"}' (the rest use their defaults)
39
32
  update [dir] Update the CLI and, in an orqen project, OpenSpec and the kit
40
33
  --cli-only Update only the CLI
41
34
  --desktop Update the global npm install of orqen Desktop
@@ -46,7 +39,7 @@ Commands:
46
39
  --step <n|id> Print one step and exit (--json for agents) · --list · --lang es|en
47
40
  lang Print the detected system language (es | en); ORQEN_LANG overrides it
48
41
  usage [--json] AI agents installed on this machine and their quota used
49
- practice <cmd> The interactive tutorial's practice project (orqen-gui): create | request <1|2> | client <KEY>
42
+ practice <cmd> The interactive tutorial's practice project (orqen-studio): create | request <1|2> | client <KEY>
50
43
  ${SWARM_HELP}
51
44
  ${EVAL_HELP}
52
45
  ${SPEC_HELP}
@@ -100,7 +93,6 @@ async function main() {
100
93
  "no-animation": { type: "boolean" },
101
94
  agent: { type: "string" },
102
95
  tools: { type: "string" },
103
- "tools-repo": { type: "string" },
104
96
  "no-openspec": { type: "boolean" },
105
97
  "no-connectors": { type: "boolean" },
106
98
  commit: { type: "boolean" },
@@ -112,11 +104,7 @@ async function main() {
112
104
  "no-kit": { type: "boolean" },
113
105
  all: { type: "boolean" },
114
106
  dir: { type: "string" },
115
- stack: { type: "string" },
116
- list: { type: "boolean" },
117
107
  json: { type: "boolean" },
118
- describe: { type: "string" },
119
- params: { type: "string" },
120
108
  },
121
109
  });
122
110
  const [cmd, ...resto] = positionals;
@@ -127,14 +115,12 @@ async function main() {
127
115
  console.log(AYUDA);
128
116
  return;
129
117
  }
130
- // `orqen` alone: logo and help. The desktop app is a separate project (github.com/sistemas-telpin/orqen-gui).
118
+ // `orqen` alone: logo and help. The desktop app is a separate project (github.com/sistemas-telpin/orqen-studio).
131
119
  if (!cmd) {
132
120
  await mostrarLogo({ animar: !v["no-animation"] && !v.yes });
133
121
  console.log(AYUDA);
134
122
  return;
135
123
  }
136
- if (v["tools-repo"] && cmd !== "bootstrap")
137
- throw new Error("--tools-repo is only supported by orqen bootstrap.");
138
124
  switch (cmd) {
139
125
  case "init":
140
126
  return init({
@@ -142,15 +128,6 @@ async function main() {
142
128
  sinOpenspec: !!v["no-openspec"], sinConectores: !!v["no-connectors"], commit: !!v.commit, conectores: v.connectors,
143
129
  herramientas: typeof v.tools === "string" ? v.tools.split(",").map((s) => s.trim()).filter(Boolean) : undefined,
144
130
  });
145
- case "bootstrap":
146
- return bootstrap({
147
- nombre: resto.join(" ") || undefined, listar: !!v.list, stack: v.stack, dir: v.dir,
148
- yes: !!v.yes, sinAnimacion: !!v["no-animation"], sinOpenspec: !!v["no-openspec"],
149
- toolsRepo: v["tools-repo"],
150
- json: !!v.json, describir: v.describe,
151
- parametros: typeof v.params === "string" ? JSON.parse(v.params) : undefined,
152
- herramientas: typeof v.tools === "string" ? v.tools.split(",").map((x) => x.trim()).filter(Boolean) : undefined,
153
- });
154
131
  case "update":
155
132
  return update({
156
133
  dir: v.dir ?? resto[0], yes: !!v.yes, sinCli: !!v["no-cli"],
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Key names of orqen/config.yaml and orqen/environment.yaml. The files use English keys; the code (and the JSON that tools
3
- * such as orqen-gui exchange with `orqen connectors get|set`) keeps the internal names. Files written by earlier versions,
3
+ * such as orqen-studio exchange with `orqen connectors get|set`) keeps the internal names. Files written by earlier versions,
4
4
  * with the keys in Spanish, are still read: each key is accepted under either name.
5
5
  */
6
6
  const TESTS = { unit: "unitarios", integration: "integracion", e2e: "e2e", visual: "visual" };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * orqen practice: the project of the interactive tutorial (orqen-gui › Tutorial interactivo).
2
+ * orqen practice: the project of the interactive tutorial (orqen-studio › Tutorial interactivo).
3
3
  * orqen practice create [--dir D] [--no-openspec] [--json] creates (or finds) <app dir>/practica/facturas-demo
4
4
  * orqen practice request <1|2> [--json] the client sends request TUT-n
5
5
  * orqen practice client <KEY> [--json] the client (an LLM) answers what the team wrote
@@ -0,0 +1,21 @@
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>
4
+ allowed-tools: Bash(orqen:*), AskUserQuestion
5
+ ---
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).
8
+
9
+ 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
+ - **description**: what to do and why, in a few sentences.
11
+ - **acceptance_criteria**: at least one, each testable ("Given … when … then …"). Testing evaluates every one.
12
+ - **plan**: the steps, each ending with its estimate in hours, e.g. `Unify the entry point (2h)`.
13
+ - **estimated_hours**: the total.
14
+
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:
16
+
17
+ `orqen new_worq "<title>" <brief.json>`
18
+
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.
20
+
21
+ 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,6 +30,8 @@ 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.
34
+
33
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.
34
36
 
35
37
  orqen works alongside the person; it does not replace them. While someone is on the other side (they invoked
@@ -56,9 +56,12 @@ export function nextSteps(item, cfg) {
56
56
  if (!item.artifacts.devel_pr)
57
57
  return [s(6, "developer", `/orqen:pr ${ik}`, "Explain the changes and open the PR")];
58
58
  return [s(9, "senior", `/orqen:approve ${ik}`, "Senior: approve the PR or request changes")];
59
- case "DELIVERY": return item.artifacts.devel_pr && !item.artifacts.devel_pr_merged
60
- ? [s(0, "senior", `merge ${item.artifacts.devel_pr}`, "Merge the approved PR by hand; orqen detects it"), s(9, "senior", `/orqen:approve ${ik}`, "Then deliver to the client")]
61
- : [s(9, "senior", `/orqen:approve ${ik}`, "Deliver to the client")];
59
+ case "DELIVERY":
60
+ if (item.origin === "internal")
61
+ return [s(0, "senior", item.artifacts.devel_pr ? `merge ${item.artifacts.devel_pr}` : `orqen status ${k}`, "Merge the approved PR by hand: orqen detects it and closes this worq and its issue")];
62
+ return item.artifacts.devel_pr && !item.artifacts.devel_pr_merged
63
+ ? [s(0, "senior", `merge ${item.artifacts.devel_pr}`, "Merge the approved PR by hand; orqen detects it"), s(9, "senior", `/orqen:approve ${ik}`, "Then deliver to the client")]
64
+ : [s(9, "senior", `/orqen:approve ${ik}`, "Deliver to the client")];
62
65
  case "ACCEPTANCE": return [s(0, "client", `orqen status ${k}`, "Waiting for the client to confirm with /approve")];
63
66
  case "EXECUTION":
64
67
  case "VERIFICATION": return [s(0, "developer", `orqen take ${ik}`, "Operational stage")];
@@ -10,6 +10,7 @@
10
10
  *
11
11
  * The request is what the client sees (requests system); the issue (optional) is the team's (issues system). Both are reached through connectors/.
12
12
  */
13
+ import { rmSync } from "node:fs";
13
14
  import { join, relative } from "node:path";
14
15
  import { detectarIdioma } from "../lib/lang.js";
15
16
  import { SCHEMAS } from "./schemas.js";
@@ -18,6 +19,7 @@ import { Factory } from "./factory.js";
18
19
  import { canLinkNatively, isBotComment, LEGACY_STATE_LABELS, STATE_LABEL } from "../connectors/index.js";
19
20
  import { hoursOf } from "./openspec.js";
20
21
  import { reviewSql } from "./sql.js";
22
+ import { RoutedTracker } from "./routed.js";
21
23
  import { newWorkItem } from "./store.js";
22
24
  import { needsQa, nextSteps, returned, roleOf, workKey } from "./board.js";
23
25
  import { branchFor } from "./workspace.js";
@@ -33,6 +35,8 @@ export class Process {
33
35
  fac;
34
36
  /** Where the client's ticket lives. */
35
37
  requests;
38
+ /** The configured requests connector, without the routing of internal worqs (to compare it with the issues connector). */
39
+ realRequests;
36
40
  /** Where the team's ticket is created (optional). */
37
41
  issues;
38
42
  constructor(cfg, connectors, store, ws, os) {
@@ -41,7 +45,9 @@ export class Process {
41
45
  this.ws = ws;
42
46
  this.os = os;
43
47
  this.fac = new Factory(cfg.factoryDir);
44
- this.requests = connectors.requests;
48
+ this.realRequests = connectors.requests;
49
+ const own = (key) => this.store.get(key)?.origin === "internal";
50
+ this.requests = new RoutedTracker(connectors.requests, connectors.issues ?? connectors.requests, own, () => this.store.all().filter((i) => own(i.key) && !["CLOSED", "CANCELLED"].includes(i.state)).map((i) => i.key));
45
51
  this.issues = connectors.issues;
46
52
  }
47
53
  // ================================================================ the record of a request on this machine
@@ -105,6 +111,7 @@ export class Process {
105
111
  key: item.key, title: item.title ?? item.artifacts.ANALYSIS?.summary?.slice(0, 90), issue: item.issue,
106
112
  state: item.state, role: b.role, lane: item.lane, route: item.route, round: item.round, branch: item.branch || undefined,
107
113
  pr: item.artifacts.devel_pr, merged: item.artifacts.devel_pr_merged ? true : undefined,
114
+ internal: item.origin === "internal" || undefined,
108
115
  analyst: item.analyst, supporter: item.supporter, request_url: this.requests.url(item.key),
109
116
  issue_url: item.issue && this.issues ? this.issues.url(item.issue) : undefined,
110
117
  dir: this.worqRel(item.key), updated: this.store.events(item.key).at(-1)?.ts, next: b.next,
@@ -160,8 +167,10 @@ export class Process {
160
167
  await this.reviewGate(item);
161
168
  else if (item.state === "BLOCKED")
162
169
  await this.reviewUnblock(item);
163
- else if (item.state === "DELIVERY")
164
- await this.checkMerge(item); // quiet: "unknown" just keeps waiting
170
+ else if (item.state === "DELIVERY") {
171
+ await this.checkMerge(item);
172
+ await this.closeInternal(item);
173
+ } // quiet: "unknown" just keeps waiting
165
174
  if (item.state === "NEW")
166
175
  pending.push({ key, state: "NEW", for: this.cfg.supportStage ? "support" : "analyst" });
167
176
  else if (isAgentState(item.state)) {
@@ -369,6 +378,8 @@ export class Process {
369
378
  throw new Error(`The analysis of ${key} is driven by an analyst: use /orqen:analyze ${key} (or \`orqen analyze ${key}\`).`);
370
379
  if (item.state === "SUPPORT" && !fromAnalyze)
371
380
  throw new Error(`Support for ${key} is driven by a person: use /orqen:support ${key} (or \`orqen support ${key}\`).`);
381
+ if (item.origin === "internal" && item.state === "DELIVERY")
382
+ throw new Error(`${key} is a worq started by the team: there is no delivery to a client. It closes by itself when its PR is merged (orqen merged ${key} if orqen cannot read it).`);
372
383
  this.assertClaimable(item, agent);
373
384
  item.lock = { agent, since: new Date().toISOString() };
374
385
  this.store.save(item);
@@ -695,7 +706,8 @@ export class Process {
695
706
  item.artifacts.estimated_hours = item.change
696
707
  ? this.os.tasks(item.change).reduce((a, t) => a + (t.hours ?? 0), 0)
697
708
  : s.estimated_hours;
698
- await this.createIssue(item);
709
+ if (item.origin !== "internal")
710
+ await this.createIssue(item); // a worq of the team already has its issue (created by `orqen new_worq`)
699
711
  this.recordAnalysis(item, s);
700
712
  if (item.change)
701
713
  this.ws.commit(item.key, `spec OpenSpec ${item.change}`);
@@ -705,7 +717,7 @@ export class Process {
705
717
  this.fac.write(item, "analysis.json", JSON.stringify(s, null, 2) + "\n");
706
718
  this.fac.write(item, "analysis.md", `# ${item.key} — analysis (round ${item.round})\n\n` +
707
719
  `- **Analyst:** ${item.analyst ?? "?"}\n- **Route:** ${s.route}\n- **Lane:** ${s.lane}\n- **Lane rationale:** ${s.lane_rationale}\n` +
708
- `- **Issue:** ${item.issue ?? "—"}\n` + (item.change ? `- **OpenSpec change:** openspec/changes/${item.change}/\n` : "") +
720
+ `- **Issue:** ${item.issue ?? (item.origin === "internal" ? item.key : "—")}\n` + (item.change ? `- **OpenSpec change:** openspec/changes/${item.change}/\n` : "") +
709
721
  (item.artifacts.estimated_hours !== undefined ? `- **Estimate:** ${item.artifacts.estimated_hours} h\n` : "") +
710
722
  `\n## Summary\n\n${s.summary}\n\n` +
711
723
  md("Acceptance criteria", s.acceptance_criteria) +
@@ -972,7 +984,7 @@ export class Process {
972
984
  this.store.save(item);
973
985
  }
974
986
  if (!item.artifacts.issue_linked) {
975
- const native = canLinkNatively(this.issues, this.requests) && this.issues.link;
987
+ const native = canLinkNatively(this.issues, this.realRequests) && this.issues.link;
976
988
  if (native)
977
989
  await this.issues.link(item.issue, item.key);
978
990
  const where = native ? item.issue : `${item.issue} (${this.issues.url(item.issue)})`;
@@ -988,6 +1000,54 @@ export class Process {
988
1000
  if (item.issue && this.issues)
989
1001
  await this.attemptAsync(() => this.issues.comment(item.issue, text));
990
1002
  }
1003
+ // ================================================================ worq started by the team
1004
+ /**
1005
+ * `orqen new_worq "<title>" <brief.json>`: work the team starts itself, with no client request. It creates the issue in the connector in
1006
+ * use (issues, or requests when there is none) and skips support and analysis: the brief (description, acceptance criteria and plan)
1007
+ * takes the place of the analysis and the worq, keyed by that issue, is born in DEVELOPMENT, direct lane (implement → testing → PR →
1008
+ * senior). It closes when its PR is merged.
1009
+ */
1010
+ async newWorq(title, raw, person) {
1011
+ const t = title.trim();
1012
+ if (t.length < 5)
1013
+ throw new Error("A title for the worq is required (at least 5 characters).");
1014
+ const b = (raw ?? {});
1015
+ const description = typeof b.description === "string" ? b.description.trim() : "";
1016
+ const analysis = {
1017
+ summary: typeof b.summary === "string" && b.summary.trim() ? b.summary.trim() : description || t,
1018
+ 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.",
1020
+ plan: b.plan, estimated_hours: b.estimated_hours,
1021
+ };
1022
+ // validated before creating anything: an invalid brief must not leave an issue behind
1023
+ const parsed = SCHEMAS.ANALYSIS.safeParse(analysis);
1024
+ if (!parsed.success)
1025
+ throw new Error(`The brief is not valid:\n${parsed.error.issues.map((i) => ` ${i.path.join(".") || "(root)"}: ${i.message}`).join("\n")}`);
1026
+ 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
+ });
1032
+ const item = { ...newWorkItem(key), state: "ANALYSIS", origin: "internal", title: t, analyst: person, lock: { agent: "internal", since: new Date().toISOString() } };
1033
+ this.store.save(item);
1034
+ const r = await this.complete(key, analysis, "internal");
1035
+ if (!r.ok) {
1036
+ this.store.remove(key);
1037
+ 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")}`);
1039
+ }
1040
+ if (description)
1041
+ this.fac.write(item, "brief.md", `# ${key} — ${t}\n\n${description}\n`);
1042
+ return { key, state: this.item(key).state, dir: this.worqRel(key), url: this.requests.url(key) };
1043
+ }
1044
+ /** A worq started by the team has nobody to deliver to: once its PR is merged it is closed (and so is its issue). */
1045
+ async closeInternal(item) {
1046
+ if (item.origin !== "internal" || item.state !== "DELIVERY" || !item.artifacts.devel_pr_merged)
1047
+ return;
1048
+ await this.attemptAsync(() => this.requests.comment(item.key, `Finished: the PR was merged into ${this.cfg.develBranch}.`));
1049
+ await this.move(item, "CLOSED", "PR merged", "process");
1050
+ }
991
1051
  // ================================================================ merge (by a person)
992
1052
  /**
993
1053
  * DELIVERY: reads whether the integration PR was merged. orqen never merges it; a person does it by hand and orqen records it
@@ -1027,6 +1087,7 @@ export class Process {
1027
1087
  if (item.artifacts.devel_pr_merged)
1028
1088
  return item.artifacts.devel_pr_merged;
1029
1089
  await this.recordMerge(item, person, undefined, true);
1090
+ await this.closeInternal(item);
1030
1091
  return item.artifacts.devel_pr_merged;
1031
1092
  }
1032
1093
  async recordMerge(item, by, at = new Date().toISOString(), confirmed = false) {
@@ -0,0 +1,29 @@
1
+ export class RoutedTracker {
2
+ real;
3
+ own;
4
+ isOwn;
5
+ ownKeys;
6
+ /** `own(key)`: the worq is the team's own; `ownKeys()`: the keys of the open ones (so they are reviewed too). */
7
+ constructor(real, own, isOwn, ownKeys) {
8
+ this.real = real;
9
+ this.own = own;
10
+ this.isOwn = isOwn;
11
+ this.ownKeys = ownKeys;
12
+ }
13
+ to = (key) => (this.isOwn(key) ? this.own : this.real);
14
+ get kind() { return this.real.kind; }
15
+ get label() { return this.real.label; }
16
+ /** The team's own worqs are always reviewed too (their PR is read, their merge detected). */
17
+ async pending() { return [...new Set([...await this.real.pending(), ...this.ownKeys()])]; }
18
+ search(query) { return this.real.search(query); }
19
+ ticket(key) { return this.to(key).ticket(key); }
20
+ comments(key) { return this.to(key).comments(key); }
21
+ comment(key, text) { return this.to(key).comment(key, text); }
22
+ setStateLabel(key, state) { return this.to(key).setStateLabel(key, state); }
23
+ transition(key, name) { return this.to(key).transition(key, name); }
24
+ create(t) { return this.own.create(t); }
25
+ async finish(key, reason) { await this.to(key).finish?.(key, reason); }
26
+ link(from, to) { return this.real.link ? this.real.link(from, to) : Promise.resolve(); }
27
+ url(key) { return this.to(key).url(key); }
28
+ check() { return this.real.check(); }
29
+ }
@@ -1,5 +1,5 @@
1
1
  /** State of each request in JSON files (orqen/state/, ignored by git → survives branch checkouts). */
2
- import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
2
+ import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
3
  import { join } from "node:path";
4
4
  export const newWorkItem = (key) => ({
5
5
  key, state: "NEW", round: 1, testingAttempts: 0, questionRounds: 0, lastSeenComment: "",
@@ -20,6 +20,9 @@ export class Store {
20
20
  writeFileSync(tmp, JSON.stringify(rec, null, 2));
21
21
  renameSync(tmp, this.path(rec.key)); // atomic write
22
22
  }
23
+ /** Forgets a request that was never started (the log goes too). */
24
+ remove(key) { for (const f of [this.path(key), join(this.dir, `${key}.log.jsonl`)])
25
+ rmSync(f, { force: true }); }
23
26
  log(key, ev) { appendFileSync(join(this.dir, `${key}.log.jsonl`), JSON.stringify(ev) + "\n"); }
24
27
  events(key) {
25
28
  const f = join(this.dir, `${key}.log.jsonl`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@telpin-sistemas/orqen",
3
- "version": "0.1.8",
3
+ "version": "0.1.11",
4
4
  "description": "orqen multi-agent orchestration on OpenSpec, from customer request to production.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -19,7 +19,7 @@
19
19
  "dev": "tsx src/index.ts",
20
20
  "build": "tsc -p tsconfig.build.json && node scripts/copy-template.mjs",
21
21
  "test": "npm run build && node --import tsx --test test/*.test.ts",
22
- "test:e2e": "npm run build && node --import tsx --test test/*e2e.test.ts test/cli.test.ts test/bootstrap.test.ts test/swarm-apply.test.ts test/tools-repository.test.ts test/workflow-environment.test.ts",
22
+ "test:e2e": "npm run build && node --import tsx --test test/*e2e.test.ts test/cli.test.ts test/swarm-apply.test.ts test/tools-repository.test.ts test/workflow-environment.test.ts",
23
23
  "typecheck": "tsc --noEmit",
24
24
  "setup": "npm run build && npm link",
25
25
  "prepack": "npm run build",
@@ -1,260 +0,0 @@
1
- /**
2
- * orqen bootstrap: bootstrap a new project from a tool of the catalog.
3
- *
4
- * 1. Ask the project name, the folder and the stack (tool).
5
- * 2. Check the stack requirements (node, mvn, docker…) and ask its parameters (ports, Java package…).
6
- * 3. Create the folder and the Git repo, generate the code (official generators + the tool's skeleton)
7
- * and copy the tool scripts to orqen/tools/ (e.g. orqen/tools/db.mjs to run the database in Docker).
8
- * 4. Run `orqen init` with the stack and environments already known (no detection or AI needed).
9
- * 5. Offer the initial commit.
10
- */
11
- import { existsSync, mkdirSync, readdirSync, writeFileSync } from "node:fs";
12
- import { join, resolve } from "node:path";
13
- import { ejecutar } from "../lib/proc.js";
14
- import { puertoAbierto } from "../lib/processes.js";
15
- import { cargarTool, chequearRequisitos, copiarCarpeta, instalarTools, listarTools, parametrosDe, render, TOOLS_DIR, validarParametro, variablesBase, } from "../lib/tools.js";
16
- import { prepararTools } from "../lib/tools-repository.js";
17
- import { VERSION_CLI } from "../lib/system.js";
18
- import { mostrarLogo } from "../ui/logo.js";
19
- import { azul, confirmar, elegir, gris, interactivo, magenta, p, pc, textoValidado, tick } from "../ui/console.js";
20
- import { init } from "./init.js";
21
- import { spawn } from "node:child_process";
22
- /** Missing requirements that prevent creating the code: the commands its generators run, and node. */
23
- export function bloqueantes(tool, req) {
24
- const paraCrear = new Set(tool.scaffold.flatMap((s) => ("correr" in s ? [s.correr.split(/\s+/)[0]] : [])));
25
- return req.filter((r) => !r.ok && (paraCrear.has(r.comando) || r.comando === "node"));
26
- }
27
- /** `orqen bootstrap --list --json` and `--describe <stack> --json`, for tools such as orqen-gui. Errors are JSON too. */
28
- async function bootstrapJson(o) {
29
- const fail = (error, extra = {}) => { console.log(JSON.stringify({ error, ...extra })); process.exitCode = 1; };
30
- try {
31
- await prepararTools(o.toolsRepo, true);
32
- }
33
- catch (e) {
34
- return fail(e.message, { needsRepo: !existsSync(TOOLS_DIR) });
35
- }
36
- const stacks = listarTools();
37
- if (!o.describir)
38
- return console.log(JSON.stringify({ stacks, dir: TOOLS_DIR }));
39
- const stack = stacks.find((t) => t.id === o.describir);
40
- if (!stack)
41
- return fail(`Unknown stack "${o.describir}". Available: ${stacks.map((t) => t.id).join(", ")}`);
42
- const base = variablesBase(o.nombre || "Project");
43
- const vars = { ...base };
44
- const parametros = [];
45
- for (const prm of parametrosDe(stack.id, base)) {
46
- const defecto = prm.tipo === "puerto" ? String(await puertoLibre(Number(prm.defecto))) : prm.defecto;
47
- vars[prm.id] = defecto;
48
- parametros.push({ id: prm.id, pregunta: prm.pregunta, tipo: prm.tipo, defecto, enUso: prm.tipo === "puerto" && defecto !== prm.defecto ? prm.defecto : undefined });
49
- }
50
- if (vars.PAQUETE)
51
- vars.PAQUETE_RUTA = vars.PAQUETE.replaceAll(".", "/");
52
- let tool;
53
- try {
54
- tool = cargarTool(stack.id, vars);
55
- }
56
- catch (e) {
57
- return fail(e.message);
58
- }
59
- const req = chequearRequisitos(tool);
60
- const bloquea = new Set(bloqueantes(tool, req).map((r) => r.comando));
61
- console.log(JSON.stringify({
62
- stack, carpeta: base.PROYECTO_ID, parametros,
63
- requisitos: req.map((r) => ({ ...r, bloquea: bloquea.has(r.comando) })),
64
- procesos: tool.entornos.procesos.map((x) => ({ nombre: x.nombre, comando: x.comando, ruta: x.ruta, cuando: x.cuando })),
65
- }));
66
- }
67
- const vacio = (dir) => !existsSync(dir) || readdirSync(dir).length === 0;
68
- /** Next free port from `desde`. */
69
- async function puertoLibre(desde) {
70
- for (let n = desde; n < desde + 50; n++)
71
- if (!(await puertoAbierto(n, 300)))
72
- return n;
73
- return desde;
74
- }
75
- /** Run a shell command in the project, keeping the last output lines for errors. */
76
- function correr(cmd, cwd) {
77
- return new Promise((ok) => {
78
- let salida = "";
79
- const h = spawn(cmd, { cwd, shell: true, windowsHide: true, stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, CI: "1" } });
80
- h.stdout?.on("data", (d) => (salida = (salida + d).slice(-8000)));
81
- h.stderr?.on("data", (d) => (salida = (salida + d).slice(-8000)));
82
- h.on("error", (e) => ok({ ok: false, cola: e.message }));
83
- h.on("close", (c) => ok({ ok: c === 0, cola: salida.split(/\r?\n/).filter(Boolean).slice(-15).join("\n") }));
84
- });
85
- }
86
- export async function bootstrap(o) {
87
- if (o.json && (o.listar || o.describir))
88
- return bootstrapJson(o);
89
- const yes = !!o.yes || !interactivo();
90
- if (!o.listar) {
91
- await mostrarLogo({
92
- animar: !o.sinAnimacion && !o.yes, esperarTecla: true,
93
- bienvenida: [
94
- "Bootstrap will:",
95
- " • Ask the name and the stack, and generate the code with the official generators",
96
- " • Add the tools that start its environments (database in Docker, servers…)",
97
- " • Leave the repository ready for agents (orqen init, OpenSpec, connectors)",
98
- ],
99
- });
100
- p.intro(`${azul("orqen")} ${magenta("bootstrap")} ${gris(`v${VERSION_CLI}`)}`);
101
- if (!o.yes && !interactivo())
102
- p.log.warn("Non-interactive terminal. Using defaults as with --yes.");
103
- }
104
- // 1. Name, folder and stack.
105
- await prepararTools(o.toolsRepo, yes);
106
- const tools = listarTools();
107
- if (!tools.length) {
108
- p.cancel(`No tools found in ${TOOLS_DIR}.`);
109
- process.exitCode = 1;
110
- return;
111
- }
112
- if (o.listar) {
113
- for (const t of tools)
114
- console.log(`${pc.bold(t.id.padEnd(24))} ${t.nombre}\n${" ".repeat(25)}${gris(t.descripcion)}`);
115
- return;
116
- }
117
- const nombre = o.nombre ?? (yes ? "" : await textoValidado("Project name", "", (v) => (/^[\p{L}\p{N}][\p{L}\p{N} _.-]*$/u.test(v) ? undefined : "Use letters, numbers, spaces, dots, dashes or underscores"), "Plataforma de Pagos"));
118
- if (!nombre) {
119
- p.cancel("A project name is required (orqen bootstrap <name>).");
120
- process.exitCode = 1;
121
- return;
122
- }
123
- const base = variablesBase(nombre);
124
- const dir = resolve(o.dir ?? (yes ? base.PROYECTO_ID : await textoValidado("Folder", base.PROYECTO_ID, (v) => (v ? undefined : "Required"))));
125
- if (!vacio(dir)) {
126
- p.cancel(`${dir} already exists and is not empty. Choose another folder (--dir).`);
127
- process.exitCode = 1;
128
- return;
129
- }
130
- let stackId = o.stack;
131
- if (stackId && !tools.some((t) => t.id === stackId)) {
132
- p.cancel(`Unknown stack "${stackId}". Available: ${tools.map((t) => t.id).join(", ")}`);
133
- process.exitCode = 1;
134
- return;
135
- }
136
- stackId ??= await elegir("Stack", tools.map((t) => ({ value: t.id, label: t.nombre, hint: t.descripcion })), tools[0].id, yes);
137
- // 2. Parameters (ports are checked against what is already running) and requirements.
138
- const vars = { ...base };
139
- for (const prm of parametrosDe(stackId, base)) {
140
- let def = prm.defecto;
141
- if (prm.tipo === "puerto") {
142
- const libre = await puertoLibre(Number(def));
143
- if (String(libre) !== def)
144
- p.log.info(`Port ${def} is in use: proposing ${libre} for "${prm.pregunta}".`);
145
- def = String(libre);
146
- }
147
- const dado = o.parametros?.[prm.id];
148
- if (dado !== undefined) {
149
- const error = validarParametro(prm.tipo, dado);
150
- if (error) {
151
- p.cancel(`${prm.pregunta}: ${error}`);
152
- process.exitCode = 1;
153
- return;
154
- }
155
- }
156
- vars[prm.id] = dado ?? (yes ? def : await textoValidado(prm.pregunta, def, (v) => validarParametro(prm.tipo, v)));
157
- }
158
- if (vars.PAQUETE)
159
- vars.PAQUETE_RUTA = vars.PAQUETE.replaceAll(".", "/");
160
- let tool;
161
- try {
162
- tool = cargarTool(stackId, vars);
163
- }
164
- catch (e) {
165
- p.cancel(e.message);
166
- process.exitCode = 1;
167
- return;
168
- }
169
- const req = chequearRequisitos(tool);
170
- p.note(req.map((r) => `${tick(r.ok, r.comando !== "docker")} ${r.comando.padEnd(8)} ${gris(r.detalle)}`).join("\n"), "Requirements");
171
- // To create the code you need the commands its generators run; Docker is only needed to run the database.
172
- const bloquean = bloqueantes(tool, req);
173
- if (bloquean.length && !o.sinComandos) {
174
- p.cancel(bloquean.map((r) => `${r.comando}: ${r.ayuda ?? r.detalle}`).join("\n"));
175
- process.exitCode = 1;
176
- return;
177
- }
178
- for (const r of req.filter((r) => !r.ok && !bloquean.includes(r)))
179
- p.log.warn(`${r.comando}: ${r.ayuda ?? r.detalle}. The project is created anyway; you need it to run it.`);
180
- p.note([
181
- `${pc.bold(vars.PROYECTO)} ${gris(dir)}`,
182
- `${tool.nombre} ${gris(`(${tool.id})`)}`,
183
- ...tool.parametros.map((x) => `${x.pregunta}: ${pc.cyan(vars[x.id])}`),
184
- "",
185
- gris("How it will start:"),
186
- ...tool.entornos.procesos.map((x) => ` ${x.nombre}: ${x.comando}${x.ruta !== "." ? gris(` (in ${x.ruta})`) : ""}${x.cuando === "e2e" ? gris(" [e2e only]") : ""}`),
187
- ].join("\n"), "New project");
188
- if (!(await confirmar("Create it?", true, yes))) {
189
- p.outro("Canceled. Nothing was created.");
190
- return;
191
- }
192
- // 3. Folder, Git and code.
193
- mkdirSync(dir, { recursive: true });
194
- ejecutar("git", ["init", "-q", "-b", "main"], { cwd: dir });
195
- const s = p.spinner();
196
- for (const paso of tool.scaffold) {
197
- if ("copiar" in paso) {
198
- const n = copiarCarpeta(join(TOOLS_DIR, stackId, paso.copiar), dir, vars).length;
199
- p.log.success(`Project skeleton (${n} files)`);
200
- }
201
- else if ("archivo" in paso) {
202
- const ruta = join(dir, render(paso.archivo, vars));
203
- mkdirSync(join(ruta, ".."), { recursive: true });
204
- writeFileSync(ruta, paso.contenido);
205
- }
206
- else if (!o.sinComandos) {
207
- const inicio = Date.now(), etiqueta = paso.descripcion ?? paso.correr;
208
- // Without a terminal (CI, tests) a spinner floods the output with frames: plain log lines instead.
209
- const tty = interactivo();
210
- if (tty)
211
- s.start(`${etiqueta}…`);
212
- else
213
- p.log.step(`${etiqueta}…`);
214
- const reloj = tty ? setInterval(() => s.message(`${etiqueta}… ${Math.round((Date.now() - inicio) / 1000)}s`), 1000) : undefined;
215
- const r = await correr(paso.correr, paso.en ? join(dir, paso.en) : dir);
216
- clearInterval(reloj);
217
- if (!r.ok) {
218
- if (tty)
219
- s.error(`Failed: ${paso.correr}`);
220
- else
221
- p.log.error(`Failed: ${paso.correr}`);
222
- p.log.message(gris(r.cola));
223
- p.cancel(`The project folder was left at ${dir} so you can check what happened. Delete it to start over.`);
224
- process.exitCode = 1;
225
- return;
226
- }
227
- const fin = `${etiqueta} ${gris(`(${Math.round((Date.now() - inicio) / 1000)}s)`)}`;
228
- if (tty)
229
- s.stop(fin);
230
- else
231
- p.log.success(fin);
232
- }
233
- }
234
- const scripts = instalarTools(dir, tool, vars);
235
- p.log.success(`Environment tools: ${scripts.join(", ")}`);
236
- // 4. orqen init with the known stack and environments.
237
- p.log.step("Preparing the repository for agents (orqen init)…");
238
- await init({
239
- dir, yes, sinAnimacion: true, sinLogo: true, sinOpenspec: o.sinOpenspec, herramientas: o.herramientas,
240
- predefinido: { stack: tool.stack, entornos: tool.entornos },
241
- });
242
- if (process.exitCode)
243
- return;
244
- // 5. Initial commit.
245
- if (await confirmar("Make the initial commit?", true, yes)) {
246
- ejecutar("git", ["add", "-A"], { cwd: dir });
247
- const c = ejecutar("git", ["commit", "-q", "-m", `Create ${vars.PROYECTO} with orqen (${tool.id})`], { cwd: dir });
248
- if (c.codigo === 0)
249
- p.log.success("Initial commit created on main");
250
- else
251
- p.log.warn(`Could not commit (${(c.stderr || c.stdout).trim().split("\n")[0]}). Configure git user.name and user.email and commit by hand.`);
252
- }
253
- p.note([
254
- `${pc.bold("1.")} ${pc.cyan(`cd ${dir}`)}`,
255
- `${pc.bold("2.")} ${pc.cyan("orqen env up")} ${gris("starts the database and the backend and runs the migrations (--all: also the frontend)")}`,
256
- `${pc.bold("3.")} ${pc.cyan("orqen env test")} ${gris("· orqen env down when you are done")}`,
257
- `${pc.bold("4.")} ${gris("Push it to your Git remote and start working on requests: /orqen:analyze <KEY> (new to orqen? run /orqen:tutorial in Claude Code)")}`,
258
- ].join("\n"), "Next steps");
259
- p.outro(`${magenta("//")} ${pc.bold(`${vars.PROYECTO} is ready.`)}`);
260
- }