@jmanuelcorral/bond-app 0.1.5 → 0.1.6

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 (70) hide show
  1. package/README.md +211 -17
  2. package/app/brand/TOKENS.md +5 -5
  3. package/app/layouts/bond.json +10 -14
  4. package/app/mods/bond-agents/api.js +35 -0
  5. package/app/mods/bond-agents/branch.svg +1 -0
  6. package/app/mods/bond-agents/brand.js +53 -2
  7. package/app/mods/bond-agents/config.js +4 -0
  8. package/app/mods/bond-agents/eye-off.svg +1 -0
  9. package/app/mods/bond-agents/eye.svg +1 -0
  10. package/app/mods/bond-agents/main.js +308 -327
  11. package/app/mods/bond-agents/model.js +354 -5
  12. package/app/mods/bond-board/api.js +35 -0
  13. package/app/mods/bond-board/branch.svg +1 -0
  14. package/app/mods/bond-board/brand.js +53 -2
  15. package/app/mods/bond-board/config.js +4 -0
  16. package/app/mods/bond-board/main.js +686 -444
  17. package/app/mods/bond-board/model.js +99 -25
  18. package/app/mods/bond-pane/close.svg +1 -0
  19. package/app/mods/bond-pane/hide.svg +1 -0
  20. package/app/mods/bond-pane/main.js +103 -0
  21. package/app/mods/bond-pane/mod.json +1 -0
  22. package/app/mods/bond-pane/model.js +18 -0
  23. package/app/mods/bond-pane/split-down.svg +1 -0
  24. package/app/mods/bond-pane/split-right.svg +1 -0
  25. package/app/mods/bond-pane/unzoom.svg +1 -0
  26. package/app/mods/bond-pane/zoom.svg +1 -0
  27. package/app/mods/bond-settings/api.js +35 -0
  28. package/app/mods/bond-settings/brand.js +53 -2
  29. package/app/mods/bond-settings/config.js +4 -0
  30. package/app/mods/bond-settings/main.js +1159 -278
  31. package/app/mods/bond-settings/mod.json +1 -1
  32. package/app/mods/bond-status/api.js +35 -0
  33. package/app/mods/bond-status/brand.js +53 -2
  34. package/app/mods/bond-status/config.js +4 -0
  35. package/app/mods/bond-status/main.js +37 -15
  36. package/app/mods/bond-status/model.js +19 -1
  37. package/app/mods/bond-tabs/brand.js +53 -2
  38. package/app/mods/bond-tabs/main.js +45 -3
  39. package/app/mods/bond-titlebar/brand.js +53 -2
  40. package/app/mods/bond-titlebar/main.js +85 -29
  41. package/app/mods/bond-titlebar/version.js +3 -0
  42. package/app/themes/bond-dark.json +5 -5
  43. package/app/themes/bond-light.json +5 -5
  44. package/package.json +1 -1
  45. package/runner/Dockerfile +16 -2
  46. package/runner/SPIKE-BOND.md +6 -2
  47. package/runner/entrypoint.sh +16 -0
  48. package/runner/setup.sh +439 -8
  49. package/runner/versions.env +32 -1
  50. package/scripts/app-install.ts +60 -1
  51. package/src/cli.ts +53 -3
  52. package/src/core/agy-login.ts +682 -0
  53. package/src/core/delivery.ts +3 -1
  54. package/src/core/orchestrator.ts +736 -78
  55. package/src/core/repo-host.ts +60 -0
  56. package/src/core/setup.ts +62 -1
  57. package/src/core/watchdog.ts +6 -6
  58. package/src/db/database.ts +41 -1
  59. package/src/db/settings-repo.ts +332 -7
  60. package/src/db/ticket-repo.ts +46 -20
  61. package/src/index.ts +4 -4
  62. package/src/runner/azure-devops-client.ts +163 -0
  63. package/src/runner/docker-client.ts +59 -9
  64. package/src/runner/github-client.ts +30 -3
  65. package/src/runner/hc-client.ts +33 -5
  66. package/src/runner/image-builder.ts +123 -5
  67. package/src/runner/jira-client.ts +368 -0
  68. package/src/runner/tool-catalog.ts +84 -0
  69. package/src/server/app.ts +377 -5
  70. package/src/types.ts +129 -2
@@ -1,10 +1,10 @@
1
- import { execFile } from 'node:child_process';
2
- import { promisify } from 'node:util';
1
+ import { spawn } from 'node:child_process';
2
+ import crypto from 'node:crypto';
3
3
  import fs from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
