huntban-cli 0.0.0-stage → 1.0.0

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.
@@ -0,0 +1,31 @@
1
+ const { apiRequest, resolveTask, checkActor } = require('../api');
2
+
3
+ module.exports = async function updateCommand(parsed, config) {
4
+ const target = parsed.positional[0] || parsed.flags.task;
5
+ const boardId = parsed.flags.board || config.boardId;
6
+
7
+ if (!target) {
8
+ console.error('❌ Falta especificar la tarea. Uso: huntban update <TASK_ID_O_CODIGO> [--phase ...] [--pipeline ...] [--name ...]');
9
+ process.exit(1);
10
+ }
11
+
12
+ const resolved = await resolveTask(boardId, target, config);
13
+
14
+ const payload = { taskId: resolved.id };
15
+ if (parsed.flags.name) payload.name = parsed.flags.name;
16
+ if (parsed.flags.description || parsed.flags.desc) payload.description = parsed.flags.description || parsed.flags.desc;
17
+ if (parsed.flags.phase) payload.phase = parsed.flags.phase;
18
+ if (parsed.flags.pipeline) payload.pipelineId = parsed.flags.pipeline;
19
+ if (parsed.flags.priority) payload.priority = parseInt(parsed.flags.priority);
20
+ if (parsed.flags.responsible) payload.responsibleId = parsed.flags.responsible;
21
+ if (parsed.flags.startedAt) payload.startedAt = parsed.flags.startedAt;
22
+ if (parsed.flags.closedAt) payload.closedAt = parsed.flags.closedAt;
23
+ if (parsed.flags.comment || parsed.flags.m) payload.comment = parsed.flags.comment || parsed.flags.m;
24
+
25
+ const endpoint = `/boards/${boardId}/connector`;
26
+ const response = await apiRequest(endpoint, 'PUT', payload, config);
27
+
28
+ console.log(`\n✅ Tarea [${resolved.code}] actualizada correctamente`);
29
+ checkActor(response?.actor, config.userEmail);
30
+ console.log('');
31
+ };
package/lib/config.js ADDED
@@ -0,0 +1,105 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const os = require('os');
4
+
5
+ const GLOBAL_CONFIG_DIR = path.join(os.homedir(), '.huntban');
6
+ const GLOBAL_CONFIG_FILE = path.join(GLOBAL_CONFIG_DIR, 'config.json');
7
+ const LOCAL_CONFIG_FILE = path.join(process.cwd(), '.huntban.json');
8
+
9
+ function ensureConfigDir() {
10
+ if (!fs.existsSync(GLOBAL_CONFIG_DIR)) {
11
+ fs.mkdirSync(GLOBAL_CONFIG_DIR, { recursive: true });
12
+ }
13
+ }
14
+
15
+ function readJsonFile(filePath) {
16
+ try {
17
+ if (fs.existsSync(filePath)) {
18
+ const content = fs.readFileSync(filePath, 'utf8');
19
+ return JSON.parse(content);
20
+ }
21
+ } catch (e) {
22
+ // Ignore invalid JSON or read errors
23
+ }
24
+ return {};
25
+ }
26
+
27
+ function writeJsonFile(filePath, data) {
28
+ if (filePath === GLOBAL_CONFIG_FILE) {
29
+ ensureConfigDir();
30
+ }
31
+ fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf8');
32
+ }
33
+
34
+ /**
35
+ * Carga la configuración combinada respetando el orden de precedencia:
36
+ * 1. Variables de Entorno (HUNTBAN_*)
37
+ * 2. Archivo local de proyecto (.huntban.json en CWD)
38
+ * 3. Archivo global de usuario (~/.huntban/config.json)
39
+ */
40
+ function loadConfig() {
41
+ const globalConfig = readJsonFile(GLOBAL_CONFIG_FILE);
42
+
43
+ const localPaths = [
44
+ path.join(process.cwd(), '.huntban.json'),
45
+ path.join(process.cwd(), '.huntban-rc.json')
46
+ ];
47
+
48
+ let localConfig = {};
49
+ let activeLocalPath = null;
50
+ for (const lp of localPaths) {
51
+ if (fs.existsSync(lp)) {
52
+ localConfig = readJsonFile(lp);
53
+ activeLocalPath = lp;
54
+ break;
55
+ }
56
+ }
57
+
58
+ const merged = {
59
+ apiUrl: process.env.HUNTBAN_API_URL || localConfig.apiUrl || globalConfig.apiUrl || 'http://localhost:3000',
60
+ apiKey: process.env.HUNTBAN_API_KEY || localConfig.apiKey || globalConfig.apiKey || '',
61
+ apiSecret: process.env.HUNTBAN_API_SECRET || localConfig.apiSecret || globalConfig.apiSecret || '',
62
+ boardId: process.env.HUNTBAN_BOARD_ID || localConfig.boardId || globalConfig.boardId || '',
63
+ userEmail: process.env.HUNTBAN_USER_EMAIL || localConfig.userEmail || globalConfig.userEmail || '',
64
+ _localFile: activeLocalPath,
65
+ _globalFile: GLOBAL_CONFIG_FILE
66
+ };
67
+
68
+ return merged;
69
+ }
70
+
71
+ /**
72
+ * Guarda valores en la configuración local del proyecto (.huntban.json)
73
+ */
74
+ function setLocalConfig(updates) {
75
+ const current = readJsonFile(LOCAL_CONFIG_FILE);
76
+ const next = { ...current, ...updates };
77
+ writeJsonFile(LOCAL_CONFIG_FILE, next);
78
+ return next;
79
+ }
80
+
81
+ /**
82
+ * Guarda valores en la configuración global (~/.huntban/config.json)
83
+ */
84
+ function setGlobalConfig(updates) {
85
+ const current = readJsonFile(GLOBAL_CONFIG_FILE);
86
+ const next = { ...current, ...updates };
87
+ writeJsonFile(GLOBAL_CONFIG_FILE, next);
88
+ return next;
89
+ }
90
+
91
+ /**
92
+ * Retorna la configuración global
93
+ */
94
+ function getGlobalConfig() {
95
+ return readJsonFile(GLOBAL_CONFIG_FILE);
96
+ }
97
+
98
+ module.exports = {
99
+ GLOBAL_CONFIG_FILE,
100
+ LOCAL_CONFIG_FILE,
101
+ loadConfig,
102
+ setLocalConfig,
103
+ setGlobalConfig,
104
+ getGlobalConfig
105
+ };
@@ -0,0 +1,57 @@
1
+ const readline = require('readline');
2
+
3
+ function isInteractive() {
4
+ return Boolean(process.stdin.isTTY && process.stdout.isTTY);
5
+ }
6
+
7
+ function askQuestion(query) {
8
+ if (!isInteractive()) return Promise.resolve('');
9
+
10
+ const rl = readline.createInterface({
11
+ input: process.stdin,
12
+ output: process.stdout
13
+ });
14
+
15
+ return new Promise((resolve) => {
16
+ rl.question(query, (ans) => {
17
+ rl.close();
18
+ resolve(ans.trim());
19
+ });
20
+ });
21
+ }
22
+
23
+ async function askConfirm(message, defaultYes = true) {
24
+ if (!isInteractive()) return true;
25
+
26
+ const hint = defaultYes ? '[S/n]' : '[s/N]';
27
+ const ans = await askQuestion(`${message} ${hint}: `);
28
+
29
+ if (!ans) return defaultYes;
30
+ const lower = ans.toLowerCase();
31
+ return lower === 's' || lower === 'si' || lower === 'y' || lower === 'yes';
32
+ }
33
+
34
+ async function askMenu(title, options) {
35
+ if (!isInteractive()) return null;
36
+
37
+ console.log(`\n${title}`);
38
+ options.forEach((opt, idx) => {
39
+ console.log(` [${idx + 1}] ${opt.label || opt.name || opt}`);
40
+ });
41
+
42
+ while (true) {
43
+ const ans = await askQuestion(`\nSelecciona una opción [1-${options.length}]: `);
44
+ const num = parseInt(ans, 10);
45
+ if (!isNaN(num) && num >= 1 && num <= options.length) {
46
+ return options[num - 1];
47
+ }
48
+ console.log(`⚠️ Por favor ingresa un número válido entre 1 y ${options.length}.`);
49
+ }
50
+ }
51
+
52
+ module.exports = {
53
+ isInteractive,
54
+ askQuestion,
55
+ askConfirm,
56
+ askMenu
57
+ };
package/package.json CHANGED
@@ -1,6 +1,22 @@
1
1
  {
2
2
  "name": "huntban-cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "CLI oficial y herramienta de automatización para Huntban y agentes Antigravity",
5
+ "main": "bin/huntban.js",
6
+ "bin": {
7
+ "huntban": "./bin/huntban.js"
8
+ },
9
+ "keywords": [
10
+ "huntban",
11
+ "cli",
12
+ "antigravity",
13
+ "kanban",
14
+ "connector",
15
+ "automation"
16
+ ],
17
+ "author": "Huntban Team",
18
+ "license": "MIT",
19
+ "engines": {
20
+ "node": ">=18.0.0"
21
+ }
22
+ }
@@ -0,0 +1,191 @@
1
+ ---
2
+ name: huntban-connector
3
+ description: Manual técnico y herramientas para que el agente Antigravity interactúe directamente con Huntban vía Connector API y huntban CLI (listar tareas, consultar detalles por código o ID, cerrar tareas con sinceramiento de fechas, comentar y actualizar estados en nombre de un usuario).
4
+ ---
5
+
6
+ # Huntban CLI Toolkit para Antigravity
7
+
8
+ Esta habilidad permite al asistente **Antigravity** comunicarse de forma bidireccional, simplificada y portable con **Huntban** utilizando el CLI global `huntban`. Soporta resolución transparente por **código amigable de tarea** (ej: `TSTT-28`, `BLBX-55`), sincronización de fechas reales (sinceramiento de Gantt), checklists de criterios de aceptación y atribución de autor.
9
+
10
+ ---
11
+
12
+ ## 1. Instalación y Vinculación Global
13
+
14
+ El CLI está empaquetado en `huntban-cli/` con dependencias nativas de Node.js (>= 18.0.0). Para habilitar el comando global `huntban` en cualquier terminal:
15
+
16
+ ```bash
17
+ cd huntban-cli
18
+ npm link
19
+ ```
20
+
21
+ Verifica la instalación ejecutando:
22
+ ```bash
23
+ huntban --version
24
+ huntban --help
25
+ ```
26
+
27
+ ---
28
+
29
+ ## 2. Guía Paso a Paso: Vincular un Repositorio (`huntban attach`)
30
+
31
+ Puedes vincular cualquier repositorio de código a Huntban con un único comando:
32
+
33
+ ```bash
34
+ huntban attach
35
+ # o también:
36
+ huntban init
37
+ ```
38
+
39
+ ### ¿Qué hace automáticamente `huntban attach`?
40
+ 1. **Instala el skill en el repo**: Crea `.agents/skills/huntban-connector/SKILL.md` para que Antigravity conozca el toolkit en este proyecto.
41
+ 2. **Asistente de Configuración**: Te solicita interactivamente (o mediante flags) los datos de tu tablero y crea `.huntban.json`.
42
+ 3. **Protección de Credenciales**: Añade automáticamente `.huntban.json` a tu `.gitignore`.
43
+ 4. **Verificación inmediata**: Valida la conexión y reporta las columnas activas del tablero.
44
+
45
+ > [!TIP]
46
+ > **Instalación Global para Antigravity**:
47
+ > Si quieres que Antigravity tenga esta habilidad disponible en **todos** los repositorios de tu máquina sin tener que copiarla a cada uno:
48
+ > ```bash
49
+ > huntban attach --global
50
+ > ```
51
+
52
+ ---
53
+
54
+ ### Paso 2.1: Obtener las credenciales en Huntban
55
+ Entra a tu tablero en Huntban y abre el menú de configuración:
56
+ 1. Abre tu tablero (ej: `https://next.huntban.com/<boardId>/board`).
57
+ 2. Haz clic en el ícono de **Configuración del Tablero (⚙️)** en la cabecera.
58
+ 3. Ve a la pestaña **Conector / Webhooks**.
59
+ 4. Copia los siguientes datos:
60
+ - **URL de la API**: Por defecto `https://next.huntban.com/api/v2` (o `http://localhost:3000` en desarrollo).
61
+ - **ID del Tablero (`boardId`)**: El identificador de 24 caracteres de tu tablero.
62
+ - **API Key (`x-api-key`)**: Tu clave pública (comienza con `hb_pk_...`).
63
+ - **API Secret (`x-api-secret`)**: Tu clave privada (comienza con `hb_sk_...`).
64
+ - **Tu Email de usuario**: El correo registrado con tu cuenta en Huntban (para que tus avances, comentarios y cierres lleven tu nombre y foto).
65
+
66
+ ---
67
+
68
+ ### Paso 2.2: Configurar con Flags (No interactivo / CI-CD)
69
+
70
+ Si prefieres pasar todos los datos en una sola línea o en un script automatizado:
71
+
72
+ ```bash
73
+ huntban attach \
74
+ --url https://next.huntban.com/api/v2 \
75
+ --board <ID_DEL_TABLERO> \
76
+ --key <API_KEY> \
77
+ --secret <API_SECRET> \
78
+ --email tu-correo@empresa.com
79
+ ```
80
+
81
+ Esto generará automáticamente el archivo `.huntban.json` en la raíz del repositorio:
82
+
83
+ ```json
84
+ {
85
+ "apiUrl": "https://next.huntban.com/api/v2",
86
+ "boardId": "5d604e568173d863e73eef7e",
87
+ "apiKey": "hb_pk_f828ec25f8a4aa9976737c8dcab5c6fe",
88
+ "apiSecret": "hb_sk_b675796caf012d9d7b1b2de86ec7540b9f6d0f7f6a616eee293b996d0ea920ea",
89
+ "userEmail": "tu-correo@empresa.com"
90
+ }
91
+ ```
92
+
93
+ > [!TIP]
94
+ > **Precedencia de configuración**:
95
+ > 1. Variables de entorno (`HUNTBAN_API_URL`, `HUNTBAN_BOARD_ID`, `HUNTBAN_API_KEY`, `HUNTBAN_API_SECRET`, `HUNTBAN_USER_EMAIL`).
96
+ > 2. Archivo local del proyecto (`.huntban.json` en la raíz actual).
97
+ > 3. Archivo global de usuario (`~/.huntban/config.json`).
98
+
99
+ ### Paso 2.3: Seguridad (`.gitignore`)
100
+ Si el repositorio es público o compartido, añade `.huntban.json` a tu `.gitignore` para no exponer el `apiSecret`:
101
+ ```bash
102
+ echo ".huntban.json" >> .gitignore
103
+ ```
104
+
105
+ ### Paso 2.4: Verificar la conexión
106
+ Comprueba que el CLI se conecta correctamente y lista las columnas de tu tablero:
107
+ ```bash
108
+ huntban cols
109
+ huntban ls --limit 5
110
+ ```
111
+
112
+ ---
113
+
114
+ ## 3. Comandos Rápidos (Cheat Sheet)
115
+
116
+ Todos los comandos admiten tanto el **código amigable de la tarjeta** (ej: `TSTT-28`, `BLBX-55`, `#28`) como el `ObjectId` de Mongo.
117
+
118
+ | Comando | Alias corto | Ejemplo de uso | Qué hace |
119
+ | :--- | :--- | :--- | :--- |
120
+ | **Consultar detalle** | `get` / `show` | `huntban get TSTT-28` | Lee especificaciones completas (Markdown), checklists con IDs, historial de comentarios, épica, etiquetas y link web. |
121
+ | **Mover a columna** | `to` / `mv` | `huntban to TSTT-28 "Haciendo"` | Mueve por keyword inteligente (`haciendo`, `qa`, `dev`). Admite menú interactivo si se omite. |
122
+ | **Avanzar siguiente** | `nx` / `next` | `huntban nx TSTT-28 -m "Avanzado"` | Pasa la tarjeta automáticamente a la siguiente columna según el orden del tablero. |
123
+ | **Marcar checklist** | `check` / `tick` | `huntban check TSTT-28 "Crear auth"` | Marca como completado un criterio de aceptación (`--undo` para desmarcar). |
124
+ | **Enviar a review** | `qa` / `review` | `huntban review TSTT-28 -m "PR #12 listo"` | Pasa a fase `in-confirmation` adjuntando reporte para el revisor o Tech Lead. |
125
+ | **Cierre definitivo** | `cl` / `close` | `huntban cl TSTT-28 --date 2026-11-25 -m "OK"` | Cierra en `closed-success` sincerando la fecha real de entrega para el Gantt. |
126
+ | **Comentar** | `msg` | `huntban msg TSTT-28 -m "Progreso 60%"` | Deja un comentario en el hilo de la tarea con atribución de autor. |
127
+ | **Abrir en navegador** | `open` | `huntban open TSTT-28` | Abre directamente el modal de la tarea en la interfaz web de Huntban. |
128
+ | **Listar tareas** | `ls` / `list` | `huntban ls --search "Login"` | Lista tareas del tablero con filtros (`--limit`, `--search`, `--priority`). |
129
+ | **Ver columnas** | `cols` | `huntban cols` | Lista ordenada de las etapas y fases del tablero. |
130
+ | **Crear tarea** | `create` / `add`| `huntban create --name "Título" --desc "Obj"` | Crea una nueva tarjeta con descripción, contenido y checklist. |
131
+ | **Vincular repositorio** | `attach` / `init` | `huntban attach` | Instala el skill en el proyecto, configura `.huntban.json` y lo añade a `.gitignore`. |
132
+ | **Instalar globalmente** | `attach -g` | `huntban attach -g` | Registra el skill globalmente en `~/.gemini/config/skills/` para todos tus proyectos. |
133
+
134
+ ---
135
+
136
+ ## 4. Flujo de Trabajo: Desarrollador vs Revisor
137
+
138
+ ### Flujo del Desarrollador (Entrega sin cerrar prematuramente):
139
+ 1. **Inspeccionar requerimientos completos**:
140
+ ```bash
141
+ huntban get TSTT-28
142
+ ```
143
+ 2. **Mover a desarrollo e iniciar trabajo**:
144
+ ```bash
145
+ huntban to TSTT-28 "Haciendo"
146
+ ```
147
+ 3. **Marcar criterios de aceptación conforme se implementan**:
148
+ ```bash
149
+ huntban check TSTT-28 "Diseñar interfaz"
150
+ huntban check TSTT-28 "Integrar endpoint"
151
+ ```
152
+ 4. **Entregar para Revisión / QA**:
153
+ ```bash
154
+ huntban review TSTT-28 -m "Código culminado en rama feature/login, listo para pruebas"
155
+ ```
156
+
157
+ ### Flujo del Revisor (Aprobación y Cierre con Sinceramiento):
158
+ Si el revisor aprueba la tarea días después pero necesita que el cronograma Gantt registre con exactitud la fecha en que el desarrollador completó el trabajo:
159
+ ```bash
160
+ huntban cl TSTT-28 --date 2026-11-25 -m "Aprobado en staging y desplegado a producción"
161
+ ```
162
+
163
+ ---
164
+
165
+ ## 5. Enlaces Directos (Deep Links) por Código o ID
166
+
167
+ La interfaz web de Huntban admite abrir directamente el modal de detalle de cualquier tarea pasando su código amigable:
168
+ - `https://next.huntban.com/<boardId>/board?taskId=TSTT-28`
169
+ - `https://next.huntban.com/<boardId>/board?code=TSTT-28`
170
+ - O por su ObjectId tradicional: `?taskId=6b04e8f87d67af55d1b69688`
171
+
172
+ Desde la terminal puedes abrirla al instante con:
173
+ ```bash
174
+ huntban open TSTT-28
175
+ ```
176
+
177
+ ---
178
+
179
+ ## 6. Directrices para el Agente Antigravity
180
+
181
+ 1. **Detección Automática de Configuración en Repositorios**:
182
+ - Antes de ejecutar comandos de Huntban, verifica si existe `.huntban.json` en la raíz del espacio de trabajo.
183
+ - Si no existe, indica al usuario los pasos de la Sección 2: *"Para conectar este repositorio a Huntban, por favor indícame o configura en `.huntban.json`: Board ID, API Key y Secret (obtenibles en Configuración del Tablero > Conector)"*.
184
+ 2. **Prioriza siempre Códigos Amigables**:
185
+ - Usa siempre el código de tarea (`TSTT-28`, `BLBX-55`) en lugar de ObjectIds de Mongo. El CLI se encarga de la resolución transparente.
186
+ 3. **Inspecciona las especificaciones completas**:
187
+ - Cuando te asignen una tarea, ejecuta `huntban get <CODIGO>` para leer las especificaciones completas, los criterios de aceptación y los comentarios previos de aclaración.
188
+ 4. **Actualiza el Checklist progresivamente**:
189
+ - Conforme termines partes de la tarea, ejecuta `huntban check <CODIGO> "<nombre_o_id_subtarea>"` para que el equipo vea el progreso en tiempo real en el tablero.
190
+ 5. **Sinceramiento de Fechas**:
191
+ - Al cerrar tareas (`huntban cl`), si el usuario indica que concluyó en una fecha pasada, incluye `--date YYYY-MM-DD` para no descalibrar el Gantt.
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.