@jmanuelcorral/bond-app 0.1.4 → 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 (78) hide show
  1. package/README.md +241 -7
  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 +8 -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 +316 -330
  11. package/app/mods/bond-agents/model.js +400 -6
  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 +8 -0
  16. package/app/mods/bond-board/main.js +1054 -366
  17. package/app/mods/bond-board/model.js +138 -17
  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 +8 -0
  30. package/app/mods/bond-settings/main.js +1645 -87
  31. package/app/mods/bond-settings/mod.json +1 -1
  32. package/app/mods/bond-settings/pi-models.js +144 -0
  33. package/app/mods/bond-status/api.js +35 -0
  34. package/app/mods/bond-status/brand.js +53 -2
  35. package/app/mods/bond-status/config.js +8 -0
  36. package/app/mods/bond-status/main.js +37 -15
  37. package/app/mods/bond-status/model.js +19 -1
  38. package/app/mods/bond-tabs/brand.js +53 -2
  39. package/app/mods/bond-tabs/main.js +45 -3
  40. package/app/mods/bond-titlebar/brand.js +53 -2
  41. package/app/mods/bond-titlebar/main.js +115 -55
  42. package/app/mods/bond-titlebar/version.js +3 -0
  43. package/app/themes/bond-dark.json +5 -5
  44. package/app/themes/bond-light.json +5 -5
  45. package/package.json +1 -1
  46. package/runner/Dockerfile +58 -15
  47. package/runner/SPIKE-BOND.md +89 -0
  48. package/runner/build-config/.none +0 -0
  49. package/runner/build-creds/.none +0 -0
  50. package/runner/config.example/README.md +27 -0
  51. package/runner/config.example/pi/models.json +22 -0
  52. package/runner/credentials.example.env +27 -0
  53. package/runner/entrypoint.sh +16 -0
  54. package/runner/setup.sh +927 -0
  55. package/runner/versions.env +61 -0
  56. package/scripts/app-install.ts +64 -1
  57. package/src/cli.ts +53 -3
  58. package/src/config.ts +8 -0
  59. package/src/core/agy-login.ts +682 -0
  60. package/src/core/delivery.ts +3 -1
  61. package/src/core/hub-session.ts +9 -7
  62. package/src/core/orchestrator.ts +1186 -168
  63. package/src/core/repo-host.ts +60 -0
  64. package/src/core/setup.ts +239 -0
  65. package/src/core/watchdog.ts +6 -6
  66. package/src/db/database.ts +55 -1
  67. package/src/db/settings-repo.ts +440 -7
  68. package/src/db/ticket-repo.ts +73 -17
  69. package/src/index.ts +4 -4
  70. package/src/runner/azure-devops-client.ts +163 -0
  71. package/src/runner/docker-client.ts +84 -5
  72. package/src/runner/github-client.ts +146 -0
  73. package/src/runner/hc-client.ts +40 -5
  74. package/src/runner/image-builder.ts +268 -10
  75. package/src/runner/jira-client.ts +368 -0
  76. package/src/runner/tool-catalog.ts +84 -0
  77. package/src/server/app.ts +585 -9
  78. package/src/types.ts +168 -1
@@ -1,9 +1,11 @@
1
1
  import type { DatabaseSync } from 'node:sqlite';
2
2
  import { randomUUID } from 'node:crypto';
3
3
  import { REPO_NAME_RE } from '../core/hub.ts';