+ import { DEFAULT_TOOLS, validateAptExtra, validateToolGroups } from './tool-catalog.ts';
6
7
 
7
- const execFileAsync = promisify(execFile);
8
8
 
9
9
  // The runner image build context (Dockerfile with pinned bond/hc/agent versions).
10
10
  const runnerBuildContext = path.resolve(
@@ -41,10 +41,50 @@ export interface RunnerBuildOptions extends RunnerVersions {
41
41
  /** System CLIs (setup.sh --skip-gh / --skip-az); az is heavy and rarely needed. */
42
42
  skip_az?: boolean;
43
43
  skip_gh?: boolean;
44
+ /** Plan bond-app-ajustes-imagen P2: developer tool groups (default: the catalog's). */
45
+ tools?: string[];
46
+ /** Extra Debian packages (setup.sh --apt-extra). */
47
+ apt_extra?: string[];
44
48
  config_dir?: string;
45
49
  credentials_file?: string;
46
50
  /** Root the staged paths must resolve inside of (the orchestrator injects its data dir). */
47
51
  data_dir?: string;
52
+ /** Called as the build advances (steps and setup.sh's narration). */
53
+ on_progress?: (progress: BuildProgress) => void;
54
+ }
55
+
56
+ /**
57
+ * The recipe's fingerprint: sha256 over every file of the build context that shapes the
58
+ * image (Dockerfile, setup.sh, versions.env, the run scripts…), path and content, in a
59
+ * fixed order. Leaves out the staging dirs (build-config, build-creds) and the docs (*.md).
60
+ * Baked as the image label LABEL_RECIPE; a different value means the image is stale even
61
+ * when it carries the chosen agents and tools (a fixed setup.sh, a new pin).
62
+ */
63
+ export const LABEL_RECIPE = 'dev.bond-app.recipe';
64
+
65
+ export function runnerRecipeHash(context: string = runnerBuildContext): string {
66
+ const files: string[] = [];
67
+ const walk = (dir: string) => {
68
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
69
+ const full = path.join(dir, entry.name);
70
+ const rel = path.relative(context, full);
71
+ if (entry.isDirectory()) {
72
+ if (rel === 'build-config' || rel === 'build-creds') continue;
73
+ walk(full);
74
+ } else if (entry.isFile() && !entry.name.endsWith('.md')) {
75
+ files.push(rel);
76
+ }
77
+ }
78
+ };
79
+ walk(context);
80
+ const hash = crypto.createHash('sha256');
81
+ for (const rel of files.sort()) {
82
+ hash.update(rel.split(path.sep).join('/'));
83
+ hash.update('\0');
84
+ hash.update(fs.readFileSync(path.join(context, rel)));
85
+ hash.update('\0');
86
+ }
87
+ return hash.digest('hex').slice(0, 16);
48
88
  }
49
89
 
50
90
  /** The agent list runner/setup.sh accepts (kept in sync; setup.sh is still the judge). */
@@ -86,6 +126,62 @@ export type DockerExec = (
86
126
  options: Record<string, unknown>
87
127
  ) => Promise<unknown>;
88
128
 
129
+ /** Progress of a running build, parsed from docker's output (plan bond-app-ajustes-imagen). */
130
+ export interface BuildProgress {
131
+ /** «Step N/M» of the classic builder; 0 until the first step. */
132
+ step: number;
133
+ total: number;
134
+ /** What it is doing, in words: the last setup.sh line or the step's instruction. */
135
+ detail: string;
136
+ }
137
+
138
+ /**
139
+ * Reads one line of `docker build` output into the progress: «Step 12/27 : RUN …» moves the
140
+ * step, a «setup.sh: …» line (the installer narrating) becomes the detail. Other lines leave
141
+ * it as it was. Never returns secrets: setup.sh masks credential values itself.
142
+ */
143
+ export function parseBuildLine(line: string, prev: BuildProgress): BuildProgress {
144
+ const clean = line.replace(/\x1b\[[0-9;]*[A-Za-z]/g, '').trim();
145
+ const step = clean.match(/^Step (\d+)\/(\d+) : (.*)$/);
146
+ if (step) {
147
+ const instr = step[3].replace(/\s+/g, ' ');
148
+ return { step: Number(step[1]), total: Number(step[2]), detail: instr.length > 90 ? `${instr.slice(0, 89)}…` : instr };
149
+ }
150
+ const setup = clean.match(/^setup\.sh: (?!ERROR)(.*)$/);
151
+ if (setup) return { ...prev, detail: setup[1].slice(0, 120) };
152
+ return prev;
153
+ }
154
+
155
+ /**
156
+ * The default runner of `docker build`: like execFile (rejects on a non-zero exit or the
157
+ * timeout), but hands every output line to `options.onLine` as it arrives.
158
+ */
159
+ const spawnDocker: DockerExec = (file, args, options) =>
160
+ new Promise((resolve, reject) => {
161
+ const onLine = options.onLine as ((line: string) => void) | undefined;
162
+ const child = spawn(file, args, { env: options.env as NodeJS.ProcessEnv, stdio: ['ignore', 'pipe', 'pipe'] });
163
+ let tail = '';
164
+ let buf = '';
165
+ const feed = (chunk: Buffer) => {
166
+ const text = chunk.toString('utf8');
167
+ tail = (tail + text).slice(-8000);
168
+ buf += text;
169
+ const lines = buf.split(/\r?\n/);
170
+ buf = lines.pop() ?? '';
171
+ for (const l of lines) onLine?.(l);
172
+ };
173
+ child.stdout.on('data', feed);
174
+ child.stderr.on('data', feed);
175
+ const timer = setTimeout(() => child.kill('SIGTERM'), Number(options.timeout) || BUILD_TIMEOUT_MS);
176
+ child.on('error', (err) => { clearTimeout(timer); reject(err); });
177
+ child.on('close', (code, signal) => {
178
+ clearTimeout(timer);
179
+ if (buf) onLine?.(buf);
180
+ if (code === 0) resolve({ stdout: tail });
181
+ else reject(new Error(`docker build exited with ${code ?? signal}: ${tail.slice(-2000)}`));
182
+ });
183
+ });
184
+
89
185
  /** Validate the agent list: non-empty array of known names, no duplicates. */
90
186
  export function validateRunnerAgents(agents: unknown): string[] {
91
187
  if (!Array.isArray(agents) || agents.length === 0) {
@@ -192,9 +288,11 @@ export function stageBuildContext(
192
288
  export async function rebuildRunnerImage(
193
289
  image: string,
194
290
  options: RunnerBuildOptions = {},
195
- exec: DockerExec = execFileAsync as unknown as DockerExec
291
+ exec: DockerExec = spawnDocker,
292
+ onProgress?: (progress: BuildProgress) => void
196
293
  ): Promise<void> {
197
- const { agents, skip_az, skip_gh, config_dir, credentials_file, data_dir, ...versions } = options;
294
+ const { agents, skip_az, skip_gh, tools, apt_extra, config_dir, credentials_file, data_dir, on_progress, ...versions } = options;
295
+ onProgress = onProgress ?? on_progress;
198
296
  const args: string[] = ['build', '--pull'];
199
297
  if ((versions.hc === undefined) !== (versions.hc_sha256 === undefined)) {
200
298
  throw new InvalidVersionError("'hc' and 'hc_sha256' go together: a new hc version needs its checksum");
@@ -233,16 +331,36 @@ export async function rebuildRunnerImage(
233
331
  args.push('--build-arg', `AGENTS=${agentList.join(',')}`);
234
332
  if (skip_az !== undefined) args.push('--build-arg', `SKIP_AZ=${skip_az ? '1' : '0'}`);
235
333
  if (skip_gh !== undefined) args.push('--build-arg', `SKIP_GH=${skip_gh ? '1' : '0'}`);
334
+ let toolList: string[];
335
+ let aptList: string[];
336
+ try {
337
+ toolList = tools === undefined ? [...DEFAULT_TOOLS] : validateToolGroups(tools);
338
+ aptList = apt_extra === undefined ? [] : validateAptExtra(apt_extra);
339
+ } catch (err) {
340
+ throw new InvalidBuildOptionsError((err as Error).message);
341
+ }
342
+ args.push('--build-arg', `TOOLS=${toolList.join(',')}`);
343
+ args.push('--build-arg', `RECIPE=${runnerRecipeHash()}`);
344
+ args.push('--build-arg', `APT_EXTRA=${aptList.join(',')}`);
236
345
  if ((config_dir !== undefined || credentials_file !== undefined) && !data_dir) {
237
346
  throw new InvalidBuildOptionsError("'data_dir' is required to stage config or credentials");
238
347
  }
239
348
 
240
349
  const cleanup = stageBuildContext(runnerBuildContext, { config_dir, credentials_file, data_dir });
241
350
  try {
351
+ let progress: BuildProgress = { step: 0, total: 0, detail: 'Preparando el build…' };
352
+ onProgress?.(progress);
242
353
  await exec('docker', [...args, '-t', image, runnerBuildContext], {
243
354
  env: { ...process.env, DOCKER_BUILDKIT: '0' },
244
355
  timeout: BUILD_TIMEOUT_MS,
245
356
  maxBuffer: 32 * 1024 * 1024,
357
+ onLine: (line: string) => {
358
+ const next = parseBuildLine(line, progress);
359
+ if (next !== progress) {
360
+ progress = next;
361
+ onProgress?.(progress);
362
+ }
363
+ },
246
364
  });
247
365
  } catch (err) {
248
366
  const detail = err instanceof Error ? err.message : String(err);
@@ -0,0 +1,368 @@
1
+ import { normalizeJiraSite, validateJiraSite } from '../types.ts';
2
+
3
+ export type FetchLike = (
4
+ url: string,
5
+ init: { method: string; headers: Record<string, string>; body?: string; redirect?: string }
6
+ ) => Promise<{ ok: boolean; status: number; text(): Promise<string> }>;
7
+
8
+ /** Ceiling for search pagination (see JiraClient.searchJql). */
9
+ const SEARCH_PAGE_LIMIT = 200;
10
+
11
+ export class JiraApiError extends Error {
12
+ status: number;
13
+ constructor(message: string, status: number) {
14
+ super(message);
15
+ this.name = 'JiraApiError';
16
+ this.status = status;
17
+ }
18
+ }
19
+
20
+ /**
21
+ * Escapes a JQL string literal: backslash FIRST, then the double quote (a trailing
22
+ * backslash would otherwise escape the closing quote and swallow the rest of the JQL).
23
+ */
24
+ export function jqlStringLiteral(value: string): string {
25
+ return value.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
26
+ }
27
+
28
+ export interface JiraIssueItem {
29
+ key: string;
30
+ summary: string;
31
+ description: string;
32
+ url: string;
33
+ project?: string;
34
+ project_name?: string;
35
+ status?: string;
36
+ updated_at?: string;
37
+ labels?: string[];
38
+ ready?: boolean;
39
+ }
40
+
41
+ /**
42
+ * Converts Atlassian Document Format (ADF) tree into clean readable plain text.
43
+ * Handles paragraphs, headings, bullet/ordered lists, code blocks, blockquotes, breaks.
44
+ */
45
+ export function adfToPlainText(doc: unknown): string {
46
+ if (!doc) return '';
47
+ if (typeof doc === 'string') return doc.trim();
48
+ if (typeof doc !== 'object') return String(doc);
49
+
50
+ function renderInline(node: unknown): string {
51
+ if (!node || typeof node !== 'object') return '';
52
+ const n = node as Record<string, unknown>;
53
+ if (n.type === 'text') return String(n.text ?? '');
54
+ if (n.type === 'hardBreak') return '\n';
55
+ if (n.type === 'mention') {
56
+ const attrs = n.attrs as Record<string, unknown> | undefined;
57
+ return String(attrs?.text ?? attrs?.id ?? '@user');
58
+ }
59
+ if (n.type === 'inlineCard') {
60
+ const attrs = n.attrs as Record<string, unknown> | undefined;
61
+ return String(attrs?.url ?? '');
62
+ }
63
+ if (n.type === 'emoji') {
64
+ const attrs = n.attrs as Record<string, unknown> | undefined;
65
+ return String(attrs?.text ?? attrs?.shortName ?? '');
66
+ }
67
+ if (Array.isArray(n.content)) {
68
+ return n.content.map(renderInline).join('');
69
+ }
70
+ return '';
71
+ }
72
+
73
+ function renderBlock(node: unknown, indent = ''): string {
74
+ if (!node || typeof node !== 'object') return '';
75
+ const n = node as Record<string, unknown>;
76
+ const type = String(n.type ?? '');
77
+
78
+ if (type === 'paragraph') {
79
+ const inner = Array.isArray(n.content) ? n.content.map(renderInline).join('') : '';
80
+ return `${indent}${inner}\n\n`;
81
+ }
82
+
83
+ if (type === 'heading') {
84
+ const attrs = n.attrs as Record<string, unknown> | undefined;
85
+ const level = Math.min(6, Math.max(1, Number(attrs?.level) || 1));
86
+ const prefix = '#'.repeat(level);
87
+ const inner = Array.isArray(n.content) ? n.content.map(renderInline).join('') : '';
88
+ return `${indent}${prefix} ${inner}\n\n`;
89
+ }
90
+
91
+ if (type === 'codeBlock') {
92
+ const attrs = n.attrs as Record<string, unknown> | undefined;
93
+ const lang = attrs?.language ? String(attrs.language) : '';
94
+ const code = Array.isArray(n.content) ? n.content.map(renderInline).join('') : '';
95
+ return `${indent}\`\`\`${lang}\n${code}\n${indent}\`\`\`\n\n`;
96
+ }
97
+
98
+ if (type === 'blockquote') {
99
+ const inner = Array.isArray(n.content) ? n.content.map((c) => renderBlock(c, '')).join('') : '';
100
+ const lines = inner.trim().split('\n').map((l) => `${indent}> ${l}`).join('\n');
101
+ return `${lines}\n\n`;
102
+ }
103
+
104
+ if (type === 'bulletList') {
105
+ if (!Array.isArray(n.content)) return '';
106
+ const items = n.content.map((item) => {
107
+ const itemObj = item as Record<string, unknown>;
108
+ const content = Array.isArray(itemObj.content)
109
+ ? itemObj.content.map((c) => renderBlock(c, '').trim()).filter(Boolean).join('\n')
110
+ : '';
111
+ return `${indent}- ${content}`;
112
+ });
113
+ return items.join('\n') + '\n\n';
114
+ }
115
+
116
+ if (type === 'orderedList') {
117
+ if (!Array.isArray(n.content)) return '';
118
+ const items = n.content.map((item, index) => {
119
+ const itemObj = item as Record<string, unknown>;
120
+ const content = Array.isArray(itemObj.content)
121
+ ? itemObj.content.map((c) => renderBlock(c, '').trim()).filter(Boolean).join('\n')
122
+ : '';
123
+ return `${indent}${index + 1}. ${content}`;
124
+ });
125
+ return items.join('\n') + '\n\n';
126
+ }
127
+
128
+ if (type === 'rule') {
129
+ return `${indent}---\n\n`;
130
+ }
131
+
132
+ if (Array.isArray(n.content)) {
133
+ return n.content.map((c) => renderBlock(c, indent)).join('');
134
+ }
135
+
136
+ return '';
137
+ }
138
+
139
+ const raw = renderBlock(doc);
140
+ return raw.replace(/\n{3,}/g, '\n\n').trim();
141
+ }
142
+
143
+ export class JiraClient {
144
+ private fetchImpl: FetchLike;
145
+
146
+ constructor(fetchImpl: FetchLike = fetch as unknown as FetchLike) {
147
+ this.fetchImpl = fetchImpl;
148
+ }
149
+
150
+ private async call(
151
+ site: string,
152
+ email: string,
153
+ token: string,
154
+ method: string,
155
+ path: string,
156
+ body?: unknown
157
+ ): Promise<{ status: number; data: unknown }> {
158
+ const normSite = normalizeJiraSite(site);
159
+ // Defense in depth (P2 review): Basic auth never leaves for a non-Jira-Cloud host,
160
+ // whatever path produced this call.
161
+ if (!validateJiraSite(normSite)) {
162
+ throw new JiraApiError(
163
+ `Refusing to send Jira credentials to '${normSite}' (only https://<site>.atlassian.net is allowed)`,
164
+ 0
165
+ );
166
+ }
167
+ const auth = Buffer.from(`${email}:${token}`).toString('base64');
168
+ const headers: Record<string, string> = {
169
+ Accept: 'application/json',
170
+ Authorization: `Basic ${auth}`,
171
+ 'User-Agent': 'bond-app',
172
+ };
173
+ if (body !== undefined) {
174
+ headers['Content-Type'] = 'application/json';
175
+ }
176
+
177
+ const res = await this.fetchImpl(`${normSite}${path}`, {
178
+ method,
179
+ headers,
180
+ body: body !== undefined ? JSON.stringify(body) : undefined,
181
+ // Never follow redirects: fetch would forward the Authorization header to the
182
+ // redirect target (Jira Cloud answers 30x on site moves), leaking the token elsewhere.
183
+ redirect: 'manual',
184
+ });
185
+
186
+ if (res.status >= 300 && res.status < 400) {
187
+ throw new JiraApiError(
188
+ `Jira API returned an unexpected redirect (HTTP ${res.status}); not following it`,
189
+ res.status
190
+ );
191
+ }
192
+
193
+ const text = await res.text();
194
+ let data: unknown = null;
195
+ try {
196
+ data = text ? JSON.parse(text) : null;
197
+ } catch {
198
+ data = null;
199
+ }
200
+
201
+ if (!res.ok) {
202
+ const errorData = data as { errorMessages?: string[]; message?: string; errors?: Record<string, string> } | null;
203
+ const msg =
204
+ errorData?.errorMessages?.[0] ||
205
+ errorData?.message ||
206
+ (errorData?.errors ? Object.values(errorData.errors)[0] : undefined) ||
207
+ `Jira API request failed with status ${res.status}`;
208
+ throw new JiraApiError(msg, res.status);
209
+ }
210
+
211
+ return { status: res.status, data };
212
+ }
213
+
214
+ /**
215
+ * Check connection and credentials using GET {site}/rest/api/3/myself
216
+ */
217
+ async myself(
218
+ site: string,
219
+ email: string,
220
+ token: string
221
+ ): Promise<{ displayName: string; emailAddress?: string; accountId?: string }> {
222
+ const { data } = await this.call(site, email, token, 'GET', '/rest/api/3/myself');
223
+ const user = data as { displayName?: string; emailAddress?: string; accountId?: string } | null;
224
+ if (!user || typeof user.displayName !== 'string') {
225
+ throw new JiraApiError('Invalid user profile response from Jira', 502);
226
+ }
227
+ return {
228
+ displayName: user.displayName,
229
+ emailAddress: user.emailAddress,
230
+ accountId: user.accountId,
231
+ };
232
+ }
233
+
234
+ /**
235
+ * One page of POST /rest/api/3/search/jql followed to its end. v3 answers page by
236
+ * page (maxResults, nextPageToken, isLast); we ask for 50 and follow pages up to
237
+ * SEARCH_PAGE_LIMIT (200 issues): more than that is noise for a picker, and the cap
238
+ * keeps the number of requests and the response size bounded.
239
+ */
240
+ private async searchJql(
241
+ site: string,
242
+ email: string,
243
+ token: string,
244
+ jql: string,
245
+ fields: string[]
246
+ ): Promise<Array<Record<string, unknown>>> {
247
+ const issues: Array<Record<string, unknown>> = [];
248
+ const body: Record<string, unknown> = { jql, fields, maxResults: 50 };
249
+ for (;;) {
250
+ const { data } = await this.call(site, email, token, 'POST', '/rest/api/3/search/jql', body);
251
+ const page = (data ?? {}) as { issues?: unknown; isLast?: boolean; nextPageToken?: string };
252
+ if (Array.isArray(page.issues)) issues.push(...(page.issues as Array<Record<string, unknown>>));
253
+ if (issues.length >= SEARCH_PAGE_LIMIT) return issues.slice(0, SEARCH_PAGE_LIMIT);
254
+ if (!page.nextPageToken || page.isLast) return issues;
255
+ body.nextPageToken = page.nextPageToken;
256
+ }
257
+ }
258
+
259
+ private toIssueItem(normSite: string, raw: Record<string, unknown>): JiraIssueItem {
260
+ const key = String(raw.key ?? '');
261
+ const fields = (raw.fields as Record<string, unknown>) ?? {};
262
+ const summary = String(fields.summary ?? '');
263
+ const description = adfToPlainText(fields.description);
264
+ const statusObj = fields.status as { name?: string; statusCategory?: { name?: string; key?: string } } | undefined;
265
+ const projectObj = fields.project as { key?: string; name?: string } | undefined;
266
+ const labels = Array.isArray(fields.labels) ? fields.labels.map(String) : [];
267
+ const statusName = statusObj?.name ? String(statusObj.name) : undefined;
268
+ const ready = labels.includes('ready') || statusName?.toLowerCase() === 'ready';
269
+
270
+ return {
271
+ key,
272
+ summary,
273
+ description,
274
+ url: `${normSite}/browse/${key}`,
275
+ project: projectObj?.key,
276
+ project_name: projectObj?.name,
277
+ status: statusName,
278
+ updated_at: fields.updated ? String(fields.updated) : undefined,
279
+ labels,
280
+ ready,
281
+ };
282
+ }
283
+
284
+ /**
285
+ * List open assigned issues via POST /rest/api/3/search/jql
286
+ * with JQL «assignee = currentUser() AND statusCategory != Done ORDER BY updated DESC»
287
+ */
288
+ async listAssigned(site: string, email: string, token: string): Promise<JiraIssueItem[]> {
289
+ const normSite = normalizeJiraSite(site);
290
+ const jql = 'assignee = currentUser() AND statusCategory != Done ORDER BY updated DESC';
291
+ const issues = await this.searchJql(site, email, token, jql, [
292
+ 'summary', 'description', 'status', 'updated', 'labels', 'project',
293
+ ]);
294
+ return issues.map((raw) => this.toIssueItem(normSite, raw));
295
+ }
296
+
297
+ /**
298
+ * Search Jira issues by text query and/or project key. A query shaped like an issue
299
+ * key (PROJ-123) also searches keys: text ~ never matches the key itself. `mine`
300
+ * keeps only the issues assigned to the credential's user.
301
+ */
302
+ async search(
303
+ site: string,
304
+ email: string,
305
+ token: string,
306
+ opts: { q?: string; project?: string; mine?: boolean } = {}
307
+ ): Promise<JiraIssueItem[]> {
308
+ const normSite = normalizeJiraSite(site);
309
+ const clauses: string[] = [];
310
+
311
+ if (opts.mine) clauses.push('assignee = currentUser()');
312
+ if (opts.project?.trim()) {
313
+ clauses.push(`project = "${jqlStringLiteral(opts.project.trim())}"`);
314
+ }
315
+ if (opts.q?.trim()) {
316
+ const q = opts.q.trim();
317
+ clauses.push(/^[A-Z][A-Z0-9]+-\d+$/.test(q)
318
+ ? `(key = ${q} OR text ~ "${jqlStringLiteral(q)}")`
319
+ : `text ~ "${jqlStringLiteral(q)}"`);
320
+ }
321
+
322
+ // Without a text or a project, only the open ones (the whole site otherwise).
323
+ if (!opts.q?.trim() && !opts.project?.trim()) clauses.push('statusCategory != Done');
324
+ const where = clauses.join(' AND ');
325
+ const jql = `${where} ORDER BY updated DESC`;
326
+
327
+ const issues = await this.searchJql(site, email, token, jql, [
328
+ 'summary', 'description', 'status', 'updated', 'labels', 'project',
329
+ ]);
330
+
331
+ return issues.map((raw) => this.toIssueItem(normSite, raw));
332
+ }
333
+
334
+ /**
335
+ * Get single Jira issue with summary and description converted to plain text.
336
+ */
337
+ async getIssue(
338
+ site: string,
339
+ email: string,
340
+ token: string,
341
+ key: string
342
+ ): Promise<{ key: string; summary: string; description: string; url: string }> {
343
+ const normSite = normalizeJiraSite(site);
344
+ const { data } = await this.call(
345
+ site,
346
+ email,
347
+ token,
348
+ 'GET',
349
+ `/rest/api/3/issue/${encodeURIComponent(key)}?fields=summary,description`
350
+ );
351
+
352
+ const doc = data as { key?: string; fields?: { summary?: string; description?: unknown } } | null;
353
+ if (!doc || !doc.fields) {
354
+ throw new JiraApiError(`Issue '${key}' not found`, 404);
355
+ }
356
+
357
+ const summary = String(doc.fields.summary ?? '');
358
+ const description = adfToPlainText(doc.fields.description);
359
+ const issueKey = doc.key || key;
360
+
361
+ return {
362
+ key: issueKey,
363
+ summary,
364
+ description,
365
+ url: `${normSite}/browse/${issueKey}`,
366
+ };
367
+ }
368
+ }
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Plan bond-app-ajustes-imagen P2: the developer tool groups the runner image can carry
3
+ * (runner/setup.sh --tools). runner/setup.sh has the same list (SUPPORTED_TOOLS) and does
4
+ * the installing; a unit test keeps both in sync. Sizes are rough figures for Ajustes, so
5
+ * the person sees what a heavy group costs before rebuilding. The three defaults were
6
+ * measured together (2026-11-24): about 620 MB on top of the image without tools.
7
+ */
8
+ export interface ToolGroup {
9
+ id: string;
10
+ label: string;
11
+ description: string;
12
+ /** Part of the catalog's default selection. */
13
+ default: boolean;
14
+ /** Rough size it adds to the image, in MB. */
15
+ size_mb: number;
16
+ }
17
+
18
+ export const TOOL_CATALOG: readonly ToolGroup[] = [
19
+ {
20
+ id: 'esenciales',
21
+ label: 'Esenciales para agentes',
22
+ description: 'ripgrep, fd, jq, yq, tree, less, file, zip/unzip, xz, patch, sqlite3, make, build-essential, python3 + venv',
23
+ default: true,
24
+ size_mb: 480,
25
+ },
26
+ { id: 'busqueda', label: 'Búsqueda de código', description: 'ast-grep y shellcheck', default: true, size_mb: 60 },
27
+ {
28
+ id: 'shell',
29
+ label: 'Shell para humanos',
30
+ description: 'zsh + oh-my-zsh (autosuggestions, syntax-highlighting), fzf, bat, delta y starship; solo para el botón Shell',
31
+ default: true,
32
+ size_mb: 80,
33
+ },
34
+ { id: 'python', label: 'Python', description: 'uv (incluye pip, venv y versiones de Python)', default: false, size_mb: 45 },
35
+ { id: 'go', label: 'Go', description: 'toolchain de Go fijado', default: false, size_mb: 250 },
36
+ { id: 'rust', label: 'Rust', description: 'rustup + toolchain estable (perfil mínimo)', default: false, size_mb: 600 },
37
+ { id: 'java', label: 'Java', description: 'Temurin 21 y Maven', default: false, size_mb: 400 },
38
+ { id: 'dotnet', label: '.NET', description: 'SDK 8', default: false, size_mb: 750 },
39
+ { id: 'js', label: 'JS extra', description: 'pnpm y yarn (corepack) y bun', default: false, size_mb: 100 },
40
+ { id: 'db', label: 'Clientes de bases de datos', description: 'postgresql-client y redis-tools', default: false, size_mb: 30 },
41
+ { id: 'cloud', label: 'Cloud', description: 'azure-cli, kubectl y terraform', default: false, size_mb: 1200 },
42
+ {
43
+ id: 'docker',
44
+ label: 'Docker en el run',
45
+ description: 'docker, buildx, compose y la CLI de devcontainers; solo arranca en los tickets con «Docker en el run» (contenedor privilegiado)',
46
+ default: false,
47
+ size_mb: 450,
48
+ },
49
+ ];
50
+
51
+ export const TOOL_IDS: readonly string[] = TOOL_CATALOG.map((g) => g.id);
52
+ export const DEFAULT_TOOLS: readonly string[] = TOOL_CATALOG.filter((g) => g.default).map((g) => g.id);
53
+
54
+ /** Debian package names (lowercase, digits, + - .), as setup.sh checks them. */
55
+ export const APT_PACKAGE_RE = /^[a-z0-9][a-z0-9+.-]{1,62}$/;
56
+ export const APT_EXTRA_MAX = 30;
57
+
58
+ /** Validates a tool group list: known ids, no duplicates (empty is fine: no tools). */
59
+ export function validateToolGroups(tools: unknown): string[] {
60
+ if (!Array.isArray(tools)) throw new TypeError("'tools' must be an array of tool group ids");
61
+ const out: string[] = [];
62
+ for (const t of tools) {
63
+ if (typeof t !== 'string' || !TOOL_IDS.includes(t)) {
64
+ throw new TypeError(`unknown tool group '${String(t)}': the catalog has ${TOOL_IDS.join(', ')}`);
65
+ }
66
+ if (out.includes(t)) throw new TypeError(`duplicate tool group '${t}'`);
67
+ out.push(t);
68
+ }
69
+ // Catalog order, so the same selection always builds (and compares) the same.
70
+ return TOOL_IDS.filter((id) => out.includes(id));
71
+ }
72
+
73
+ /** Validates extra apt packages: Debian names only, deduped, at most APT_EXTRA_MAX. */
74
+ export function validateAptExtra(pkgs: unknown): string[] {
75
+ if (!Array.isArray(pkgs)) throw new TypeError("'apt_extra' must be an array of Debian package names");
76
+ const out: string[] = [];
77
+ for (const p of pkgs) {
78
+ const name = typeof p === 'string' ? p.trim() : '';
79
+ if (!APT_PACKAGE_RE.test(name)) throw new TypeError(`invalid Debian package name '${String(p)}'`);
80
+ if (!out.includes(name)) out.push(name);
81
+ }
82
+ if (out.length > APT_EXTRA_MAX) throw new TypeError(`'apt_extra' takes at most ${APT_EXTRA_MAX} packages`);
83
+ return out.sort();
84
+ }