4
+ import { azureRepoUrl, parseAzureRepoUrl } from '../core/repo-host.ts';
4
5
  import {
5
6
  validateGitHubUrl,
6
7
  isValidAgent,
8
+ SUPPORTED_AGENTS,
7
9
  validateBranchName,
8
10
  validateVerifyCommands,
9
11
  type Ticket,
@@ -34,6 +36,30 @@ export function repoKey(url: string): string {
34
36
  return url.trim().toLowerCase().replace(/\.git$/, '');
35
37
  }
36
38
 
39
+ /**
40
+ * Plan bond-app-nuevo-ticket (D1): with a linked GitHub issue, the issue names the ticket
41
+ * (`gh-<owner>-<repo>-<n>`) so the ticket, its id and the branch `feat/<id>` trace the issue.
42
+ * Anything that is not a plain GitHub issue URL yields null (uuid id as before).
43
+ */
44
+ export function issueTicketId(issueUrl?: string | null): string | null {
45
+ const url = String(issueUrl ?? '').trim();
46
+ const m = /^https:\/\/github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)\/issues\/([1-9][0-9]*)(?:[#?].*)?$/.exec(url);
47
+ if (m) {
48
+ const slug = (s: string) => s.replace(/[^A-Za-z0-9_.-]/g, '-').replace(/^[-.]+|[-.]+$/g, '');
49
+ const id = `gh-${slug(m[1])}-${slug(m[2])}-${m[3]}`.replace(/\.{2,}/g, '-');
50
+ return id.length <= 80 ? id : null;
51
+ }
52
+ const j = /^https:\/\/([a-zA-Z0-9_-]+)\.atlassian\.net\/browse\/([a-zA-Z0-9_-]+)(?:[#?].*)?$/.exec(url);
53
+ if (j) {
54
+ const slug = (s: string) => s.replace(/[^A-Za-z0-9_.-]/g, '-').replace(/^[-.]+|[-.]+$/g, '');
55
+ // The tenant is part of the id: two sites can share project keys (CORE-1 on two
56
+ // sites are different issues).
57
+ const id = `jira-${slug(j[1].toLowerCase())}-${slug(j[2].toLowerCase())}`.replace(/\.{2,}/g, '-');
58
+ return id.length <= 80 ? id : null;
59
+ }
60
+ return null;
61
+ }
62
+
37
63
  /**
38
64
  * P5: a ticket is exactly one of: a single repo (`repo_url`), a list of repos (`repos`; two
39
65
  * or more make the run create a hub) or an existing hub (`hub_url`, optional `hub_base`).
@@ -93,9 +119,13 @@ export function normalizeLayout(rawInput: LayoutInput): TicketLayout {
93
119
  return { repo_url: repos[0].url, base_branch: repos[0].base_branch, hub_url: null, hub_base: null, repos };
94
120
  }
95
121
 
96
- const repoUrl = String(input.repo_url).trim();
97
- if (!validateGitHubUrl(repoUrl)) {
98
- throw new Error(`Invalid repo_url '${repoUrl}'. Only https://github.com/<owner>/<repo>[.git] URLs are allowed.`);
122
+ // Plan bond-app-azure-jira P1: a single-repo ticket may live on GitHub or Azure Repos
123
+ // (kept in its canonical dev.azure.com form). Hubs and repo lists stay GitHub only.
124
+ const rawRepoUrl = String(input.repo_url).trim();
125
+ const azure = parseAzureRepoUrl(rawRepoUrl);
126
+ const repoUrl = azure ? azureRepoUrl(azure) : rawRepoUrl;
127
+ if (!validateGitHubUrl(repoUrl) && !azure) {
128
+ throw new Error(`Invalid repo_url '${repoUrl}'. Only https://github.com/<owner>/<repo>[.git] or https://dev.azure.com/<org>/<project>/_git/<repo> URLs are allowed.`);
99
129
  }
100
130
  const base = input.base_branch || 'main';
101
131
  if (!validateBranchName(base)) throw new Error(`Invalid base_branch '${base}'`);
@@ -158,7 +188,13 @@ export class TicketRepository {
158
188
 
159
189
  const layout = normalizeLayout(input);
160
190
 
161
- const id = input.id || `ticket-${randomUUID().slice(0, 8)}`;
191
+ // D1: the linked issue decides the id unless one is given explicitly; the same issue
192
+ // cannot back two tickets.
193
+ const derivedId = input.id ? null : issueTicketId(input.issue_url);
194
+ if (derivedId && this.db.prepare('SELECT 1 FROM tickets WHERE id = ?').get(derivedId)) {
195
+ throw new Error(`There is already a ticket for this issue: ${derivedId}`);
196
+ }
197
+ const id = input.id || derivedId || `ticket-${randomUUID().slice(0, 8)}`;
162
198
  const now = new Date().toISOString();
163
199
  const baseBranch = layout.base_branch;
164
200
  const targetBranch = input.target_branch || `feat/${id}`;
@@ -172,14 +208,15 @@ export class TicketRepository {
172
208
  throw new Error("Field 'budget_usd' must be a positive finite number");
173
209
  }
174
210
 
175
- const timeoutMinutes = input.timeout_minutes !== undefined ? Number(input.timeout_minutes) : 20;
176
- if (isNaN(timeoutMinutes) || timeoutMinutes <= 0 || !isFinite(timeoutMinutes)) {
177
- throw new Error("Field 'timeout_minutes' must be a positive finite number");
211
+ // 0 (the default) means no timeout: the watchdog never terminates the run on time.
212
+ const timeoutMinutes = input.timeout_minutes !== undefined ? Number(input.timeout_minutes) : 0;
213
+ if (Number.isNaN(timeoutMinutes) || timeoutMinutes < 0 || !Number.isFinite(timeoutMinutes)) {
214
+ throw new Error("Field 'timeout_minutes' must be a finite number >= 0 (0 = no timeout)");
178
215
  }
179
216
 
180
217
  const agent = input.agent || 'pi';
181
218
  if (!isValidAgent(agent)) {
182
- throw new Error(`Invalid agent '${agent}'. Supported agents are: pi, claude, codex, opencode, copilot, crush, agy`);
219
+ throw new Error(`Invalid agent '${agent}'. Supported agents are: ${SUPPORTED_AGENTS.join(', ')}`);
183
220
  }
184
221
 
185
222
  const repoAgents = normalizeRepoAgents(input.repo_agents);
@@ -192,6 +229,13 @@ export class TicketRepository {
192
229
  if (!validateVerifyCommands(verifyCommands)) {
193
230
  throw new Error("Field 'verify_commands' must be an array of at most 20 non-empty strings");
194
231
  }
232
+ if (input.bondify !== undefined && typeof input.bondify !== 'boolean') {
233
+ throw new Error("Field 'bondify' must be a boolean");
234
+ }
235
+ const bondify = input.bondify !== false;
236
+ if (input.docker !== undefined && typeof input.docker !== 'boolean') {
237
+ throw new Error("Field 'docker' must be a boolean");
238
+ }
195
239
  if (layoutBases(layout).includes(targetBranch)) {
196
240
  throw new Error('target_branch must differ from base_branch: a run only pushes its own branch (P4)');
197
241
  }
@@ -202,8 +246,8 @@ export class TicketRepository {
202
246
  INSERT INTO tickets (
203
247
  id, title, description, repo_url, base_branch, target_branch,
204
248
  budget_usd, timeout_minutes, agent, model, prompt, verify_commands,
205
- hub_url, hub_base, repos, repo_agents, issue_url, story, team_engine, status, created_at, updated_at
206
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
249
+ hub_url, hub_base, repos, repo_agents, issue_url, story, team_engine, bondify, docker, status, created_at, updated_at
250
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
207
251
  `);
208
252
 
209
253
  const teamEngine = input.team_engine === 'herdr' ? 'herdr' : 'hc';
@@ -226,8 +270,10 @@ export class TicketRepository {
226
270
  layout.repos ? JSON.stringify(layout.repos) : null,
227
271
  Object.keys(repoAgents).length ? JSON.stringify(repoAgents) : null,
228
272
  input.issue_url ? String(input.issue_url).trim() : null,
229
- input.story || null,
273
+ input.story ?? null,
230
274
  teamEngine,
275
+ bondify ? 1 : 0,
276
+ input.docker === true ? 1 : 0,
231
277
  status,
232
278
  now,
233
279
  now
@@ -301,7 +347,7 @@ export class TicketRepository {
301
347
  throw new Error("'repo_agents' is for an existing hub; in a list, give each repo its 'agent'");
302
348
  }
303
349
  if (updates.agent !== undefined && !isValidAgent(updates.agent)) {
304
- throw new Error(`Invalid agent '${updates.agent}'. Supported agents are: pi, claude, codex, opencode, copilot, crush, agy`);
350
+ throw new Error(`Invalid agent '${updates.agent}'. Supported agents are: ${SUPPORTED_AGENTS.join(', ')}`);
305
351
  }
306
352
  if (updates.target_branch !== undefined && !validateBranchName(updates.target_branch)) {
307
353
  throw new Error(`Invalid target_branch '${updates.target_branch}'`);
@@ -320,10 +366,16 @@ export class TicketRepository {
320
366
  }
321
367
  if (updates.timeout_minutes !== undefined) {
322
368
  const t = Number(updates.timeout_minutes);
323
- if (isNaN(t) || t <= 0 || !isFinite(t)) {
324
- throw new Error("Field 'timeout_minutes' must be a positive finite number");
369
+ if (Number.isNaN(t) || t < 0 || !Number.isFinite(t)) {
370
+ throw new Error("Field 'timeout_minutes' must be a finite number >= 0 (0 = no timeout)");
325
371
  }
326
372
  }
373
+ if (updates.bondify !== undefined && typeof updates.bondify !== 'boolean') {
374
+ throw new Error("Field 'bondify' must be a boolean");
375
+ }
376
+ if (updates.docker !== undefined && typeof updates.docker !== 'boolean') {
377
+ throw new Error("Field 'docker' must be a boolean");
378
+ }
327
379
 
328
380
  // Preserve status: status is managed via run lifecycle, not arbitrary ticket patch
329
381
  const merged = { ...existing, ...updates, status: existing.status, updated_at: new Date().toISOString() };
@@ -333,7 +385,7 @@ export class TicketRepository {
333
385
  title = ?, description = ?, repo_url = ?, base_branch = ?, target_branch = ?,
334
386
  budget_usd = ?, timeout_minutes = ?, agent = ?, model = ?, prompt = ?,
335
387
  verify_commands = ?, hub_url = ?, hub_base = ?, repos = ?, repo_agents = ?,
336
- issue_url = ?, story = ?, team_engine = ?, status = ?, updated_at = ?
388
+ issue_url = ?, story = ?, team_engine = ?, bondify = ?, docker = ?, status = ?, updated_at = ?
337
389
  WHERE id = ?
338
390
  `);
339
391
 
@@ -354,8 +406,10 @@ export class TicketRepository {
354
406
  layout.repos ? JSON.stringify(layout.repos) : null,
355
407
  Object.keys(repoAgents).length ? JSON.stringify(repoAgents) : null,
356
408
  merged.issue_url ? String(merged.issue_url).trim() : null,
357
- merged.story || null,
409
+ merged.story ?? null,
358
410
  merged.team_engine === 'herdr' ? 'herdr' : 'hc',
411
+ merged.bondify ? 1 : 0,
412
+ merged.docker ? 1 : 0,
359
413
  merged.status,
360
414
  merged.updated_at,
361
415
  id
@@ -382,7 +436,7 @@ export class TicketRepository {
382
436
  title: String(row.title),
383
437
  description: row.description ? String(row.description) : undefined,
384
438
  issue_url: row.issue_url ? String(row.issue_url) : null,
385
- story: row.story ? String(row.story) : null,
439
+ story: row.story === null || row.story === undefined ? null : String(row.story),
386
440
  repo_url: repoUrl,
387
441
  base_branch: baseBranch,
388
442
  hub_url: hubUrl,
@@ -398,6 +452,8 @@ export class TicketRepository {
398
452
  prompt: row.prompt ? String(row.prompt) : undefined,
399
453
  verify_commands: parseVerifyCommands(row.verify_commands),
400
454
  team_engine: (row.team_engine === 'hc' ? 'hc' : 'herdr') as 'hc' | 'herdr',
455
+ bondify: row.bondify !== null && row.bondify !== undefined ? Number(row.bondify) !== 0 : true,
456
+ docker: Number(row.docker ?? 0) !== 0,
401
457
  status: row.status as RunState,
402
458
  created_at: String(row.created_at),
403
459
  updated_at: String(row.updated_at),
package/src/index.ts CHANGED
@@ -7,16 +7,16 @@ import { SettingsRepository } from './db/settings-repo.ts';
7
7
  import { EventBus } from './sse/event-bus.ts';
8
8
  import { DockerClient } from './runner/docker-client.ts';
9
9
  import { Orchestrator } from './core/orchestrator.ts';
10
- import { createServer } from './server/app.ts';
10
+ import { createServer, type ServerHooks } from './server/app.ts';
11
11
 
12
- export async function bootstrap(configOverrides = {}) {
12
+ export async function bootstrap(configOverrides = {}, hooks: ServerHooks = {}) {
13
13
  const config = loadConfig(configOverrides);
14
14
  const db = initDatabase(config.dbPath);
15
15
 
16
16
  const ticketRepo = new TicketRepository(db);
17
17
  const runRepo = new RunRepository(db);
18
18
  const eventRepo = new EventRepository(db);
19
- const settingsRepo = new SettingsRepository(db);
19
+ const settingsRepo = new SettingsRepository(db, config.dataDir);
20
20
  const eventBus = new EventBus(eventRepo);
21
21
  const dockerClient = new DockerClient();
22
22
 
@@ -31,7 +31,7 @@ export async function bootstrap(configOverrides = {}) {
31
31
 
32
32
  await orchestrator.start();
33
33
 
34
- const server = createServer(orchestrator);
34
+ const server = createServer(orchestrator, hooks);
35
35
 
36
36
  return new Promise<{ server: typeof server; orchestrator: Orchestrator; port: number }>((resolve) => {
37
37
  server.listen(config.port, config.host, () => {
@@ -0,0 +1,163 @@
1
+ /**
2
+ * Plan bond-app-azure-jira P1: the Azure DevOps REST calls bond-app makes from the host
3
+ * with the user's PAT (Basic auth, empty user): check the credential, open the pull
4
+ * request of a delivered branch, and check or delete that branch when the ticket goes.
5
+ * Never in argv, env or logs; the push itself happens in the container (delivery.ts).
6
+ */
7
+ import type { FetchLike, PullRequest } from './github-client.ts';
8
+ import { parseAzureRepoUrl, type AzureRepoRef } from '../core/repo-host.ts';
9
+
10
+ const API = 'api-version=7.1';
11
+
12
+ export class AzureDevOpsApiError extends Error {
13
+ status: number;
14
+ constructor(message: string, status: number) {
15
+ super(message);
16
+ this.name = 'AzureDevOpsApiError';
17
+ this.status = status;
18
+ }
19
+ }
20
+
21
+ /** https://dev.azure.com/<org> (trailing slash and the older visualstudio.com form accepted). */
22
+ export function normalizeAzureOrgUrl(raw: string): string | null {
23
+ const u = String(raw ?? '').trim().replace(/\/+$/, '');
24
+ const dev = /^https:\/\/dev\.azure\.com\/([A-Za-z0-9][A-Za-z0-9_.-]{0,99})$/.exec(u);
25
+ if (dev) return `https://dev.azure.com/${dev[1]}`;
26
+ const vs = /^https:\/\/([A-Za-z0-9][A-Za-z0-9_.-]{0,99})\.visualstudio\.com$/.exec(u);
27
+ if (vs) return `https://dev.azure.com/${vs[1]}`;
28
+ return null;
29
+ }
30
+
31
+ export class AzureDevOpsClient {
32
+ private fetchImpl: FetchLike;
33
+
34
+ constructor(fetchImpl: FetchLike = fetch as unknown as FetchLike) {
35
+ this.fetchImpl = fetchImpl;
36
+ }
37
+
38
+ private async call(pat: string, method: string, url: string, body?: unknown): Promise<{ status: number; data: unknown }> {
39
+ const res = await this.fetchImpl(url, {
40
+ method,
41
+ headers: {
42
+ Accept: 'application/json',
43
+ Authorization: `Basic ${Buffer.from(`:${pat}`).toString('base64')}`,
44
+ 'User-Agent': 'bond-app',
45
+ ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),
46
+ },
47
+ body: body !== undefined ? JSON.stringify(body) : undefined,
48
+ });
49
+ const text = await res.text();
50
+ let data: unknown = null;
51
+ try {
52
+ data = text ? JSON.parse(text) : null;
53
+ } catch {
54
+ data = null;
55
+ }
56
+ return { status: res.status, data };
57
+ }
58
+
59
+ private repoApi(ref: AzureRepoRef, tail: string): string {
60
+ return `${ref.orgUrl}/${ref.project}/_apis/git/repositories/${ref.repo}${tail}`;
61
+ }
62
+
63
+ private ref(repoUrl: string): AzureRepoRef {
64
+ const ref = parseAzureRepoUrl(repoUrl);
65
+ if (!ref) throw new AzureDevOpsApiError(`Not an Azure Repos URL: '${repoUrl}'`, 400);
66
+ return ref;
67
+ }
68
+
69
+ /**
70
+ * Who the PAT belongs to in that organization (connectionData). Throws a clear error on
71
+ * a wrong PAT or organization: the caller shows it in Ajustes.
72
+ */
73
+ async whoAmI(pat: string, orgUrl: string): Promise<{ name: string; email?: string }> {
74
+ const res = await this.call(pat, 'GET', `${orgUrl}/_apis/connectionData?${API}-preview`);
75
+ const user = (res.data as { authenticatedUser?: { providerDisplayName?: string; properties?: { Account?: { $value?: string } } } } | null)?.authenticatedUser;
76
+ if (res.status !== 200 || !user || !user.providerDisplayName || user.providerDisplayName === 'Anonymous') {
77
+ throw new AzureDevOpsApiError(
78
+ res.status === 401 || res.status === 203 || !user || user?.providerDisplayName === 'Anonymous'
79
+ ? 'Azure DevOps no acepta ese PAT en esa organización'
80
+ : `Azure DevOps respondió ${res.status}`,
81
+ res.status === 200 ? 401 : res.status
82
+ );
83
+ }
84
+ const email = user.properties?.Account?.$value;
85
+ return { name: user.providerDisplayName, ...(email ? { email } : {}) };
86
+ }
87
+
88
+ /**
89
+ * Open the PR `head` -> `base`, or return the active one that already exists for that
90
+ * branch (a delivery retried after a crash must not fail on it).
91
+ */
92
+ async openPullRequest(pat: string, repoUrl: string, pr: { head: string; base: string; title: string; body: string }): Promise<PullRequest> {
93
+ const ref = this.ref(repoUrl);
94
+ const created = await this.call(pat, 'POST', this.repoApi(ref, `/pullrequests?${API}`), {
95
+ sourceRefName: `refs/heads/${pr.head}`,
96
+ targetRefName: `refs/heads/${pr.base}`,
97
+ title: pr.title,
98
+ // Azure caps the description at 4000 characters.
99
+ description: pr.body.length > 4000 ? `${pr.body.slice(0, 3990)}\n…` : pr.body,
100
+ });
101
+ const web = (id: number) => `${ref.orgUrl}/${ref.project}/_git/${ref.repo}/pullrequest/${id}`;
102
+ if (created.status === 201 || created.status === 200) {
103
+ const id = (created.data as { pullRequestId?: number }).pullRequestId!;
104
+ return { number: id, url: web(id), created: true };
105
+ }
106
+ if (created.status === 409) {
107
+ const q = `?searchCriteria.sourceRefName=${encodeURIComponent(`refs/heads/${pr.head}`)}&searchCriteria.targetRefName=${encodeURIComponent(`refs/heads/${pr.base}`)}&searchCriteria.status=active&${API}`;
108
+ const found = await this.call(pat, 'GET', this.repoApi(ref, `/pullrequests${q}`));
109
+ const first = (found.data as { value?: Array<{ pullRequestId: number }> } | null)?.value?.[0];
110
+ if (first) return { number: first.pullRequestId, url: web(first.pullRequestId), created: false };
111
+ }
112
+ const message = (created.data as { message?: string } | null)?.message || `HTTP ${created.status}`;
113
+ throw new AzureDevOpsApiError(`Azure DevOps refused the pull request: ${message}`, created.status);
114
+ }
115
+
116
+ /**
117
+ * The organization's repositories (all projects the PAT sees), for the new-ticket repo
118
+ * search: canonical clone URL, «org / project / repo» and the default branch.
119
+ */
120
+ async listRepositories(pat: string, orgUrl: string): Promise<Array<{ url: string; project: string; name: string; default_branch?: string }>> {
121
+ const res = await this.call(pat, 'GET', `${orgUrl}/_apis/git/repositories?${API}`);
122
+ if (res.status !== 200) throw new AzureDevOpsApiError(`Azure DevOps repositories: HTTP ${res.status}`, res.status);
123
+ const rows = (res.data as { value?: Array<{ name?: string; isDisabled?: boolean; defaultBranch?: string; project?: { name?: string } }> } | null)?.value ?? [];
124
+ const out: Array<{ url: string; project: string; name: string; default_branch?: string }> = [];
125
+ for (const r of rows) {
126
+ if (!r?.name || !r.project?.name || r.isDisabled) continue;
127
+ const url = `${orgUrl}/${encodeURIComponent(r.project.name)}/_git/${encodeURIComponent(r.name)}`;
128
+ const branch = typeof r.defaultBranch === 'string' ? r.defaultBranch.replace(/^refs\/heads\//, '') : undefined;
129
+ out.push({ url, project: r.project.name, name: r.name, ...(branch ? { default_branch: branch } : {}) });
130
+ }
131
+ return out.sort((a, b) => `${a.project}/${a.name}`.localeCompare(`${b.project}/${b.name}`));
132
+ }
133
+
134
+ private async branchSha(pat: string, ref: AzureRepoRef, branch: string): Promise<string | null> {
135
+ const res = await this.call(pat, 'GET', this.repoApi(ref, `/refs?filter=${encodeURIComponent(`heads/${branch}`)}&${API}`));
136
+ if (res.status !== 200) throw new AzureDevOpsApiError(`Azure DevOps refs: HTTP ${res.status}`, res.status);
137
+ const hit = (res.data as { value?: Array<{ name: string; objectId: string }> } | null)?.value?.find((r) => r.name === `refs/heads/${branch}`);
138
+ return hit ? hit.objectId : null;
139
+ }
140
+
141
+ async remoteBranchExists(pat: string, repoUrl: string, branch: string): Promise<boolean> {
142
+ return (await this.branchSha(pat, this.ref(repoUrl), branch)) !== null;
143
+ }
144
+
145
+ /** Whether every commit of `branch` is already in `base` (aheadCount 0). */
146
+ async isBranchMerged(pat: string, repoUrl: string, branch: string, base: string): Promise<boolean> {
147
+ const ref = this.ref(repoUrl);
148
+ const q = `?baseVersion=${encodeURIComponent(base)}&baseVersionType=branch&targetVersion=${encodeURIComponent(branch)}&targetVersionType=branch&$top=1&${API}`;
149
+ const res = await this.call(pat, 'GET', this.repoApi(ref, `/diffs/commits${q}`));
150
+ if (res.status !== 200) return false;
151
+ return (res.data as { aheadCount?: number } | null)?.aheadCount === 0;
152
+ }
153
+
154
+ async deleteRemoteBranch(pat: string, repoUrl: string, branch: string): Promise<boolean> {
155
+ const ref = this.ref(repoUrl);
156
+ const sha = await this.branchSha(pat, ref, branch);
157
+ if (!sha) return false;
158
+ const res = await this.call(pat, 'POST', this.repoApi(ref, `/refs?${API}`), [
159
+ { name: `refs/heads/${branch}`, oldObjectId: sha, newObjectId: '0000000000000000000000000000000000000000' },
160
+ ]);
161
+ return res.status === 200 && Boolean((res.data as { value?: Array<{ success?: boolean }> } | null)?.value?.[0]?.success);
162
+ }
163
+ }
@@ -1,5 +1,8 @@
1
1
  import { execFile, spawn } from 'node:child_process';
2
2
  import { promisify } from 'node:util';
3
+ import type { RunnerImageInfo } from '../types.ts';
4
+ import { parseRunnerManifest, parseRunnerManifestTools } from '../core/setup.ts';
5
+ import { LABEL_RECIPE } from './image-builder.ts';
3
6
 
4
7
  const execFileAsync = promisify(execFile);
5
8
 
@@ -14,6 +17,13 @@ export interface ContainerStartOptions {
14
17
  pidsLimit?: number;
15
18
  securityProfile?: boolean;
16
19
  extraMounts?: string[];
20
+ /**
21
+ * Plan bond-app-ajustes-imagen P4: «Docker en el run». The container runs --privileged
22
+ * with its own anonymous volume for /var/lib/docker (gone with `docker rm -v`, never
23
+ * shared) and BOND_DIND=1, a flag the entrypoint reads to start dockerd. Accepted risk:
24
+ * on Linux such a run can take over the host (decision 2026-11-24).
25
+ */
26
+ docker?: boolean;
17
27
  }
18
28
 
19
29
  export interface ContainerInfo {
@@ -131,9 +141,8 @@ export class DockerClient {
131
141
  });
132
142
  }
133
143
 
134
- async createAndStartContainer(options: ContainerStartOptions): Promise<ContainerInfo> {
144
+ buildRunArgs(options: ContainerStartOptions, network: string): string[] {
135
145
  const containerName = `bond-app-${options.runId}`;
136
- const network = options.network || (await this.createNetwork(options.runId, options.instanceId));
137
146
 
138
147
  const args: string[] = [
139
148
  'run',
@@ -155,10 +164,16 @@ export class DockerClient {
155
164
  // P3 (D19): no published ports. The host reaches the container only with docker exec
156
165
  // (hc machine --via). --init reaps the processes docker exec sessions leave behind.
157
166
  // P7 (Ampliación): BOND_TEAM_NO_TABLE=1 disables bond team's live table.
158
- args.push('--network', network, '--init', '-e', 'BOND_TEAM_NO_TABLE=1');
167
+ // P3 (D-BB): BOND_APP=1 selects hc transport in bond; passed defensively for older runner images.
168
+ args.push('--network', network, '--init', '-e', 'BOND_TEAM_NO_TABLE=1', '-e', 'BOND_APP=1');
169
+
170
+ if (options.docker) {
171
+ // dockerd needs the privileges the hardened profile drops; nothing else changes.
172
+ args.push('--privileged', '-v', '/var/lib/docker', '-e', 'BOND_DIND=1');
173
+ }
159
174
 
160
175
  // Security options: criterion 12
161
- if (options.securityProfile !== false) {
176
+ if (options.securityProfile !== false && !options.docker) {
162
177
  args.push(
163
178
  '--cap-drop=ALL',
164
179
  '--cap-add=CHOWN',
@@ -177,7 +192,8 @@ export class DockerClient {
177
192
  // Resource limits (M2)
178
193
  const cpus = options.cpus ?? 2;
179
194
  const memory = options.memory ?? '2g';
180
- const pidsLimit = options.pidsLimit ?? 200;
195
+ // dockerd and the containers it starts share the run's pid budget.
196
+ const pidsLimit = options.docker ? Math.max(options.pidsLimit ?? 200, 4096) : (options.pidsLimit ?? 200);
181
197
 
182
198
  args.push(`--cpus=${cpus}`, `--memory=${memory}`, `--pids-limit=${pidsLimit}`);
183
199
 
@@ -190,6 +206,15 @@ export class DockerClient {
190
206
  // Image
191
207
  args.push(options.image);
192
208
 
209
+ return args;
210
+ }
211
+
212
+ async createAndStartContainer(options: ContainerStartOptions): Promise<ContainerInfo> {
213
+ const containerName = `bond-app-${options.runId}`;
214
+ const network = options.network || (await this.createNetwork(options.runId, options.instanceId));
215
+
216
+ const args = this.buildRunArgs(options, network);
217
+
193
218
  const { stdout } = await execFileAsync('docker', args);
194
219
  const containerId = stdout.trim();
195
220
 
@@ -389,4 +414,58 @@ export class DockerClient {
389
414
  throw err;
390
415
  }
391
416
  }
417
+
418
+ /**
419
+ * W-P1 (wizard): is the runner image there, and which agents does it bake? Presence is
420
+ * a plain `docker image inspect`; the agent list comes from the /opt/runner-agents
421
+ * manifest (image plan P1) read without booting the image's entrypoint: a throwaway
422
+ * `docker run --rm --network none --entrypoint cat` that no process of a run lives in.
423
+ * An older image without the manifest reports present with no agents. Never logs the
424
+ * manifest content; the manifest carries no secrets by design.
425
+ */
426
+ /** The last manifest read, by image id: reading it costs a `docker run`, and Ajustes
427
+ * asks for the setup state every few seconds (plan bond-app-ajustes-imagen P2). */
428
+ private manifestCache: { id: string; info: RunnerImageInfo } | null = null;
429
+
430
+ async inspectRunnerImage(image: string): Promise<RunnerImageInfo> {
431
+ let id: string;
432
+ let recipe: string | undefined;
433
+ try {
434
+ const { stdout } = await execFileAsync(
435
+ 'docker',
436
+ // The whole Config as JSON: an image without labels has no Labels key at all, and a
437
+ // template that names it (`index`, `.Config.Labels`) fails instead of printing nothing.
438
+ ['image', 'inspect', image, '--format', '{{.Id}} {{json .Config}}'],
439
+ { timeout: 20_000 }
440
+ );
441
+ const out = String(stdout).trim();
442
+ const space = out.indexOf(' ');
443
+ id = space === -1 ? out : out.slice(0, space);
444
+ try {
445
+ const config = JSON.parse(space === -1 ? 'null' : out.slice(space + 1)) as { Labels?: Record<string, string> | null } | null;
446
+ recipe = config?.Labels?.[LABEL_RECIPE] || undefined;
447
+ } catch {
448
+ recipe = undefined;
449
+ }
450
+ } catch {
451
+ return { present: false };
452
+ }
453
+ const withRecipe = (info: RunnerImageInfo): RunnerImageInfo =>
454
+ recipe ? { ...info, recipe } : { ...info };
455
+ if (this.manifestCache && this.manifestCache.id === id) return withRecipe(this.manifestCache.info);
456
+ try {
457
+ const { stdout } = await execFileAsync(
458
+ 'docker',
459
+ ['run', '--rm', '--network', 'none', '--entrypoint', 'cat', image, '/opt/runner-agents'],
460
+ { timeout: 30_000, maxBuffer: 256 * 1024 }
461
+ );
462
+ const agents = parseRunnerManifest(stdout);
463
+ const { tools, apt_extra } = parseRunnerManifestTools(stdout);
464
+ const info: RunnerImageInfo = { present: true, ...(agents.length > 0 ? { agents } : {}), tools, apt_extra };
465
+ this.manifestCache = { id, info };
466
+ return withRecipe(info);
467
+ } catch {
468
+ return withRecipe({ present: true });
469
+ }
470
+ }
392
471
  }