@jmanuelcorral/bond-app 0.1.5 → 0.2.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.
Files changed (80) hide show
  1. package/README.md +280 -23
  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 +376 -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 +1000 -449
  17. package/app/mods/bond-board/model.js +170 -28
  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 +1216 -272
  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 +322 -27
  51. package/src/cli.ts +562 -21
  52. package/src/config.ts +15 -3
  53. package/src/core/agy-login.ts +683 -0
  54. package/src/core/delivery.ts +125 -6
  55. package/src/core/doctor.ts +748 -0
  56. package/src/core/hub-session.ts +108 -91
  57. package/src/core/hub.ts +40 -8
  58. package/src/core/orchestrator.ts +1481 -187
  59. package/src/core/paths.ts +107 -0
  60. package/src/core/permissions.ts +143 -0
  61. package/src/core/pr-source.ts +147 -0
  62. package/src/core/repo-host.ts +60 -0
  63. package/src/core/service-windows.ts +180 -0
  64. package/src/core/service.ts +861 -0
  65. package/src/core/setup-install.ts +1380 -0
  66. package/src/core/setup.ts +62 -1
  67. package/src/core/watchdog.ts +6 -6
  68. package/src/db/database.ts +54 -7
  69. package/src/db/settings-repo.ts +332 -7
  70. package/src/db/ticket-repo.ts +73 -25
  71. package/src/index.ts +4 -4
  72. package/src/runner/azure-devops-client.ts +273 -0
  73. package/src/runner/docker-client.ts +93 -9
  74. package/src/runner/github-client.ts +148 -3
  75. package/src/runner/hc-client.ts +33 -5
  76. package/src/runner/image-builder.ts +123 -5
  77. package/src/runner/jira-client.ts +368 -0
  78. package/src/runner/tool-catalog.ts +84 -0
  79. package/src/server/app.ts +467 -8
  80. package/src/types.ts +140 -2
@@ -1,7 +1,7 @@
1
- import http from 'node:http';
2
1
  import fs from 'node:fs';
3
2
  import os from 'node:os';
4
3
  import path from 'node:path';
4
+ import crypto from 'node:crypto';
5
5
  import { TicketRepository } from '../db/ticket-repo.ts';
6
6
  import { RunRepository } from '../db/run-repo.ts';
7
7
  import { SettingsRepository } from '../db/settings-repo.ts';
@@ -11,8 +11,9 @@ import { Watchdog } from './watchdog.ts';
11
11
  import { CostTracker } from './cost-tracker.ts';
12
12
  import { HcClient, HcError, machineNameForRun, type HcMachineInfo, type HcTerminalDetails } from '../runner/hc-client.ts';
13
13
  import { validateTransition, InvalidStateTransitionError } from './state-machine.ts';
14
- import { rebuildRunnerImage as rebuildRunnerImageImpl, type RunnerBuildOptions, type RunnerVersions } from '../runner/image-builder.ts';
15
- import { GitHubClient, parseGitHubRepo } from '../runner/github-client.ts';
14
+ import { rebuildRunnerImage as rebuildRunnerImageImpl, runnerRecipeHash, type RunnerBuildOptions, type RunnerVersions } from '../runner/image-builder.ts';
15
+ import { GitHubApiError, GitHubClient, parseGitHubRepo } from '../runner/github-client.ts';
16
+ import { JiraClient } from '../runner/jira-client.ts';
16
17
  import {
17
18
  assertHubPushTarget,
18
19
  assertPushTarget,
@@ -26,23 +27,34 @@ import {
26
27
  pullRequestBody,
27
28
  tail,
28
29
  TREE_SCRIPT,
30
+ GIT_SETUP_COMMAND,
31
+ BOND_SYNC_COMMIT_SCRIPT,
29
32
  } from './delivery.ts';
30
33
  import { HubMountError, HubSession, proposeUrls } from './hub-session.ts';
34
+ import { AzureDevOpsApiError, AzureDevOpsClient } from '../runner/azure-devops-client.ts';
35
+ import { azureRepoUrl, parseAzureRepoUrl, repoHostOf, repoLabel, validateRepoUrl } from './repo-host.ts';
36
+ import { parseSourceUrl, type PullRequestHit, type SourceHubInfo, type SourceHubRef, type SourceHubRepoStatus, type SourceInfo, type SourceRef } from './pr-source.ts';
37
+ import { AgyLoginManager, CLAUDE_LOGIN_SPEC, CODEX_LOGIN_SPEC, COPILOT_LOGIN_SPEC, type AgyLoginDriver } from './agy-login.ts';
31
38
  import { buildSetupState } from './setup.ts';
32
- import { HUB_DIR, NAME_RE, agentGaps, analysisPrompt, buildAnalysis, fixedGaps, parseAgentAnswer, repoNameFromUrl, teamAgentFor, teamAgents, type HubToml } from './hub.ts';
39
+ import { HUB_DIR, NAME_RE, agentGaps, analysisPrompt, buildAnalysis, fixedGaps, parseAgentAnswer, parseHubToml, repoNameFromUrl, teamAgentFor, teamAgents, type HubToml } from './hub.ts';
33
40
  import {
34
41
  validateGitHubUrl,
35
42
  validateGitHubIssueUrl,
36
43
  parseGitHubIssueUrl,
44
+ validateJiraIssueUrl,
45
+ parseJiraIssueUrl,
46
+ normalizeJiraSite,
37
47
  isValidAgent,
38
48
  type HubAnalysis,
39
49
  type HubFix,
40
50
  type RepoDelivery,
41
51
  type Run,
42
52
  type Ticket,
53
+ type CreateTicketInput,
43
54
  type RunState,
44
55
  type FailureReason,
45
56
  type TeamStatusRow,
57
+ type RunTerminal,
46
58
  type RunnerImageInfo,
47
59
  type SetupState,
48
60
  } from '../types.ts';
@@ -101,6 +113,15 @@ export class ValidationError extends Error {
101
113
  * D20: launching needs a GitHub credential (the user's gh session stored from Ajustes) or
102
114
  * an explicit token in the request. The message is shown as is by the launch dialog.
103
115
  */
116
+ /** Plan bond-app-azure-jira P1: a ticket on Azure Repos with no Azure DevOps PAT stored. */
117
+ export class AzureDevOpsCredentialMissingError extends ValidationError {
118
+ code = 'azure_devops_credential_missing';
119
+ constructor() {
120
+ super('No hay credencial de Azure DevOps: añade la organización y el PAT en Ajustes → Azure DevOps antes de lanzar el run');
121
+ this.name = 'AzureDevOpsCredentialMissingError';
122
+ }
123
+ }
124
+
104
125
  export class GitHubCredentialMissingError extends ValidationError {
105
126
  code = 'github_credential_missing';
106
127
  constructor() {
@@ -109,6 +130,21 @@ export class GitHubCredentialMissingError extends ValidationError {
109
130
  }
110
131
  }
111
132
 
133
+ /**
134
+ * Plan bond-app-ticket-desde-pr P1: resolving a PR or branch failed; `code` is the API's
135
+ * error (source_invalid, source_not_found, source_fork, source_closed, github_/azure_…).
136
+ */
137
+ export class SourceError extends Error {
138
+ code: string;
139
+ status: number;
140
+ constructor(code: string, status: number, message: string) {
141
+ super(message);
142
+ this.name = 'SourceError';
143
+ this.code = code;
144
+ this.status = status;
145
+ }
146
+ }
147
+
112
148
  export { PushNotAllowedError };
113
149
 
114
150
  export class RebuildInProgressError extends Error {
@@ -132,6 +168,65 @@ export interface TestStartRunOptions extends StartRunOptions {
132
168
  gitInsteadOf?: Record<string, string>;
133
169
  }
134
170
 
171
+ /** E5: the notice of a run whose agent exited with a non-zero code (or was closed). */
172
+ /** Agents that need their own login in Ajustes, and the notice of a run without it. */
173
+ export const LOGIN_REQUIRED: Record<string, string> = {
174
+ agy: 'sin sesion agy: haz Login OAuth en Ajustes',
175
+ claude: 'sin sesión claude: haz «Login con Claude» en Ajustes',
176
+ codex: 'sin sesión codex: haz «Login con ChatGPT» en Ajustes → Agentes',
177
+ copilot: 'sin sesión copilot: haz «Login con Copilot» en Ajustes → Agentes',
178
+ };
179
+
180
+ /** The agent says it has no valid session (agy signed out; claude's token missing, expired
181
+ * or revoked). */
182
+ export function signedOutOn(agent: string, screen: string): boolean {
183
+ if (agent === 'agy') return screen.includes('You are currently not signed in');
184
+ if (agent === 'claude') {
185
+ return /Not logged in|Please run \/login|Invalid API key|OAuth token (has expired|has been revoked|revoked)|authentication_error|Failed to authenticate/i.test(screen);
186
+ }
187
+ if (agent === 'codex') {
188
+ // Its welcome screen without a session, or a session it could not refresh.
189
+ return /Sign in with ChatGPT|Please (log|sign) in again|could not be refreshed|refresh token (was )?(already used|revoked|expired)|Not logged in/i.test(screen);
190
+ }
191
+ if (agent === 'copilot') {
192
+ return /Please (run|use) \/login|No authentication information found|not (logged|signed) in to GitHub|Bad credentials|authentication failed/i.test(screen);
193
+ }
194
+ return false;
195
+ }
196
+
197
+ /** A ticket asks for Docker in the run and the runner image does not carry it. */
198
+ export const DOCKER_REQUIRED = 'el ticket pide Docker y la imagen no lo lleva: marca «Docker en el run» en Ajustes → Imagen y reconstruye';
199
+
200
+ /** What AGENT_ENV_SCRIPT holds: it exports every agent-env.d/*.env of the user. */
201
+ export const AGENT_ENV_SCRIPT_BODY = [
202
+ '# bond-app: credenciales para los agentes del run (plan bond-app-azure-jira P0).',
203
+ '# Lo carga el arranque del core de hc (viaCommandFor): lo heredan todas sus terminales.',
204
+ 'for _bond_env in "$HOME"/.config/bond-app/agent-env.d/*.env; do',
205
+ ' [ -r "$_bond_env" ] && . "$_bond_env"',
206
+ 'done',
207
+ 'unset _bond_env',
208
+ '',
209
+ ].join('\n');
210
+
211
+ /**
212
+ * One agent-env file: `export NAME='value'` lines, shell-quoted. Names are upper-case
213
+ * identifiers; values may not carry newlines or NUL (they would break the file).
214
+ */
215
+ export function agentEnvFile(source: string, vars: Record<string, string>): string {
216
+ if (!/^[a-z][a-z0-9-]{0,40}$/.test(source)) throw new ValidationError(`Invalid agent env source '${source}'`);
217
+ const lines = [`# bond-app: ${source} (no editar: se reescribe en cada run)`];
218
+ for (const [name, value] of Object.entries(vars)) {
219
+ if (!/^[A-Z_][A-Z0-9_]{0,63}$/.test(name)) throw new ValidationError(`Invalid variable name '${name}'`);
220
+ if (/[\n\r\0]/.test(value)) throw new ValidationError(`Variable '${name}' cannot contain line breaks`);
221
+ lines.push(`export ${name}='${value.replace(/'/g, `'\\''`)}'`);
222
+ }
223
+ return lines.join('\n') + '\n';
224
+ }
225
+
226
+ export function agentExitedReason(exitCode: number | null | undefined): string {
227
+ return `El agente se cerró (código ${exitCode ?? '?'}): escríbele para relanzarlo o márcalo terminado`;
228
+ }
229
+
135
230
  export class Orchestrator {
136
231
  public ticketRepo: TicketRepository;
137
232
  public runRepo: RunRepository;
@@ -145,6 +240,8 @@ export class Orchestrator {
145
240
  public hcClient: HcClient;
146
241
  // P4: opens the run's pull request with the GitHub REST API (token in the header only).
147
242
  public github: GitHubClient;
243
+ /** Plan bond-app-azure-jira P1: Azure Repos (PR and branches) with the stored PAT. */
244
+ public azure: AzureDevOpsClient = new AzureDevOpsClient();
148
245
 
149
246
  private reconcileTimer: NodeJS.Timeout | null = null;
150
247
  private inFlightTerminations = new Set<string>();
@@ -168,6 +265,17 @@ export class Orchestrator {
168
265
  private missingContainerStrikes = new Map<string, number>();
169
266
  // P2 criterion 7: guard against concurrent image rebuilds.
170
267
  private rebuildInFlight = false;
268
+ /** The current or last image build, for Ajustes' progress bar (GET /system/rebuild). */
269
+ private rebuildStatus: {
270
+ running: boolean;
271
+ started_at: string | null;
272
+ finished_at: string | null;
273
+ step: number;
274
+ total: number;
275
+ detail: string;
276
+ ok: boolean | null;
277
+ error: string | null;
278
+ } = { running: false, started_at: null, finished_at: null, step: 0, total: 0, detail: '', ok: null, error: null };
171
279
  private rebuildImpl: (image: string, options?: RunnerBuildOptions) => Promise<void>;
172
280
  // P4: deliveries in progress (verify, commit, push, PR), one per run.
173
281
  private deliveries = new Map<string, Promise<Run>>();
@@ -182,8 +290,14 @@ export class Orchestrator {
182
290
  private approving = new Set<string>();
183
291
  // P5 review M-2: a person's instructions for the hub agent («Desbloquear»), per run.
184
292
  private analysisNotes = new Map<string, string>();
185
- // P7: per-run local socket server for 'bond-app pr' channel
186
- private runServers = new Map<string, { server: http.Server; socketDir: string }>();
293
+ // P7 / D6-rev (2026-11-25): per-run long-lived docker exec FIFO watcher for 'bond-app pr' channel
294
+ private runPrWatchers = new Map<string, { token: string; stop: () => void }>();
295
+ public agyLoginManager: AgyLoginManager;
296
+ /** Plan bond-app-claude-agente P2: `claude setup-token` in a throwaway container. */
297
+ public claudeLoginManager: AgyLoginManager;
298
+ public codexLoginManager: AgyLoginManager;
299
+ public copilotLoginManager: AgyLoginManager;
300
+ public jira: JiraClient;
187
301
 
188
302
  constructor(
189
303
  ticketRepo: TicketRepository,
@@ -195,9 +309,12 @@ export class Orchestrator {
195
309
  // P2 criterion 7: injectable for tests; the real docker build is never run in unit/UI tests.
196
310
  rebuildImpl: (image: string, options?: RunnerBuildOptions) => Promise<void> = rebuildRunnerImageImpl,
197
311
  hcClient: HcClient = new HcClient(),
198
- github: GitHubClient = new GitHubClient()
312
+ github: GitHubClient = new GitHubClient(),
313
+ agyLoginDriver?: AgyLoginDriver,
314
+ jira: JiraClient = new JiraClient()
199
315
  ) {
200
316
  this.github = github;
317
+ this.jira = jira;
201
318
  this.rebuildImpl = rebuildImpl;
202
319
  this.hcClient = hcClient;
203
320
  this.ticketRepo = ticketRepo;
@@ -209,6 +326,40 @@ export class Orchestrator {
209
326
  this.watchdog = new Watchdog(runRepo, ticketRepo, config.watchdogIntervalMs);
210
327
  this.watchdog.setOrchestrator(this);
211
328
  this.costTracker = new CostTracker(runRepo, eventBus);
329
+ this.agyLoginManager = new AgyLoginManager({
330
+ runnerImage: config.runnerImage,
331
+ dataDir: config.dataDir,
332
+ driver: agyLoginDriver,
333
+ });
334
+ this.claudeLoginManager = new AgyLoginManager({
335
+ runnerImage: config.runnerImage,
336
+ dataDir: config.dataDir,
337
+ driver: agyLoginDriver,
338
+ spec: CLAUDE_LOGIN_SPEC,
339
+ // The one-year token is the credential: kept like any other, injected per run (D7).
340
+ onToken: (token) => this.settingsRepo.setCredential('claude', token, 'setup-token'),
341
+ });
342
+ // Plan bond-app-codex-copilot: the ChatGPT session and copilot's token, kept like any
343
+ // credential and injected per run by stdin (D7).
344
+ this.codexLoginManager = new AgyLoginManager({
345
+ runnerImage: config.runnerImage,
346
+ dataDir: config.dataDir,
347
+ driver: agyLoginDriver,
348
+ spec: CODEX_LOGIN_SPEC,
349
+ maxDurationMs: 15 * 60 * 1000,
350
+ onToken: (content) => this.settingsRepo.setCredential('codex', content, 'chatgpt'),
351
+ });
352
+ this.copilotLoginManager = new AgyLoginManager({
353
+ runnerImage: config.runnerImage,
354
+ dataDir: config.dataDir,
355
+ driver: agyLoginDriver,
356
+ spec: COPILOT_LOGIN_SPEC,
357
+ maxDurationMs: 15 * 60 * 1000,
358
+ onToken: (content) => this.settingsRepo.setCredential('copilot', content, 'copilot-login'),
359
+ });
360
+ if (this.config.dataDir) {
361
+ this.settingsRepo.setDataDir(this.config.dataDir);
362
+ }
212
363
  }
213
364
 
214
365
  async start(): Promise<void> {
@@ -230,11 +381,14 @@ export class Orchestrator {
230
381
  clearInterval(this.reconcileTimer);
231
382
  this.reconcileTimer = null;
232
383
  }
233
- for (const [, s] of this.runServers.entries()) {
234
- try { s.server.close(); } catch {}
235
- try { fs.rmSync(s.socketDir, { recursive: true, force: true }); } catch {}
384
+ await this.agyLoginManager.cancel();
385
+ await this.claudeLoginManager.cancel();
386
+ await this.codexLoginManager.cancel();
387
+ await this.copilotLoginManager.cancel();
388
+ for (const [, w] of this.runPrWatchers.entries()) {
389
+ try { w.stop(); } catch {}
236
390
  }
237
- this.runServers.clear();
391
+ this.runPrWatchers.clear();
238
392
  }
239
393
 
240
394
  /**
@@ -249,17 +403,16 @@ export class Orchestrator {
249
403
  case 'pi':
250
404
  return '/home/runner/.pi/agent/models.json';
251
405
  case 'claude':
252
- return '/home/runner/.claude/config.json';
406
+ // The `claude setup-token` token; the image's claude wrapper reads it (decision 2026-11-23).
407
+ return '/home/runner/.claude/oauth-token';
253
408
  case 'codex':
254
- return '/home/runner/.codex/config.json';
255
- case 'opencode':
256
- return '/home/runner/.opencode/config.json';
409
+ // The ChatGPT session of `codex login` (plan bond-app-codex-copilot).
410
+ return '/home/runner/.codex/auth.json';
257
411
  case 'copilot':
412
+ // `copilot login`'s token file (authTokens); its settings.json is baked, never overwritten.
258
413
  return '/home/runner/.copilot/config.json';
259
- case 'crush':
260
- return '/home/runner/.crush/config.json';
261
414
  case 'agy':
262
- return '/home/runner/.gemini/antigravity-cli/config.json';
415
+ return '/home/runner/.gemini/antigravity-cli/antigravity-oauth-token';
263
416
  }
264
417
  }
265
418
 
@@ -267,6 +420,581 @@ export class Orchestrator {
267
420
  * Write each agent's stored credential into the container as runner (0600), under
268
421
  * `home` (the runner's HOME, or the hub agent's throwaway one; review M-1).
269
422
  */
423
+ /** Every agent with a stored credential (same user, same D7 regime). Runs inject all
424
+ * of them because an agent inside a run may delegate to another (bond team in-container). */
425
+ allConfiguredAgents(): string[] {
426
+ return this.settingsRepo.listSummaries()
427
+ .filter((s) => s.configured)
428
+ .map((s) => s.agent);
429
+ }
430
+
431
+ /**
432
+ * Plan bond-app-azure-jira P0: credentials meant for the agents of the run (their MCP
433
+ * servers, skills, delegates), as environment variables. Each source becomes
434
+ * `~/.config/bond-app/agent-env.d/<name>.env` (0600, by stdin) and the script BASH_ENV
435
+ * points at (AGENT_ENV_SCRIPT, the hc core starts with it) exports them all. Never
436
+ * through `docker -e`, arguments or the image (D7).
437
+ */
438
+ agentEnvSources(): Array<{ name: string; vars: Record<string, string> }> {
439
+ const sources: Array<{ name: string; vars: Record<string, string> }> = [];
440
+ // P1: the Azure DevOps PAT, for `az devops`/`az repos` and the user's PR skills.
441
+ const azure = this.settingsRepo.getAzureDevOpsCredential?.();
442
+ if (azure && azure.agents_enabled) {
443
+ sources.push({
444
+ name: 'azure-devops',
445
+ vars: { AZURE_DEVOPS_ORG_URL: azure.org_url, AZURE_DEVOPS_PAT: azure.pat, AZURE_DEVOPS_EXT_PAT: azure.pat },
446
+ });
447
+ }
448
+ // P2: the Jira API token, for the Jira MCP and skills.
449
+ const jiraCred = this.settingsRepo.getJiraCredential();
450
+ if (jiraCred && jiraCred.agents_enabled && jiraCred.site && jiraCred.email && jiraCred.token) {
451
+ sources.push({
452
+ name: 'jira',
453
+ vars: {
454
+ JIRA_URL: jiraCred.site,
455
+ JIRA_USERNAME: jiraCred.email,
456
+ JIRA_API_TOKEN: jiraCred.token,
457
+ },
458
+ });
459
+ }
460
+ return sources;
461
+ }
462
+
463
+ /** The org's Azure repos, cached a few minutes: the repo search asks on every keystroke. */
464
+ private azureReposCache: { org: string; at: number; repos: Array<{ url: string; project: string; name: string; default_branch?: string }> } | null = null;
465
+ private hubTomlCache = new Map<string, { at: number; toml: HubToml | null }>();
466
+
467
+ /**
468
+ * Alta de ticket (Qué · Dónde · Quién): the repos to offer for «Dónde», in this order —
469
+ * favorites (★), recent ones (repos of the user's tickets, newest first), the Azure
470
+ * organization's repos and, with a query, GitHub's search. Each with its host, a label
471
+ * and the default branch when known; `q` filters by words (any order). A source that
472
+ * fails reports its error and the rest still answer.
473
+ */
474
+ async suggestRepos(q: string): Promise<{
475
+ repos: Array<{ url: string; label: string; host: 'github' | 'azure'; base?: string; favorite: boolean; recent: boolean; source: 'favorite' | 'recent' | 'azure' | 'github' }>;
476
+ errors: Record<string, string>;
477
+ }> {
478
+ const words = q.toLowerCase().split(/\s+/).filter(Boolean);
479
+ const matches = (text: string) => words.every((w) => text.toLowerCase().includes(w));
480
+ const key = (url: string) => url.trim().replace(/\.git$/, '').replace(/\/+$/, '').toLowerCase();
481
+ const favorites = this.settingsRepo.getFavoriteRepos();
482
+ const favKeys = new Set(favorites.map(key));
483
+ const recents: string[] = [];
484
+ for (const t of [...this.ticketRepo.list()].sort((a, b) => String(b.updated_at).localeCompare(String(a.updated_at)))) {
485
+ if (t.mode === 'hub' || !t.repo_url || !validateRepoUrl(t.repo_url)) continue;
486
+ if (!recents.some((r) => key(r) === key(t.repo_url))) recents.push(t.repo_url);
487
+ if (recents.length >= 10) break;
488
+ }
489
+ const recentKeys = new Set(recents.map(key));
490
+ const out = new Map<string, { url: string; label: string; host: 'github' | 'azure'; base?: string; favorite: boolean; recent: boolean; source: 'favorite' | 'recent' | 'azure' | 'github' }>();
491
+ const add = (url: string, source: 'favorite' | 'recent' | 'azure' | 'github', base?: string) => {
492
+ const host = repoHostOf(url);
493
+ if (!host) return;
494
+ const k = key(url);
495
+ const prev = out.get(k);
496
+ if (prev) {
497
+ if (base && !prev.base) prev.base = base;
498
+ return;
499
+ }
500
+ const label = repoLabel(url);
501
+ if (!matches(`${label} ${url}`)) return;
502
+ out.set(k, { url, label, host, ...(base ? { base } : {}), favorite: favKeys.has(k), recent: recentKeys.has(k), source });
503
+ };
504
+ for (const u of favorites) add(u, 'favorite');
505
+ for (const u of recents) add(u, 'recent');
506
+ const errors: Record<string, string> = {};
507
+ const azure = this.settingsRepo.getAzureDevOpsCredential();
508
+ if (azure) {
509
+ try {
510
+ if (!this.azureReposCache || this.azureReposCache.org !== azure.org_url || Date.now() - this.azureReposCache.at > 5 * 60_000) {
511
+ this.azureReposCache = { org: azure.org_url, at: Date.now(), repos: await this.azure.listRepositories(azure.pat, azure.org_url) };
512
+ }
513
+ for (const r of this.azureReposCache.repos) add(r.url, 'azure', r.default_branch);
514
+ } catch (err) {
515
+ errors.azure = (err as Error).message;
516
+ }
517
+ }
518
+ const gh = this.settingsRepo.getGitHubToken();
519
+ if (gh && q.trim().length >= 2) {
520
+ try {
521
+ for (const r of await this.github.searchRepos(gh, q.trim())) add(`${r.url}`, 'github', r.default_branch);
522
+ } catch (err) {
523
+ errors.github = (err as Error).message;
524
+ }
525
+ }
526
+ return { repos: [...out.values()].slice(0, 60), errors };
527
+ }
528
+
529
+ /** The token for a source's host: the gh session, or the PAT when the repo is in its org. */
530
+ private sourceToken(ref: SourceRef): string {
531
+ if (ref.host === 'github') {
532
+ const t = this.settingsRepo.getGitHubToken();
533
+ if (!t) throw new SourceError('github_not_configured', 409, 'No hay sesión de GitHub: conéctala en Ajustes');
534
+ return t;
535
+ }
536
+ const t = this.repoAccessFor(ref.repo_url).token;
537
+ if (!t) throw new SourceError('azure_not_configured', 409, 'No hay PAT de Azure DevOps para esa organización: añádelo en Ajustes');
538
+ return t;
539
+ }
540
+
541
+ /** A host error as a SourceError: 401/403 = credential, 404 = not found, else upstream. */
542
+ private sourceApiError(ref: SourceRef, err: unknown): SourceError {
543
+ if (err instanceof SourceError) return err;
544
+ const status = err instanceof GitHubApiError || err instanceof AzureDevOpsApiError ? err.status : 0;
545
+ const host = ref.host === 'github' ? 'github' : 'azure';
546
+ if (status === 401 || status === 403 || status === 203) return new SourceError(`${host}_not_configured`, 409, (err as Error).message);
547
+ if (status === 404) return new SourceError('source_not_found', 404, 'No encuentro esa PR o rama (o la credencial no llega a ese repo)');
548
+ return new SourceError(`${host}_api_error`, 502, (err as Error).message);
549
+ }
550
+
551
+ private canonicalRepoKey(url: string): string {
552
+ const az = parseAzureRepoUrl(url);
553
+ if (az) return azureRepoUrl(az).toLowerCase();
554
+ return url.trim().replace(/\.git$/, '').replace(/\/+$/, '').toLowerCase();
555
+ }
556
+
557
+ /** P5: read and parse `hub.toml` of `repoUrl` at `ref` (cached for 5 minutes). */
558
+ private async fetchHubToml(repoUrl: string, ref?: string): Promise<HubToml | null> {
559
+ const cacheKey = `${this.canonicalRepoKey(repoUrl)}@${ref ?? ''}`;
560
+ const cached = this.hubTomlCache.get(cacheKey);
561
+ if (cached && Date.now() - cached.at <= 5 * 60_000) return cached.toml;
562
+ const host = repoHostOf(repoUrl);
563
+ let raw: string | null = null;
564
+ if (host === 'github') {
565
+ const token = this.settingsRepo.getGitHubToken();
566
+ if (!token) return null;
567
+ const { owner, repo } = parseGitHubRepo(repoUrl);
568
+ raw = await this.github.getHubToml(token, owner, repo, ref);
569
+ } else if (host === 'azure') {
570
+ const token = this.repoAccessFor(repoUrl).token;
571
+ if (!token) return null;
572
+ raw = await this.azure.getHubToml(token, repoUrl, ref);
573
+ }
574
+ let toml: HubToml | null = null;
575
+ if (raw) {
576
+ try {
577
+ toml = parseHubToml(raw, repoUrl);
578
+ } catch {
579
+ toml = null;
580
+ }
581
+ }
582
+ this.hubTomlCache.set(cacheKey, { at: Date.now(), toml });
583
+ return toml;
584
+ }
585
+
586
+ /** P5 (D8): known hubs on the same host that list `repoUrl` in their `hub.toml`. */
587
+ private async findHubsForRepo(repoUrl: string, host: 'github' | 'azure'): Promise<SourceHubRef[]> {
588
+ const targetKey = this.canonicalRepoKey(repoUrl);
589
+ const candidates: string[] = [];
590
+ const seen = new Set<string>([targetKey]);
591
+ const pushCandidate = (u: string | null | undefined) => {
592
+ if (!u || !validateRepoUrl(u)) return;
593
+ if (repoHostOf(u) !== host) return;
594
+ const k = this.canonicalRepoKey(u);
595
+ if (seen.has(k)) return;
596
+ seen.add(k);
597
+ candidates.push(u);
598
+ };
599
+
600
+ if (host === 'azure') {
601
+ const az = this.settingsRepo.getAzureDevOpsCredential();
602
+ const refAz = parseAzureRepoUrl(repoUrl);
603
+ if (az && refAz && refAz.orgUrl.toLowerCase() === az.org_url.toLowerCase()) {
604
+ if (!this.azureReposCache || this.azureReposCache.org !== az.org_url || Date.now() - this.azureReposCache.at > 5 * 60_000) {
605
+ this.azureReposCache = { org: az.org_url, at: Date.now(), repos: await this.azure.listRepositories(az.pat, az.org_url) };
606
+ }
607
+ for (const r of this.azureReposCache.repos) pushCandidate(r.url);
608
+ }
609
+ } else {
610
+ for (const u of this.settingsRepo.getFavoriteRepos()) pushCandidate(u);
611
+ for (const t of [...this.ticketRepo.list()].sort((a, b) => String(b.updated_at).localeCompare(String(a.updated_at)))) {
612
+ pushCandidate(t.hub_url);
613
+ pushCandidate(t.repo_url);
614
+ if (candidates.length >= 25) break;
615
+ }
616
+ }
617
+
618
+ const found: SourceHubRef[] = [];
619
+ for (let i = 0; i < candidates.length; i += 6) {
620
+ const batch = candidates.slice(i, i + 6);
621
+ const results = await Promise.all(batch.map(async (u) => {
622
+ const toml = await this.fetchHubToml(u).catch(() => null);
623
+ if (!toml) return null;
624
+ if (!toml.repos.some((r) => r.url && this.canonicalRepoKey(r.url) === targetKey)) return null;
625
+ return { url: u, name: toml.name || repoLabel(u) };
626
+ }));
627
+ for (const r of results) if (r) found.push(r);
628
+ }
629
+ return found;
630
+ }
631
+
632
+ /** P5 (D6/D8): for each repo in a hub, check whether `branch` exists and has an open PR. */
633
+ private async inspectHubRepos(
634
+ hubUrl: string,
635
+ hubToml: HubToml,
636
+ branch: string,
637
+ knownPr?: { repo_url: string; pr_url: string | null }
638
+ ): Promise<SourceHubInfo> {
639
+ const knownKey = knownPr ? this.canonicalRepoKey(knownPr.repo_url) : '';
640
+ const repos: SourceHubRepoStatus[] = await Promise.all(hubToml.repos.map(async (r): Promise<SourceHubRepoStatus> => {
641
+ if (!r.url || !validateRepoUrl(r.url)) {
642
+ return { name: r.name, url: r.url, base: r.base, branch_exists: false, pr_url: null };
643
+ }
644
+ if (knownPr && this.canonicalRepoKey(r.url) === knownKey) {
645
+ return { name: r.name, url: r.url, base: r.base, branch_exists: true, pr_url: knownPr.pr_url };
646
+ }
647
+ const access = this.repoAccessFor(r.url);
648
+ if (!access.token) {
649
+ return { name: r.name, url: r.url, base: r.base, branch_exists: false, pr_url: null };
650
+ }
651
+ try {
652
+ const pr = access.findPullRequestByHead ? await access.findPullRequestByHead(branch) : null;
653
+ if (pr) return { name: r.name, url: r.url, base: r.base, branch_exists: true, pr_url: pr.url };
654
+ const branch_exists = await access.branchExists(branch);
655
+ return { name: r.name, url: r.url, base: r.base, branch_exists, pr_url: null };
656
+ } catch {
657
+ return { name: r.name, url: r.url, base: r.base, branch_exists: false, pr_url: null };
658
+ }
659
+ }));
660
+ return {
661
+ url: hubUrl,
662
+ name: hubToml.name || repoLabel(hubUrl),
663
+ base: hubToml.base || 'main',
664
+ repos,
665
+ };
666
+ }
667
+
668
+ /**
669
+ * Plan bond-app-ticket-desde-pr P1/P5: what a PR or branch URL holds — repo, branches,
670
+ * state, fork, hub, title and description, plus hub repos & proposed hubs (D8).
671
+ */
672
+ async resolveSource(rawUrl: string, hubUrl?: string): Promise<SourceInfo> {
673
+ const ref = parseSourceUrl(rawUrl);
674
+ if (!ref) throw new SourceError('source_invalid', 400, 'No es la URL de una PR ni de una rama de GitHub o Azure Repos');
675
+ const token = this.sourceToken(ref);
676
+ let info: SourceInfo;
677
+ try {
678
+ if (ref.host === 'github') {
679
+ const { owner, repo } = ref.github!;
680
+ let number = ref.number;
681
+ if (ref.kind === 'branch') number = (await this.github.findOpenPullRequestByHead(token, owner, repo, ref.branch!)) ?? undefined;
682
+ if (number) {
683
+ const pr = await this.github.getPullRequest(token, owner, repo, number);
684
+ const is_hub = pr.is_fork || !pr.head ? false : await this.github.isHub(token, owner, repo, pr.head);
685
+ info = { kind: 'pr', host: 'github', url: pr.url, repo_url: ref.repo_url, repo_label: repoLabel(ref.repo_url), number: pr.number,
686
+ title: pr.title, body: pr.body, head: pr.head, base: pr.base, state: pr.state, draft: pr.draft, is_fork: pr.is_fork, is_hub,
687
+ ...(pr.author ? { author: pr.author } : {}) };
688
+ } else {
689
+ if (!(await this.github.remoteBranchExists(token, owner, repo, ref.branch!))) {
690
+ throw new SourceError('source_not_found', 404, `No existe la rama '${ref.branch}' en ${owner}/${repo}`);
691
+ }
692
+ const [base, is_hub] = await Promise.all([this.github.getDefaultBranch(token, owner, repo), this.github.isHub(token, owner, repo, ref.branch)]);
693
+ info = { kind: 'branch', host: 'github', url: `https://github.com/${owner}/${repo}/tree/${ref.branch}`, repo_url: ref.repo_url,
694
+ repo_label: repoLabel(ref.repo_url), title: ref.branch!, body: '', head: ref.branch!, base, state: 'open', draft: false, is_fork: false, is_hub };
695
+ }
696
+ } else {
697
+ let number = ref.number;
698
+ if (ref.kind === 'branch') number = (await this.azure.findActivePullRequestByHead(token, ref.repo_url, ref.branch!)) ?? undefined;
699
+ if (number) {
700
+ const pr = await this.azure.getPullRequest(token, ref.repo_url, number);
701
+ const is_hub = pr.is_fork || !pr.head ? false : await this.azure.isHub(token, ref.repo_url, pr.head);
702
+ info = { kind: 'pr', host: 'azure', url: pr.url, repo_url: ref.repo_url, repo_label: repoLabel(ref.repo_url), number: pr.number,
703
+ title: pr.title, body: pr.body, head: pr.head, base: pr.base, state: pr.state, draft: pr.draft, is_fork: pr.is_fork, is_hub,
704
+ ...(pr.author ? { author: pr.author } : {}) };
705
+ } else {
706
+ if (!(await this.azure.remoteBranchExists(token, ref.repo_url, ref.branch!))) {
707
+ throw new SourceError('source_not_found', 404, `No existe la rama '${ref.branch}' en ${repoLabel(ref.repo_url)}`);
708
+ }
709
+ const [base, is_hub] = await Promise.all([this.azure.getDefaultBranch(token, ref.repo_url), this.azure.isHub(token, ref.repo_url, ref.branch)]);
710
+ info = { kind: 'branch', host: 'azure', url: `${ref.repo_url}?version=GB${encodeURIComponent(ref.branch!)}`, repo_url: ref.repo_url,
711
+ repo_label: repoLabel(ref.repo_url), title: ref.branch!, body: '', head: ref.branch!, base, state: 'open', draft: false, is_fork: false, is_hub };
712
+ }
713
+ }
714
+ } catch (err) {
715
+ throw this.sourceApiError(ref, err);
716
+ }
717
+
718
+ if (!info.is_fork && info.state === 'open' && info.head) {
719
+ if (info.is_hub) {
720
+ const toml = await this.fetchHubToml(info.repo_url, info.head).catch(() => null);
721
+ if (toml) {
722
+ info.hub = await this.inspectHubRepos(info.repo_url, toml, info.head);
723
+ }
724
+ } else {
725
+ const hubs = await this.findHubsForRepo(info.repo_url, info.host).catch(() => []);
726
+ if (hubs.length > 0) info.hubs = hubs;
727
+ const chosenHubUrl = hubUrl?.trim() || hubs[0]?.url;
728
+ if (chosenHubUrl) {
729
+ const toml = await this.fetchHubToml(chosenHubUrl).catch(() => null);
730
+ if (toml) {
731
+ info.hub = await this.inspectHubRepos(chosenHubUrl, toml, info.head, {
732
+ repo_url: info.repo_url,
733
+ pr_url: info.kind === 'pr' ? info.url : null,
734
+ });
735
+ }
736
+ }
737
+ }
738
+ }
739
+ return info;
740
+ }
741
+
742
+ /**
743
+ * P1 (D7): open PRs to start a ticket from. GitHub: the ones involving the user, or all
744
+ * open ones of `repo` (`owner/repo` or a GitHub URL). Azure: the active ones of the repo
745
+ * (an Azure URL) or of every project of the organization (at most 10). `q` filters by
746
+ * words. Each host reports its own error; the other still answers.
747
+ */
748
+ /** The Azure DevOps user id of the PAT (cached per organization): «mías» / «asignadas a mí». */
749
+ private azureMeCache: { org: string; id: string } | null = null;
750
+ private async azureMe(pat: string, orgUrl: string): Promise<string> {
751
+ if (this.azureMeCache?.org === orgUrl) return this.azureMeCache.id;
752
+ const me = await this.azure.whoAmI(pat, orgUrl);
753
+ if (!me.id) throw new AzureDevOpsApiError('Azure DevOps no devuelve el id del usuario del PAT', 502);
754
+ this.azureMeCache = { org: orgUrl, id: me.id };
755
+ return me.id;
756
+ }
757
+
758
+ async searchPullRequests(q: string, repo?: string, filters: { host?: 'github' | 'azure'; mine?: 'assigned' | 'author' } = {}): Promise<{ items: PullRequestHit[]; errors: Record<string, string> }> {
759
+ const words = q.toLowerCase().split(/\s+/).filter(Boolean);
760
+ const matches = (text: string) => words.every((w) => text.toLowerCase().includes(w));
761
+ const items: PullRequestHit[] = [];
762
+ const errors: Record<string, string> = {};
763
+ const repoArg = String(repo ?? '').trim();
764
+ const ghRepo = /^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/.exec(repoArg) ?? /^https:\/\/github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?\/?$/.exec(repoArg);
765
+ const azRepo = parseAzureRepoUrl(repoArg);
766
+ // Filtro de host (alta «Desde una PR»): solo GitHub o solo Azure.
767
+ const wantGitHub = (!repoArg || Boolean(ghRepo)) && filters.host !== 'azure';
768
+ const wantAzure = (!repoArg || Boolean(azRepo)) && filters.host !== 'github';
769
+
770
+ const gh = this.settingsRepo.getGitHubToken();
771
+ if (wantGitHub && gh) {
772
+ try {
773
+ for (const p of await this.github.searchPullRequests(gh, q, ghRepo ? { owner: ghRepo[1], repo: ghRepo[2] } : undefined, filters.mine)) {
774
+ items.push({ url: p.url, host: 'github', number: p.number, title: p.title, repo_label: `${p.owner}/${p.repo}`,
775
+ ...(p.author ? { author: p.author } : {}), ...(p.updated_at ? { updated_at: p.updated_at } : {}), draft: p.draft });
776
+ }
777
+ } catch (err) {
778
+ errors.github = (err as Error).message;
779
+ }
780
+ } else if (wantGitHub && ghRepo) {
781
+ errors.github = 'github_not_configured';
782
+ }
783
+
784
+ const az = this.settingsRepo.getAzureDevOpsCredential();
785
+ if (wantAzure && az && (!azRepo || azRepo.orgUrl.toLowerCase() === az.org_url.toLowerCase())) {
786
+ try {
787
+ let rows: Awaited<ReturnType<AzureDevOpsClient['listActivePullRequests']>> = [];
788
+ // «Mías» = las que creó el usuario del PAT; «asignadas a mí» = en las que es revisor.
789
+ const me = filters.mine ? await this.azureMe(az.pat, az.org_url) : null;
790
+ const who = filters.mine === 'author' ? { creatorId: me! } : filters.mine === 'assigned' ? { reviewerId: me! } : {};
791
+ if (azRepo) {
792
+ rows = await this.azure.listActivePullRequests(az.pat, az.org_url, { repoUrl: azureRepoUrl(azRepo), ...who });
793
+ } else {
794
+ if (!this.azureReposCache || this.azureReposCache.org !== az.org_url || Date.now() - this.azureReposCache.at > 5 * 60_000) {
795
+ this.azureReposCache = { org: az.org_url, at: Date.now(), repos: await this.azure.listRepositories(az.pat, az.org_url) };
796
+ }
797
+ const projects = [...new Set(this.azureReposCache.repos.map((r) => r.project))].slice(0, 10);
798
+ for (const lists of await Promise.all(projects.map((p) => this.azure.listActivePullRequests(az.pat, az.org_url, { project: encodeURIComponent(p), ...who })))) {
799
+ rows.push(...lists);
800
+ }
801
+ }
802
+ for (const p of rows) {
803
+ const label = repoLabel(p.repo_url);
804
+ if (!matches(`${label} ${p.title} #${p.number} ${p.author ?? ''}`)) continue;
805
+ items.push({ url: p.url, host: 'azure', number: p.number, title: p.title, repo_label: label,
806
+ ...(p.author ? { author: p.author } : {}), ...(p.updated_at ? { updated_at: p.updated_at } : {}), draft: p.draft });
807
+ }
808
+ } catch (err) {
809
+ errors.azure = (err as Error).message;
810
+ }
811
+ } else if (wantAzure && azRepo) {
812
+ errors.azure = 'azure_not_configured';
813
+ }
814
+ items.sort((a, b) => String(b.updated_at ?? '').localeCompare(String(a.updated_at ?? '')));
815
+ return { items: items.slice(0, 60), errors };
816
+ }
817
+
818
+ /**
819
+ * P1 (D3): create a ticket from a PR or branch — resolve it, refuse forks and closed PRs,
820
+ * and take repo, branches, id and, when not given, title and story from it. A hub PR
821
+ * becomes a hub ticket on that hub (GitHub or Azure DevOps).
822
+ */
823
+ async createTicketFromSource(input: CreateTicketInput): Promise<Ticket> {
824
+ const info = await this.resolveSource(String(input.source_pr_url), input.hub_url);
825
+ if (info.is_fork) throw new SourceError('source_fork', 400, 'La PR viene de un fork: bond-app no puede hacer push a su rama');
826
+ if (info.state !== 'open') throw new SourceError('source_closed', 400, `La PR está ${info.state === 'merged' ? 'mergeada' : 'cerrada'}`);
827
+ if (!info.head || !info.base) throw new SourceError('source_invalid', 400, 'La PR no tiene rama de origen o destino');
828
+ let layout: Partial<CreateTicketInput>;
829
+ if (info.is_hub) {
830
+ layout = { hub_url: info.repo_url, hub_base: info.base };
831
+ } else if (input.hub_url) {
832
+ const rawHub = String(input.hub_url).trim();
833
+ const az = parseAzureRepoUrl(rawHub);
834
+ const canonicalHub = az ? azureRepoUrl(az) : rawHub;
835
+ if (!validateGitHubUrl(canonicalHub) && !az) {
836
+ throw new SourceError('ticket_invalid', 400, `URL de hub no válida: '${rawHub}'`);
837
+ }
838
+ const toml = info.hub && this.canonicalRepoKey(info.hub.url) === this.canonicalRepoKey(canonicalHub)
839
+ ? { base: info.hub.base }
840
+ : await this.fetchHubToml(canonicalHub);
841
+ if (!toml) {
842
+ throw new SourceError('ticket_invalid', 400, `El hub '${canonicalHub}' no tiene hub.toml`);
843
+ }
844
+ layout = { hub_url: canonicalHub, hub_base: toml.base || 'main' };
845
+ } else {
846
+ layout = { repo_url: info.repo_url, base_branch: info.base };
847
+ }
848
+ const story = info.kind === 'pr' ? `PR #${info.number}: ${info.title}\n${info.url}\n\n${info.body}`.trim() : undefined;
849
+ const rest = { ...input };
850
+ for (const k of ['repo_url', 'base_branch', 'repos', 'hub_url', 'hub_base', 'target_branch'] as const) delete rest[k];
851
+ try {
852
+ return this.ticketRepo.create({
853
+ ...rest,
854
+ ...layout,
855
+ source_pr_url: info.url,
856
+ target_branch: info.head,
857
+ title: input.title?.trim() ? input.title : info.title || info.head,
858
+ ...(input.story === undefined && story ? { story: story.slice(0, 8000) } : {}),
859
+ } as CreateTicketInput);
860
+ } catch (err) {
861
+ throw new SourceError('ticket_invalid', 400, (err as Error).message);
862
+ }
863
+ }
864
+
865
+ /**
866
+ * Plan bond-app-azure-jira P1: what bond-app needs to act on a repo's host — the token
867
+ * for its clone and push (stdin) and the API calls of the delivery and the ticket's
868
+ * deletion — whether the repo is on GitHub or on Azure Repos. Null token = no credential.
869
+ */
870
+ repoAccessFor(repoUrl: string, runId?: string): {
871
+ host: 'github' | 'azure';
872
+ label: string;
873
+ token: string | null;
874
+ missing: () => ValidationError;
875
+ branchExists: (branch: string) => Promise<boolean>;
876
+ branchMerged: (branch: string, base: string) => Promise<boolean>;
877
+ deleteBranch: (branch: string) => Promise<boolean>;
878
+ findPullRequestByHead?: (branch: string) => Promise<{ number: number; url: string } | null>;
879
+ openPullRequest: (pr: { head: string; base: string; title: string; body: string }) => Promise<{ number: number; url: string; created: boolean }>;
880
+ } {
881
+ const label = repoLabel(repoUrl);
882
+ if (repoHostOf(repoUrl) === 'azure') {
883
+ const cred = this.settingsRepo.getAzureDevOpsCredential();
884
+ const ref = parseAzureRepoUrl(repoUrl)!;
885
+ // A PAT is per organization: a repo of another one gets none (it would leak).
886
+ const token = cred && cred.org_url.toLowerCase() === ref.orgUrl.toLowerCase() ? cred.pat : null;
887
+ return {
888
+ host: 'azure',
889
+ label,
890
+ token,
891
+ missing: () => new AzureDevOpsCredentialMissingError(),
892
+ branchExists: (b) => this.azure.remoteBranchExists(token!, repoUrl, b),
893
+ branchMerged: (b, base) => this.azure.isBranchMerged(token!, repoUrl, b, base),
894
+ deleteBranch: (b) => this.azure.deleteRemoteBranch(token!, repoUrl, b),
895
+ findPullRequestByHead: async (b) => {
896
+ const n = await this.azure.findActivePullRequestByHead(token!, repoUrl, b);
897
+ return n ? { number: n, url: this.azure.pullRequestWebUrl(repoUrl, n) } : null;
898
+ },
899
+ openPullRequest: (pr) => this.azure.openPullRequest(token!, repoUrl, pr),
900
+ };
901
+ }
902
+ const token = (runId ? this.runTokens.get(runId) : undefined) || this.settingsRepo.getGitHubToken() || null;
903
+ const gh = () => parseGitHubRepo(repoUrl);
904
+ return {
905
+ host: 'github',
906
+ label,
907
+ token,
908
+ missing: () => new GitHubCredentialMissingError(),
909
+ branchExists: (b) => this.github.remoteBranchExists(token!, gh().owner, gh().repo, b),
910
+ branchMerged: (b, base) => this.github.isBranchMerged(token!, gh().owner, gh().repo, b, base),
911
+ deleteBranch: (b) => this.github.deleteRemoteBranch(token!, gh().owner, gh().repo, b),
912
+ findPullRequestByHead: async (b) => {
913
+ const { owner, repo } = gh();
914
+ const n = await this.github.findOpenPullRequestByHead(token!, owner, repo, b);
915
+ return n ? { number: n, url: `https://github.com/${owner}/${repo}/pull/${n}` } : null;
916
+ },
917
+ openPullRequest: (pr) => this.github.openPullRequest(token!, repoUrl, pr),
918
+ };
919
+ }
920
+
921
+ /**
922
+ * The person's git identity for a repo's host: on Azure Repos the account the PAT belongs
923
+ * to, else the GitHub login with its noreply address. The delivery signs with it, and the
924
+ * agents' own commits inside the run carry it too (decision 2026-11-25, «mi cuenta»).
925
+ */
926
+ gitIdentityFor(repoUrl: string): { name: string; email: string } {
927
+ const login = this.settingsRepo.getGitHubSummary().login;
928
+ const azureAccount = repoHostOf(repoUrl) === 'azure' ? this.settingsRepo.getAzureDevOpsSummary().account : undefined;
929
+ const azureMatch = azureAccount ? /^(.*?)\s*<([^<>\s]+@[^<>\s]+)>$/.exec(azureAccount) : null;
930
+ const name = azureMatch ? azureMatch[1] : azureAccount || login || 'bond-app';
931
+ const email = azureMatch ? azureMatch[2] : !azureAccount && login ? `${login}@users.noreply.github.com` : 'bond-app@localhost';
932
+ return { name, email };
933
+ }
934
+
935
+ /**
936
+ * Git inside the run (decision 2026-11-25): the person's identity, `push.default=current`
937
+ * with autoSetupRemote, and — with `withCredentials` — a credential helper reading each
938
+ * host's token from a 0600 file (written by stdin, never argv/env/image) plus a pre-push
939
+ * hook that only lets the run's branch through: no other branch, no deletion, no
940
+ * non-fast-forward, nothing under .github/workflows (the delivery's own barriers). The
941
+ * hook is a guardrail, not a lock: the delivery still checks everything on its push.
942
+ * `repos` are the run's checkouts with their base (the hook diffs against it).
943
+ */
944
+ async prepareGit(
945
+ containerName: string,
946
+ ticket: Ticket,
947
+ opts: { repos: Array<{ dir: string; base: string }>; withCredentials: boolean; runId?: string }
948
+ ): Promise<void> {
949
+ const { name, email } = this.gitIdentityFor(ticket.repo_url);
950
+ const creds: Array<{ host: string; token: string }> = [];
951
+ if (opts.withCredentials) {
952
+ const urls = [ticket.repo_url, ticket.hub_url, ...(ticket.repos ?? []).map((r) => r.url)].filter((u): u is string => Boolean(u));
953
+ const seen = new Set<string>();
954
+ for (const url of urls) {
955
+ const host = repoHostOf(url) === 'azure' ? 'dev.azure.com' : repoHostOf(url) === 'github' ? 'github.com' : null;
956
+ if (!host || seen.has(host)) continue;
957
+ const token = this.repoAccessFor(url, opts.runId).token;
958
+ if (token) {
959
+ creds.push({ host, token });
960
+ seen.add(host);
961
+ }
962
+ }
963
+ // A hub run may hold repos of the other host than its own url: GitHub too, when configured.
964
+ if (!seen.has('github.com')) {
965
+ const gh = this.settingsRepo.getGitHubToken();
966
+ if (gh) creds.push({ host: 'github.com', token: gh });
967
+ }
968
+ }
969
+ const config = JSON.stringify({ name, email, branch: ticket.target_branch, repos: opts.repos, creds });
970
+ const res = await this.dockerClient.injectStdin(containerName, GIT_SETUP_COMMAND, config, 'runner', 30_000);
971
+ if (res.exitCode !== 0) {
972
+ const detail = creds.reduce((s, c) => s.split(c.token).join('***'), String(res.stderr || res.stdout));
973
+ throw new Error(`git setup in the run failed (exit ${res.exitCode}): ${detail.slice(0, 300)}`);
974
+ }
975
+ }
976
+
977
+ async prepareAgentEnv(containerName: string, home = '/home/runner', withSources = true): Promise<string[]> {
978
+ const write = async (dest: string, content: string) => {
979
+ const res = await this.dockerClient.injectStdin(
980
+ containerName,
981
+ ['sh', '-c', 'umask 077; mkdir -p "$(dirname "$1")" && cat > "$1"', '--', dest],
982
+ content,
983
+ 'runner'
984
+ );
985
+ if (res.exitCode !== 0) throw new Error(`Agent env injection failed with code ${res.exitCode}: ${res.stderr}`);
986
+ };
987
+ await write(`${home}/.config/bond-app/agent-env.sh`, AGENT_ENV_SCRIPT_BODY);
988
+ const written: string[] = [];
989
+ if (!withSources) return written;
990
+ for (const source of this.agentEnvSources()) {
991
+ const dest = `${home}/.config/bond-app/agent-env.d/${source.name}.env`;
992
+ await write(dest, agentEnvFile(source.name, source.vars));
993
+ written.push(dest);
994
+ }
995
+ return written;
996
+ }
997
+
270
998
  async injectCredentials(containerName: string, agents: string[], home = '/home/runner'): Promise<string[]> {
271
999
  const written: string[] = [];
272
1000
  const wanted = new Set(agents);
@@ -430,7 +1158,7 @@ export class Orchestrator {
430
1158
  }
431
1159
  }
432
1160
 
433
- // P7 (MEDIUM-3): Re-establish Unix socket servers for live runs with Up containers
1161
+ // P7 / D6-rev: Re-establish per-run docker exec FIFO watchers for live runs with Up containers
434
1162
  for (const r of activeRuns) {
435
1163
  if (
436
1164
  r.container_name &&
@@ -438,7 +1166,9 @@ export class Orchestrator {
438
1166
  ['running', 'analyzing', 'verifying', 'blocked', 'waiting', 'finished'].includes(r.state)
439
1167
  ) {
440
1168
  try {
441
- this.ensureRunSocketServer(r.id);
1169
+ if (!this.runPrWatchers.has(r.id)) {
1170
+ await this.ensureRunPrWatcher(r.id, r.container_name);
1171
+ }
442
1172
  } catch {
443
1173
  // ignore
444
1174
  }
@@ -779,8 +1509,10 @@ export class Orchestrator {
779
1509
 
780
1510
  /**
781
1511
  * P4 criterion 6 (P3 debt M-3): a `running` run whose agent terminal finished leaves
782
- * `running` at once: exit code 0 starts the verification and delivery; any other code
783
- * fails the run with `agent_exited`. Without hc (or with the machine lost, which M-1
1512
+ * `running` at once: exit code 0 finishes it; any other code (a crash, or its tab closed
1513
+ * in herdr-app, which ends the terminal) moves it to `waiting` with a notice, keeping the
1514
+ * container and its work: a message (nudge) starts a new agent terminal (plan
1515
+ * bond-app-pestanas-paneles, E5). Without hc (or with the machine lost, which M-1
784
1516
  * fixes) nothing is decided: the next sweep looks again.
785
1517
  */
786
1518
  async checkAgentExits(): Promise<string[]> {
@@ -806,12 +1538,13 @@ export class Orchestrator {
806
1538
  // The run transitions to 'finished'. Container and session stay alive.
807
1539
  if (this.setState(r.id, 'running', 'finished', null, { finished_at: new Date().toISOString() })) {
808
1540
  this.ticketRepo.updateStatus(r.ticket_id, 'finished');
1541
+ await this.syncAgyTokenFromContainer(r);
809
1542
  }
810
1543
  } else {
811
- try {
812
- await this.terminateRun(r.id, 'failed', 'agent_exited');
813
- } catch {
814
- // retried on the next sweep
1544
+ const reason = agentExitedReason(t.exit_code);
1545
+ if (this.setState(r.id, 'running', 'waiting', reason)) {
1546
+ this.ticketRepo.updateStatus(r.ticket_id, 'waiting');
1547
+ this.agentEvent(latest, 'agent.waiting', { reason, exit_code: t.exit_code });
815
1548
  }
816
1549
  }
817
1550
  }
@@ -840,6 +1573,7 @@ export class Orchestrator {
840
1573
 
841
1574
  let isBlocked = false;
842
1575
  let waitingAgentName: string | null = null;
1576
+ let notSignedInBlocked = false;
843
1577
 
844
1578
  if (ticket.mode === 'hub') {
845
1579
  if (ticket.team_engine === 'herdr') {
@@ -868,12 +1602,12 @@ export class Orchestrator {
868
1602
  return (a.agent_status === 'idle' || a.agent_status === 'done') && seq > 0;
869
1603
  };
870
1604
  const isLeader = (a: { cwd?: string; pane_id?: string; name?: string }) => {
871
- if (a.name === 'hub leader' || a.name === 'hub-leader' || a.name === 'leader' || a.name === 'orquestador') {
1605
+ if (a.name === 'gru' || a.name === 'hub leader' || a.name === 'hub-leader' || a.name === 'leader' || a.name === 'orquestador') {
872
1606
  return true;
873
1607
  }
874
1608
  const cleanCwd = a.cwd?.replace(/\/+$/, '');
875
1609
  if (cleanCwd === '/workspace/hub') return true;
876
- if (a.pane_id === 'w1:p1' && (!a.name || a.name === 'pi' || a.name === 'agent')) return true;
1610
+ if (a.pane_id === 'w1:p1' && (!a.name || a.name === 'pi' || a.name === 'agent' || a.name === 'gru')) return true;
877
1611
  return false;
878
1612
  };
879
1613
  const waiting = agents.filter(isWaiting);
@@ -914,7 +1648,7 @@ export class Orchestrator {
914
1648
  return (t.status === 'idle' || t.status === 'done') && (t.turn ?? 0) > 0;
915
1649
  };
916
1650
  const isLeader = (t: { name?: string; cwd?: string; address?: string }) => {
917
- if (t.name === 'hub leader' || t.name === 'hub-leader' || t.name === 'leader' || t.name === 'orquestador') {
1651
+ if (t.name === 'gru' || t.name === 'hub leader' || t.name === 'hub-leader' || t.name === 'leader' || t.name === 'orquestador') {
918
1652
  return true;
919
1653
  }
920
1654
  const cleanCwd = t.cwd?.replace(/\/+$/, '');
@@ -946,11 +1680,24 @@ export class Orchestrator {
946
1680
  if (!r.hc_terminal) continue;
947
1681
  try {
948
1682
  const t = await this.hcClient.getTerminal(r.hc_terminal);
1683
+ // E5: an agent that exited leaves the run waiting (checkAgentExits) until a nudge
1684
+ // starts a new one; it must not bounce back to running here.
1685
+ if (t.state === 'finished') continue;
949
1686
  if (t.state === 'live') {
950
- const isWaiting = t.status === 'blocked' || ((t.status === 'idle' || t.status === 'done') && (t.turn ?? 0) > 0);
951
- if (isWaiting) {
952
- isBlocked = true;
953
- waitingAgentName = ticket.agent || 'agente';
1687
+ if (LOGIN_REQUIRED[ticket.agent]) {
1688
+ try {
1689
+ const screen = await this.hcClient.readTerminal(r.hc_terminal);
1690
+ if (signedOutOn(ticket.agent, screen)) {
1691
+ notSignedInBlocked = true;
1692
+ }
1693
+ } catch {}
1694
+ }
1695
+ if (!notSignedInBlocked) {
1696
+ const isWaiting = t.status === 'blocked' || ((t.status === 'idle' || t.status === 'done') && (t.turn ?? 0) > 0);
1697
+ if (isWaiting) {
1698
+ isBlocked = true;
1699
+ waitingAgentName = ticket.agent || 'agente';
1700
+ }
954
1701
  }
955
1702
  }
956
1703
  } catch {
@@ -961,6 +1708,16 @@ export class Orchestrator {
961
1708
  const latest = this.runRepo.get(r.id);
962
1709
  if (!latest || (latest.state !== 'running' && latest.state !== 'waiting')) continue;
963
1710
 
1711
+ if (notSignedInBlocked) {
1712
+ const reason = LOGIN_REQUIRED[ticket.agent] ?? LOGIN_REQUIRED.agy;
1713
+ if (this.setState(r.id, latest.state, 'blocked', reason)) {
1714
+ this.ticketRepo.updateStatus(r.ticket_id, 'blocked');
1715
+ this.agentEvent(latest, 'agent.blocked', { reason });
1716
+ transitioned.push(r.id);
1717
+ continue;
1718
+ }
1719
+ }
1720
+
964
1721
  if (isBlocked) {
965
1722
  const reason = `Esperando respuesta: ${waitingAgentName}`;
966
1723
  if (latest.state === 'running') {
@@ -1132,15 +1889,17 @@ export class Orchestrator {
1132
1889
  this.agentEvent(run, 'verification.passed', { commands: ticket.verify_commands.length });
1133
1890
 
1134
1891
  // 2. Commit what the agent left on the run's branch and bundle it.
1135
- const login = this.settingsRepo.getGitHubSummary().login;
1892
+ // The commit's author: the GitHub login (noreply address) or, on Azure Repos, the
1893
+ // account the PAT belongs to (P1, plan bond-app-azure-jira).
1894
+ const { name: authorName, email: authorEmail } = this.gitIdentityFor(ticket.repo_url);
1136
1895
  const commit = await this.dockerClient.exec(
1137
1896
  ctr,
1138
1897
  [
1139
1898
  'sh', '-c', COMMIT_SCRIPT, 'bond-commit',
1140
1899
  ticket.target_branch,
1141
1900
  `${ticket.title}\n\nbond-app run ${runId} (ticket ${ticket.id})`,
1142
- login || 'bond-app',
1143
- login ? `${login}@users.noreply.github.com` : 'bond-app@localhost',
1901
+ authorName,
1902
+ authorEmail,
1144
1903
  '/workspace/repo',
1145
1904
  BUNDLE_PATH,
1146
1905
  expectedTree,
@@ -1160,11 +1919,17 @@ export class Orchestrator {
1160
1919
  // on the exact object pushed: it is the committed head, adds commits to the real base
1161
1920
  // from GitHub and changes nothing under .github/workflows (review HIGH-1).
1162
1921
  // D2: push retries up to 3 times with growing backoff; exhausted -> blocked.
1163
- const token = this.runTokens.get(runId) || this.settingsRepo.getGitHubToken();
1164
- if (!token) throw new GitHubCredentialMissingError();
1922
+ const access = this.repoAccessFor(ticket.repo_url, runId);
1923
+ const token = access.token;
1924
+ if (!token) throw access.missing();
1165
1925
  const shouldRetryPush = (err: unknown) => {
1166
1926
  const msg = String((err as Error).message || err);
1167
- return !msg.includes('nothing to deliver') && !msg.includes('.github/workflows') && !msg.includes('does not match the committed head');
1927
+ return (
1928
+ !msg.includes('nothing to deliver') &&
1929
+ !msg.includes('.github/workflows') &&
1930
+ !msg.includes('does not match the committed head') &&
1931
+ !msg.includes('not fast-forward')
1932
+ );
1168
1933
  };
1169
1934
  const pushed = await this.retryDeliveryStep(
1170
1935
  'push',
@@ -1196,7 +1961,7 @@ export class Orchestrator {
1196
1961
  const pr = await this.retryDeliveryStep(
1197
1962
  'pr',
1198
1963
  run,
1199
- () => this.github.openPullRequest(token, ticket.repo_url, {
1964
+ () => access.openPullRequest({
1200
1965
  head: ticket.target_branch,
1201
1966
  base: ticket.base_branch,
1202
1967
  title: ticket.title,
@@ -1365,9 +2130,43 @@ export class Orchestrator {
1365
2130
  this.ticketRepo.updateStatus(run.ticket_id, 'finished');
1366
2131
  const updated = this.runRepo.get(runId)!;
1367
2132
  this.agentEvent(updated, 'agent.finished', { manual: true });
2133
+ await this.syncAgyTokenFromContainer(updated);
1368
2134
  return updated;
1369
2135
  }
1370
2136
 
2137
+ /**
2138
+ * P2: After agy run finishes, re-read token from container and sync to dataDir if changed.
2139
+ * Best-effort: catches and ignores all errors.
2140
+ */
2141
+ private async syncAgyTokenFromContainer(run: Run): Promise<void> {
2142
+ try {
2143
+ const ticket = this.ticketRepo.get(run.ticket_id);
2144
+ if (!ticket) return;
2145
+ const isAgy =
2146
+ ticket.agent === 'agy' ||
2147
+ (ticket.repos && ticket.repos.some((r: any) => teamAgentFor(ticket, r.name) === 'agy'));
2148
+ if (!isAgy || !run.container_name) return;
2149
+
2150
+ const containerTokenPath = this.getAgentConfigPath('agy');
2151
+ const execRes = await this.dockerClient.exec(run.container_name, ['cat', containerTokenPath], 'runner');
2152
+ if (execRes.exitCode !== 0 || !execRes.stdout.trim()) return;
2153
+
2154
+ const newContent = execRes.stdout.trim();
2155
+ try {
2156
+ JSON.parse(newContent);
2157
+ } catch {
2158
+ return;
2159
+ }
2160
+
2161
+ const currentCred = this.settingsRepo.getCredential('agy');
2162
+ if (!currentCred || currentCred.config_json.trim() !== newContent) {
2163
+ this.settingsRepo.setCredential('agy', newContent);
2164
+ }
2165
+ } catch {
2166
+ // Best-effort without propagating errors
2167
+ }
2168
+ }
2169
+
1371
2170
  /**
1372
2171
  * P2: Build the orchestrator / leader row for a run, used in getRunTeamStatus.
1373
2172
  * Guarantees that any run (hub or single, running or waiting or queued,
@@ -1402,7 +2201,7 @@ export class Orchestrator {
1402
2201
  } catch {}
1403
2202
  }
1404
2203
 
1405
- const isGenericAgent = (name?: string) => !name || name === 'agent' || /^t\d+$/.test(name);
2204
+ const isGenericAgent = (name?: string) => !name || name === 'agent' || name === 'gru' || /^t\d+$/.test(name);
1406
2205
 
1407
2206
  let listedAgent: string | undefined;
1408
2207
  if (isGenericAgent(t?.agent) && (run.hc_machine || run.hc_terminal || t?.address)) {
@@ -1534,7 +2333,7 @@ export class Orchestrator {
1534
2333
  const terminals = await this.hcClient.getMachineTerminals(machine);
1535
2334
 
1536
2335
  const isLeader = (t: { name?: string; cwd?: string; address?: string }) => {
1537
- if (t.name === 'hub leader' || t.name === 'hub-leader' || t.name === 'leader' || t.name === 'orquestador') {
2336
+ if (t.name === 'gru' || t.name === 'hub leader' || t.name === 'hub-leader' || t.name === 'leader' || t.name === 'orquestador') {
1538
2337
  return true;
1539
2338
  }
1540
2339
  const cleanCwd = t.cwd?.replace(/\/+$/, '');
@@ -1614,12 +2413,12 @@ export class Orchestrator {
1614
2413
 
1615
2414
  if (isHub) {
1616
2415
  const isLeader = (a: { cwd?: string; pane_id?: string; name?: string }) => {
1617
- if (a.name === 'hub leader' || a.name === 'hub-leader' || a.name === 'leader' || a.name === 'orquestador') {
2416
+ if (a.name === 'gru' || a.name === 'hub leader' || a.name === 'hub-leader' || a.name === 'leader' || a.name === 'orquestador') {
1618
2417
  return true;
1619
2418
  }
1620
2419
  const cleanCwd = a.cwd?.replace(/\/+$/, '');
1621
2420
  if (cleanCwd === '/workspace/hub') return true;
1622
- if (a.pane_id === 'w1:p1' && (!a.name || a.name === 'pi' || a.name === 'agent')) return true;
2421
+ if (a.pane_id === 'w1:p1' && (!a.name || a.name === 'pi' || a.name === 'agent' || a.name === 'gru')) return true;
1623
2422
  return false;
1624
2423
  };
1625
2424
 
@@ -1718,6 +2517,65 @@ export class Orchestrator {
1718
2517
  }
1719
2518
  }
1720
2519
 
2520
+ /**
2521
+ * P4: Proxy hc ls for the run's machine, returning live terminals with agent, state,
2522
+ * turn, and where (cwd). Returns an empty list if machine is down or unreachable without breaking.
2523
+ */
2524
+ async getRunTerminals(runId: string): Promise<RunTerminal[]> {
2525
+ const run = this.runRepo.get(runId);
2526
+ if (!run) throw new ValidationError(`Run '${runId}' not found`);
2527
+
2528
+ const machine = run.hc_machine || (run.container_name ? machineNameForRun(run.id) : null);
2529
+ if (!machine || !this.hcClient) {
2530
+ return [];
2531
+ }
2532
+
2533
+ try {
2534
+ const listed = await this.hcClient.listTerminals(machine);
2535
+ const ticket = this.ticketRepo.get(run.ticket_id);
2536
+ const isLeaderTerminal = (t: { address?: string; name?: string }) =>
2537
+ t.address?.endsWith('/t1') || t.name === 'gru' || t.name === 'agent' || t.name === 'hub leader';
2538
+
2539
+ // Accept only live terminals: exit_code must be null/undefined, state not dead/exited/closed/inactive
2540
+ const live = (listed || []).filter((t) => {
2541
+ if (t.exit_code !== null && t.exit_code !== undefined) return false;
2542
+ if (t.state && t.state !== 'live') return false;
2543
+ return true;
2544
+ });
2545
+
2546
+ return live.map((t) => {
2547
+ let agent = t.agent;
2548
+ // The orchestrator's terminal is named gru (agent in older runs): a name, not a program.
2549
+ if (!agent || agent === 'agent' || agent === 'gru' || /^t\d+$/.test(agent)) {
2550
+ if (t.name && t.name !== 'agent' && t.name !== 'gru' && !/^t\d+$/.test(t.name)) {
2551
+ agent = t.name;
2552
+ } else if (isLeaderTerminal(t)) {
2553
+ agent = ticket?.mode === 'hub' ? 'hub leader' : (ticket?.agent || 'pi');
2554
+ } else {
2555
+ agent = t.name || 'agent';
2556
+ }
2557
+ }
2558
+
2559
+ const cwd = t.cwd || '';
2560
+ return {
2561
+ address: t.address,
2562
+ name: t.name || t.address.split('/').pop() || 'agent',
2563
+ agent,
2564
+ state: t.state || 'live',
2565
+ status: t.status ?? null,
2566
+ turn: typeof t.turn === 'number' ? t.turn : 0,
2567
+ where: cwd,
2568
+ cwd,
2569
+ labels: t.labels,
2570
+ exit_code: t.exit_code ?? null,
2571
+ };
2572
+ });
2573
+ } catch (err) {
2574
+ console.warn(`[bond-app] Warning: unable to list terminals for run '${runId}' on machine '${machine}':`, err);
2575
+ return [];
2576
+ }
2577
+ }
2578
+
1721
2579
  /**
1722
2580
  * Criterion 2: push the run's bundled branch from the container, as root, with the token
1723
2581
  * on stdin (D8). Refuses (PushNotAllowedError) any repo or branch but the ticket's.
@@ -1736,8 +2594,9 @@ export class Orchestrator {
1736
2594
  assertPushTarget(ticket, repoUrl, branch);
1737
2595
  if (!/^[0-9a-f]{40}$/.test(expectedSha)) throw new Error('Invalid expected head sha');
1738
2596
  if (!run.container_name) throw new Error('The run has no container');
1739
- const secret = token || this.runTokens.get(runId) || this.settingsRepo.getGitHubToken();
1740
- if (!secret) throw new GitHubCredentialMissingError();
2597
+ const access = this.repoAccessFor(repoUrl, runId);
2598
+ const secret = token || access.token;
2599
+ if (!secret) throw access.missing();
1741
2600
  return this.pushBundle(run, repoUrl, branch, BUNDLE_PATH, expectedSha, ticket.base_branch, secret);
1742
2601
  }
1743
2602
 
@@ -1774,6 +2633,9 @@ export class Orchestrator {
1774
2633
  if (res.exitCode === PUSH_EXIT.mismatch) {
1775
2634
  throw new Error(`not pushed: the bundle does not match the committed head ${expectedSha}`);
1776
2635
  }
2636
+ if (res.exitCode === PUSH_EXIT.nonFastForward) {
2637
+ throw new Error(`not pushed: remote branch '${branch}' has new commits (not fast-forward); bundle preserved at ${bundle}`);
2638
+ }
1777
2639
  if (res.exitCode !== 0) {
1778
2640
  throw new Error(`push of ${branch} failed (exit ${res.exitCode}): ${out}`);
1779
2641
  }
@@ -1803,7 +2665,7 @@ export class Orchestrator {
1803
2665
  const branch = ticket.target_branch;
1804
2666
  const HUB_KEY = '_hub_';
1805
2667
  const targets = analysis.repos
1806
- .filter((r) => r.url && validateGitHubUrl(r.url))
2668
+ .filter((r) => r.url && validateRepoUrl(r.url))
1807
2669
  .map((r) => ({ key: r.name, dir: `${HUB_DIR}/${r.path}`, url: r.url!, base: r.base, hub: false }));
1808
2670
  if (ticket.hub_url) {
1809
2671
  targets.push({ key: HUB_KEY, dir: HUB_DIR, url: ticket.hub_url, base: ticket.hub_base || 'main', hub: true });
@@ -1881,8 +2743,7 @@ export class Orchestrator {
1881
2743
  }
1882
2744
  }
1883
2745
 
1884
- // 2. Commit, push and PR, repo by repo.
1885
- const token = this.tokenFor(runId);
2746
+ // 2. Commit and push, repo by repo (so every pushed repo is known before opening PRs).
1886
2747
  const login = this.settingsRepo.getGitHubSummary().login;
1887
2748
  const failed: string[] = [];
1888
2749
  for (const t of targets) {
@@ -1891,6 +2752,9 @@ export class Orchestrator {
1891
2752
  if (done(t.key)) continue;
1892
2753
  try {
1893
2754
  assertHubPushTarget(ticket, allowedUrls, t.url, branch, t.base);
2755
+ const access = this.repoAccessFor(t.url, runId);
2756
+ if (!access.token) throw access.missing();
2757
+ const repoToken = access.token;
1894
2758
  if (!(st.status === 'pushed' && st.sha)) {
1895
2759
  if (!(await session.hasBranch(t.dir, branch))) {
1896
2760
  st.status = 'no_changes';
@@ -1925,12 +2789,15 @@ export class Orchestrator {
1925
2789
  if (!stillVerifying()) return current();
1926
2790
  const shouldRetryPush = (err: unknown) => {
1927
2791
  const msg = String((err as Error).message || err);
1928
- return !msg.includes('nothing to deliver') && !msg.includes('.github/workflows') && !msg.includes('does not match the committed head');
2792
+ return !msg.includes('nothing to deliver')
2793
+ && !msg.includes('.github/workflows')
2794
+ && !msg.includes('does not match the committed head')
2795
+ && !msg.includes('not fast-forward');
1929
2796
  };
1930
2797
  const pushed = await this.retryDeliveryStep(
1931
2798
  `push_${t.key}`,
1932
2799
  run,
1933
- () => this.pushBundle(run, t.url, branch, bundle, sha, t.base, token),
2800
+ () => this.pushBundle(run, t.url, branch, bundle, sha, t.base, repoToken),
1934
2801
  this.config.deliveryRetryDelaysMs,
1935
2802
  shouldRetryPush
1936
2803
  );
@@ -1944,12 +2811,48 @@ export class Orchestrator {
1944
2811
  delete st.error;
1945
2812
  save();
1946
2813
  }
1947
- if (!stillVerifying()) return current();
1948
- const others = targets.filter((o) => o !== t).map(nameOf);
2814
+ } catch (err) {
2815
+ const message = String((err as Error).message || err).slice(0, 300);
2816
+ if (st.status !== 'pushed') st.status = 'failed';
2817
+ st.error = message;
2818
+ save();
2819
+ failed.push(nameOf(t));
2820
+ this.agentEvent(run, 'delivery.repo_failed', { repo: nameOf(t), error: message });
2821
+ }
2822
+ }
2823
+
2824
+ // 3. Pre-discover existing open PRs (D6) so new PR bodies can link sibling PR URLs.
2825
+ if (ticket.source_pr_url) {
2826
+ await Promise.all(targets.map(async (t) => {
2827
+ const st = states[t.key];
2828
+ if (st.status !== 'pushed' || st.pr_url) return;
2829
+ try {
2830
+ const access = this.repoAccessFor(t.url, runId);
2831
+ if (!access.token || !access.findPullRequestByHead) return;
2832
+ const existing = await access.findPullRequestByHead(branch);
2833
+ if (existing) {
2834
+ st.pr_url = existing.url;
2835
+ st.pr_number = existing.number;
2836
+ }
2837
+ } catch {}
2838
+ }));
2839
+ }
2840
+
2841
+ // 4. Open or link PRs for every pushed repo.
2842
+ for (const t of targets) {
2843
+ if (!stillVerifying()) return current();
2844
+ const st = states[t.key];
2845
+ if (st.status !== 'pushed') continue;
2846
+ try {
2847
+ const access = this.repoAccessFor(t.url, runId);
2848
+ if (!access.token) throw access.missing();
2849
+ const others = targets
2850
+ .filter((o) => o !== t && states[o.key].status !== 'no_changes' && states[o.key].status !== 'failed')
2851
+ .map((o) => ({ name: nameOf(o), url: states[o.key].pr_url ?? null }));
1949
2852
  const pr = await this.retryDeliveryStep(
1950
2853
  `pr_${t.key}`,
1951
2854
  run,
1952
- () => this.github.openPullRequest(token, t.url, {
2855
+ () => access.openPullRequest({
1953
2856
  head: branch,
1954
2857
  base: t.base,
1955
2858
  title: ticket.title,
@@ -1974,7 +2877,6 @@ export class Orchestrator {
1974
2877
  });
1975
2878
  } catch (err) {
1976
2879
  const message = String((err as Error).message || err).slice(0, 300);
1977
- if (st.status !== 'pushed') st.status = 'failed';
1978
2880
  st.error = message;
1979
2881
  save();
1980
2882
  failed.push(nameOf(t));
@@ -2060,7 +2962,7 @@ export class Orchestrator {
2060
2962
  const syncError = await session.sync();
2061
2963
  const checked = await session.check((name) => teamAgentFor(ticket, name));
2062
2964
  warnings.push(...checked.warnings);
2063
- const hub: HubToml = await session.readHubToml();
2965
+ const hub: HubToml = await session.readHubToml(ticket.hub_url);
2064
2966
  // Review H2: a created hub only lists the repos it could add; the ticket's other repos
2065
2967
  // are still part of the session and must show up as gaps.
2066
2968
  if (!ticket.hub_url) {
@@ -2072,12 +2974,12 @@ export class Orchestrator {
2072
2974
  }
2073
2975
  }
2074
2976
 
2075
- // Mounted or not: each repo with a GitHub url must be in the hub, with its base.
2977
+ // Mounted or not: each repo with a supported url must be in the hub, with its base.
2076
2978
  const known = this.mountFailures.get(runId) ?? {};
2077
2979
  const inaccessible: Record<string, string> = {};
2078
2980
  const missingBases: string[] = [];
2079
2981
  for (const r of hub.repos) {
2080
- if (!r.url || !validateGitHubUrl(r.url)) continue;
2982
+ if (!r.url || !validateRepoUrl(r.url)) continue;
2081
2983
  // Review M1: an empty submodule dir would answer with the hub's own .git.
2082
2984
  const present = await session.runner(['test', '-e', `${HUB_DIR}/${r.path}/.git`]);
2083
2985
  if (present.exitCode !== 0) {
@@ -2190,9 +3092,28 @@ export class Orchestrator {
2190
3092
  }
2191
3093
  // The hub covers the story: the team, one agent per repo, on the ticket's branch.
2192
3094
  const ticket = this.ticketRepo.get(run.ticket_id)!;
3095
+ const teamAgentsList = analysis.repos.map((r) => teamAgentFor(ticket, r.name));
3096
+ const missingLogin = teamAgentsList.find((a) => LOGIN_REQUIRED[a] && !this.settingsRepo.getCredential(a));
3097
+ if (missingLogin) {
3098
+ this.setState(runId, 'analyzing', 'blocked', LOGIN_REQUIRED[missingLogin]);
3099
+ return current();
3100
+ }
2193
3101
  try {
2194
3102
  // Review M-1: the team's credentials go in only now, after the analysis.
2195
- await this.injectCredentials(run.container_name!, analysis.repos.map((r) => teamAgentFor(ticket, r.name)));
3103
+ // A team member may delegate to another configured agent in-container, so every
3104
+ // configured credential goes in (same user, D7), not just the team's own agents.
3105
+ await this.injectCredentials(run.container_name!, [
3106
+ ...new Set([...teamAgentsList, ...this.allConfiguredAgents()]),
3107
+ ]);
3108
+ // P0 (plan bond-app-azure-jira): the agent credentials arrive with the team too; every
3109
+ // bash of the run re-reads them through BASH_ENV.
3110
+ await this.prepareAgentEnv(run.container_name!);
3111
+ // Git with the person's identity and credentials for gru (the analysis is over, M-1).
3112
+ await this.prepareGit(run.container_name!, ticket, {
3113
+ repos: [{ dir: HUB_DIR, base: ticket.hub_base || 'main' }, ...analysis.repos.map((r) => ({ dir: `${HUB_DIR}/${r.path}`, base: r.base }))],
3114
+ withCredentials: true,
3115
+ runId,
3116
+ });
2196
3117
  if (!stillAnalyzing()) return current();
2197
3118
  const session = this.hubSessionOf(run);
2198
3119
  // Review L-2: a restart during the launch left the team open: keep it, do not relaunch.
@@ -2204,7 +3125,10 @@ export class Orchestrator {
2204
3125
  } catch {
2205
3126
  live = false;
2206
3127
  }
2207
- reused = live && (await session.teamOpen(ticket.target_branch, analysis.repos.length, ticket.team_engine || 'hc', this.hcClient, run.hc_machine || machineNameForRun(run.id)));
3128
+ // hc: the run is one session, its leader (gru); a live leader is the run already open.
3129
+ // herdr (legacy TUI): the whole team must be open.
3130
+ reused = live && ((ticket.team_engine || 'hc') === 'hc'
3131
+ || (await session.teamOpen(ticket.target_branch, analysis.repos.length, 'herdr', this.hcClient, run.hc_machine || machineNameForRun(run.id))));
2208
3132
  }
2209
3133
  if (!reused) {
2210
3134
  const terminal = await session.launchTeam(this.hcClient, run.hc_machine!, ticket, analysis.repos, {
@@ -2246,7 +3170,7 @@ export class Orchestrator {
2246
3170
  throw new ValidationError('El análisis no propone arreglos automáticos: arregla el hub a mano y relanza el run');
2247
3171
  }
2248
3172
  const ticket = this.ticketRepo.get(run.ticket_id)!;
2249
- const token = this.tokenFor(runId);
3173
+ const token = (url: string) => this.repoAccessFor(url, runId).token;
2250
3174
  this.approving.add(runId);
2251
3175
  let result: { applied: string[]; failed: string[] };
2252
3176
  try {
@@ -2297,7 +3221,7 @@ export class Orchestrator {
2297
3221
  return (t.status === 'idle' || t.status === 'done') && (t.turn ?? 0) > 0;
2298
3222
  };
2299
3223
  const isLeader = (t: { name?: string; cwd?: string; address?: string }) => {
2300
- if (t.name === 'hub leader' || t.name === 'hub-leader' || t.name === 'leader' || t.name === 'orquestador') {
3224
+ if (t.name === 'gru' || t.name === 'hub leader' || t.name === 'hub-leader' || t.name === 'leader' || t.name === 'orquestador') {
2301
3225
  return true;
2302
3226
  }
2303
3227
  const cleanCwd = t.cwd?.replace(/\/+$/, '');
@@ -2336,12 +3260,12 @@ export class Orchestrator {
2336
3260
  });
2337
3261
  if (waitingList.length > 0) {
2338
3262
  const isLeader = (a: { cwd?: string; pane_id?: string; name?: string }) => {
2339
- if (a.name === 'hub leader' || a.name === 'hub-leader' || a.name === 'leader' || a.name === 'orquestador') {
3263
+ if (a.name === 'gru' || a.name === 'hub leader' || a.name === 'hub-leader' || a.name === 'leader' || a.name === 'orquestador') {
2340
3264
  return true;
2341
3265
  }
2342
3266
  const cleanCwd = a.cwd?.replace(/\/+$/, '');
2343
3267
  if (cleanCwd === '/workspace/hub') return true;
2344
- if (a.pane_id === 'w1:p1' && (!a.name || a.name === 'pi' || a.name === 'agent')) return true;
3268
+ if (a.pane_id === 'w1:p1' && (!a.name || a.name === 'pi' || a.name === 'agent' || a.name === 'gru')) return true;
2345
3269
  return false;
2346
3270
  };
2347
3271
 
@@ -2434,7 +3358,7 @@ export class Orchestrator {
2434
3358
  private async unblockHub(run: Run, ticket: Ticket, text: string): Promise<Run> {
2435
3359
  const runId = run.id;
2436
3360
  if (this.analyses.has(runId) || this.approving.has(runId)) throw new ValidationError('El hub ya se está analizando');
2437
- const token = this.tokenFor(runId);
3361
+ const token = (url: string) => this.repoAccessFor(url, runId).token;
2438
3362
  this.approving.add(runId);
2439
3363
  try {
2440
3364
  if (!this.setState(runId, 'blocked', 'analyzing', null)) {
@@ -2445,12 +3369,12 @@ export class Orchestrator {
2445
3369
  const session = this.hubSessionOf(run);
2446
3370
  try {
2447
3371
  // Whatever the person fixed outside (access, a base branch...): mount it again.
2448
- const hub = await session.readHubToml();
3372
+ const hub = await session.readHubToml(ticket.hub_url);
2449
3373
  const missing = new Set<string>();
2450
3374
  for (const r of hub.repos) {
2451
3375
  // P5 debt L-1: validate repo names in unblockHub and prevent _hub_ collision
2452
3376
  if (!NAME_RE.test(r.name) || r.name === '_hub_') continue;
2453
- if (!r.url || !validateGitHubUrl(r.url)) continue;
3377
+ if (!r.url || !validateRepoUrl(r.url)) continue;
2454
3378
  const present = await session.runner(['test', '-e', `${HUB_DIR}/${r.path}/.git`]);
2455
3379
  if (present.exitCode !== 0) {
2456
3380
  await session.removeDir(`/workspace/repos/${r.name}`);
@@ -2522,48 +3446,124 @@ export class Orchestrator {
2522
3446
  }
2523
3447
 
2524
3448
  /**
2525
- * P7 (MEDIUM-3): Dedicated Unix socket server for 'bond-app pr' channel.
2526
- * Survives or is recreated upon orchestrator restart for any live runs.
3449
+ * 2026-11-25-el-canal-bond-app-pr-va-por-docker-exec-fifo-en-el-contenedor-sin-red:
3450
+ * Dedicated per-run long-lived docker exec FIFO watcher for 'bond-app pr' channel.
3451
+ * Requires zero network reachability from container to host (works with ufw/firewalls
3452
+ * and Docker Desktop alike). Token is written via stdin (0600, runner) and validated
3453
+ * in constant time on each request; results are written back via stdin (0600, runner).
2527
3454
  */
2528
- ensureRunSocketServer(runId: string): string {
2529
- const existing = this.runServers.get(runId);
2530
- if (existing) return existing.socketDir;
3455
+ async ensureRunPrWatcher(
3456
+ runId: string,
3457
+ containerName: string
3458
+ ): Promise<{ token: string }> {
3459
+ const existing = this.runPrWatchers.get(runId);
3460
+ if (existing) {
3461
+ return { token: existing.token };
3462
+ }
2531
3463
 
2532
- const socketDir = path.join(os.tmpdir(), `bond-app-sock-${runId}`);
2533
- fs.mkdirSync(socketDir, { recursive: true, mode: 0o777 });
2534
- const hostSocketPath = path.join(socketDir, 'bond-app.sock');
2535
- try { fs.rmSync(hostSocketPath, { force: true }); } catch {}
3464
+ const token = crypto.randomBytes(32).toString('hex');
3465
+ const safeCompare = (a: string, b: string): boolean => {
3466
+ const bufA = Buffer.from(a);
3467
+ const bufB = Buffer.from(b);
3468
+ if (bufA.length !== bufB.length) return false;
3469
+ return crypto.timingSafeEqual(bufA, bufB);
3470
+ };
2536
3471
 
2537
- const socketServer = http.createServer(async (req, res) => {
2538
- if (req.method === 'POST' && req.url === '/pr') {
2539
- try {
2540
- const delivered = await this.deliverRun(runId);
2541
- const isSuccess = delivered.state === 'finished' && Boolean(delivered.pr_url);
2542
- res.writeHead(isSuccess ? 200 : 500, { 'Content-Type': 'application/json' });
2543
- res.end(JSON.stringify({
2544
- ok: isSuccess,
2545
- state: delivered.state,
2546
- pr_url: delivered.pr_url,
2547
- pr_number: delivered.pr_number,
2548
- error: delivered.failure_reason,
2549
- }));
2550
- } catch (err) {
2551
- const msg = String((err as Error).message || err);
2552
- res.writeHead(400, { 'Content-Type': 'application/json' });
2553
- res.end(JSON.stringify({ ok: false, error: msg }));
3472
+ const prEnvContent = `BOND_APP_PR_TOKEN=${token}\n`;
3473
+ await this.dockerClient.injectStdin(
3474
+ containerName,
3475
+ ['sh', '-c', 'mkdir -p /var/run/bond-app && chown runner:runner /var/run/bond-app && chmod 0700 /var/run/bond-app && cat > /var/run/bond-app/pr.env && chown runner:runner /var/run/bond-app/pr.env && chmod 0600 /var/run/bond-app/pr.env'],
3476
+ prEnvContent,
3477
+ 'root'
3478
+ );
3479
+
3480
+ if (typeof this.dockerClient.execStream !== 'function') {
3481
+ this.runPrWatchers.set(runId, { token, stop: () => {} });
3482
+ return { token };
3483
+ }
3484
+
3485
+ const fifoReaderScript = [
3486
+ 'trap "exit 0" TERM INT',
3487
+ 'mkdir -p /var/run/bond-app',
3488
+ 'chown runner:runner /var/run/bond-app',
3489
+ 'chmod 0700 /var/run/bond-app',
3490
+ 'FIFO="/var/run/bond-app/pr.fifo"',
3491
+ 'rm -f "$FIFO"',
3492
+ 'mkfifo -m 0600 "$FIFO"',
3493
+ 'chown runner:runner "$FIFO"',
3494
+ 'while true; do',
3495
+ ' if IFS= read -r line < "$FIFO"; then',
3496
+ ' printf "%s\\n" "$line"',
3497
+ ' fi',
3498
+ 'done',
3499
+ ].join('\n');
3500
+
3501
+ const handle = this.dockerClient.execStream(containerName, ['sh', '-c', fifoReaderScript], 'root');
3502
+ let stopped = false;
3503
+ let buffer = '';
3504
+
3505
+ const handleLine = async (rawLine: string) => {
3506
+ const match = /^([a-f0-9]+)\s+([A-Za-z0-9_-]{1,64})$/.exec(rawLine.trim());
3507
+ if (!match) return;
3508
+ const [, providedToken, reqId] = match;
3509
+ if (!safeCompare(providedToken, token)) return;
3510
+
3511
+ let result: Record<string, unknown>;
3512
+ try {
3513
+ const delivered = await this.deliverRun(runId);
3514
+ const isSuccess = delivered.state === 'finished' && Boolean(delivered.pr_url);
3515
+ result = {
3516
+ ok: isSuccess,
3517
+ state: delivered.state,
3518
+ pr_url: delivered.pr_url,
3519
+ pr_number: delivered.pr_number,
3520
+ error: delivered.failure_reason,
3521
+ };
3522
+ } catch (err) {
3523
+ result = { ok: false, error: String((err as Error).message || err) };
3524
+ }
3525
+
3526
+ if (stopped) return;
3527
+ const resultPath = `/var/run/bond-app/pr-${reqId}.json`;
3528
+ try {
3529
+ await this.dockerClient.injectStdin(
3530
+ containerName,
3531
+ ['sh', '-c', `cat > "${resultPath}.tmp" && chown runner:runner "${resultPath}.tmp" && chmod 0600 "${resultPath}.tmp" && mv "${resultPath}.tmp" "${resultPath}"`],
3532
+ JSON.stringify(result),
3533
+ 'root'
3534
+ );
3535
+ } catch {
3536
+ // container may have stopped during delivery
3537
+ }
3538
+ };
3539
+
3540
+ handle.stdout.on('data', (chunk: Buffer | string) => {
3541
+ if (stopped) return;
3542
+ buffer += chunk.toString();
3543
+ let idx: number;
3544
+ while ((idx = buffer.indexOf('\n')) !== -1) {
3545
+ const line = buffer.slice(0, idx);
3546
+ buffer = buffer.slice(idx + 1);
3547
+ if (line.trim()) {
3548
+ void handleLine(line);
2554
3549
  }
2555
- } else {
2556
- res.writeHead(404);
2557
- res.end();
2558
3550
  }
2559
3551
  });
2560
- socketServer.on('error', () => {});
2561
- socketServer.listen(hostSocketPath, () => {
2562
- try { fs.chmodSync(hostSocketPath, 0o666); } catch {}
3552
+
3553
+ const stop = () => {
3554
+ if (stopped) return;
3555
+ stopped = true;
3556
+ handle.kill();
3557
+ };
3558
+
3559
+ void handle.done.then(() => {
3560
+ if (!stopped && this.runPrWatchers.get(runId)?.stop === stop) {
3561
+ this.runPrWatchers.delete(runId);
3562
+ }
2563
3563
  });
2564
- socketServer.unref();
2565
- this.runServers.set(runId, { server: socketServer, socketDir });
2566
- return socketDir;
3564
+
3565
+ this.runPrWatchers.set(runId, { token, stop });
3566
+ return { token };
2567
3567
  }
2568
3568
 
2569
3569
  private async internalStartRun(runId: string, options: TestStartRunOptions = {}): Promise<Run> {
@@ -2580,15 +3580,20 @@ export class Orchestrator {
2580
3580
  // D20: an explicit token in the request wins; else the stored GitHub credential (the
2581
3581
  // user's gh session); without either the launch is refused (N4). It still reaches the
2582
3582
  // container only on stdin (D8).
3583
+ // P1 (plan bond-app-azure-jira): the clone token is the one of the repo's host — the
3584
+ // GitHub token as always, or the Azure DevOps PAT for an Azure Repos ticket.
3585
+ const onAzure = repoHostOf(ticket.repo_url) === 'azure';
2583
3586
  const githubToken = options.skipClone
2584
3587
  ? undefined
2585
- : options.githubToken || this.settingsRepo.getGitHubToken() || undefined;
3588
+ : onAzure
3589
+ ? this.repoAccessFor(ticket.repo_url).token || undefined
3590
+ : options.githubToken || this.settingsRepo.getGitHubToken() || undefined;
2586
3591
  if (!options.skipClone) {
2587
3592
  if (!githubToken) {
2588
- throw new GitHubCredentialMissingError();
3593
+ throw onAzure ? new AzureDevOpsCredentialMissingError() : new GitHubCredentialMissingError();
2589
3594
  }
2590
- if (options.githubToken) this.runTokens.set(runId, options.githubToken);
2591
- if (!validateGitHubUrl(ticket.repo_url)) {
3595
+ if (options.githubToken && !onAzure) this.runTokens.set(runId, options.githubToken);
3596
+ if (!validateRepoUrl(ticket.repo_url)) {
2592
3597
  throw new ValidationError(`Invalid repo_url '${ticket.repo_url}'`);
2593
3598
  }
2594
3599
  } else if (ticket.mode === 'hub') {
@@ -2610,30 +3615,91 @@ export class Orchestrator {
2610
3615
 
2611
3616
  this.startingRuns.add(runId);
2612
3617
 
2613
- // P7: Registration with linked GitHub issue URL (read on host with gh session, never in container)
3618
+ // P7 / P2: Registration with linked GitHub or Jira issue URL (read on host with session/credential, never in container)
2614
3619
  if (ticket.issue_url) {
2615
- if (!validateGitHubIssueUrl(ticket.issue_url)) {
3620
+ const isGh = validateGitHubIssueUrl(ticket.issue_url);
3621
+ const isJira = validateJiraIssueUrl(ticket.issue_url);
3622
+ if (!isGh && !isJira) {
2616
3623
  this.setState(run.id, 'queued', 'blocked', 'invalid_issue_url');
2617
3624
  this.startingRuns.delete(runId);
2618
3625
  return this.runRepo.get(run.id)!;
2619
3626
  }
2620
- const { owner, repo, issueNumber } = parseGitHubIssueUrl(ticket.issue_url);
2621
- const token = githubToken || this.settingsRepo.getGitHubToken() || '';
3627
+ if (isGh) {
3628
+ const { owner, repo, issueNumber } = parseGitHubIssueUrl(ticket.issue_url);
3629
+ // La historia solo se inyecta si el ticket no trae ya una (check del alta
3630
+ // <<Llevar el cuerpo de la issue>>): desmarcado = story vacía = sin re-fetch.
3631
+ // Solo re-fetch si no hay historia alguna (ticket antiguo o URL manual: null). Un ""
3632
+ // explícito significa «cuerpo desmarcado a propósito»: no se fetchea ni se inyecta.
3633
+ if (ticket.story === null || ticket.story === undefined) {
3634
+ const token = githubToken || this.settingsRepo.getGitHubToken() || '';
3635
+ try {
3636
+ const issue = await this.github.getIssue(token, owner, repo, issueNumber);
3637
+ const updated = this.ticketRepo.update(ticket.id, {
3638
+ story: issue.title + (issue.body ? '\n\n' + issue.body : ''),
3639
+ title: ticket.title || issue.title,
3640
+ });
3641
+ if (updated) ticket = updated;
3642
+ } catch (err) {
3643
+ const msg = String((err as Error).message || err);
3644
+ this.setState(run.id, 'queued', 'blocked', `issue_inaccessible: ${msg}`);
3645
+ this.startingRuns.delete(runId);
3646
+ return this.runRepo.get(run.id)!;
3647
+ }
3648
+ }
3649
+ } else if (isJira) {
3650
+ const { site, issueKey } = parseJiraIssueUrl(ticket.issue_url);
3651
+ const cred = this.settingsRepo.getJiraCredential();
3652
+ // P2 review: the stored token never travels to a site other than the configured
3653
+ // one (both normalized). A mismatch means the linked issue belongs to another
3654
+ // Jira Cloud site: block instead of sending credentials there.
3655
+ if (cred && normalizeJiraSite(cred.site) !== normalizeJiraSite(site)) {
3656
+ this.setState(run.id, 'queued', 'blocked', 'issue_inaccessible: jira_site_mismatch');
3657
+ this.startingRuns.delete(runId);
3658
+ return this.runRepo.get(run.id)!;
3659
+ }
3660
+ if (ticket.story === null || ticket.story === undefined) {
3661
+ if (!cred) {
3662
+ this.setState(run.id, 'queued', 'blocked', 'issue_inaccessible: jira_not_configured');
3663
+ this.startingRuns.delete(runId);
3664
+ return this.runRepo.get(run.id)!;
3665
+ }
3666
+ try {
3667
+ const issue = await this.jira.getIssue(site, cred.email, cred.token, issueKey);
3668
+ const updated = this.ticketRepo.update(ticket.id, {
3669
+ story: issue.summary + (issue.description ? '\n\n' + issue.description : ''),
3670
+ title: ticket.title || issue.summary,
3671
+ });
3672
+ if (updated) ticket = updated;
3673
+ } catch (err) {
3674
+ const msg = String((err as Error).message || err);
3675
+ this.setState(run.id, 'queued', 'blocked', `issue_inaccessible: ${msg}`);
3676
+ this.startingRuns.delete(runId);
3677
+ return this.runRepo.get(run.id)!;
3678
+ }
3679
+ }
3680
+ }
3681
+ }
3682
+
3683
+ // P4 (plan bond-app-ajustes-imagen): «Docker en el run» needs the image's docker group.
3684
+ if (ticket.docker === true) {
3685
+ let tools: string[] | undefined;
2622
3686
  try {
2623
- const issue = await this.github.getIssue(token, owner, repo, issueNumber);
2624
- const updated = this.ticketRepo.update(ticket.id, {
2625
- story: issue.title + (issue.body ? '\n\n' + issue.body : ''),
2626
- title: ticket.title || issue.title,
2627
- });
2628
- if (updated) ticket = updated;
2629
- } catch (err) {
2630
- const msg = String((err as Error).message || err);
2631
- this.setState(run.id, 'queued', 'blocked', `issue_inaccessible: ${msg}`);
3687
+ tools = (await this.dockerClient.inspectRunnerImage(this.config.runnerImage)).tools;
3688
+ } catch {}
3689
+ if (tools && !tools.includes('docker')) {
3690
+ this.setState(run.id, 'queued', 'blocked', DOCKER_REQUIRED);
2632
3691
  this.startingRuns.delete(runId);
2633
3692
  return this.runRepo.get(run.id)!;
2634
3693
  }
2635
3694
  }
2636
3695
 
3696
+ // P2: an agent that needs its own login (agy, claude) without a stored one: BLOCKED before launch
3697
+ if (LOGIN_REQUIRED[ticket.agent] && !this.settingsRepo.getCredential(ticket.agent)) {
3698
+ this.setState(run.id, 'queued', 'blocked', LOGIN_REQUIRED[ticket.agent]);
3699
+ this.startingRuns.delete(runId);
3700
+ return this.runRepo.get(run.id)!;
3701
+ }
3702
+
2637
3703
  const assertQueued = () => {
2638
3704
  const current = this.runRepo.get(runId);
2639
3705
  if (!current || current.state !== 'queued') {
@@ -2649,10 +3715,7 @@ export class Orchestrator {
2649
3715
  try {
2650
3716
  assertQueued();
2651
3717
 
2652
- // P7: Dedicated Unix socket server for 'bond-app pr' channel
2653
- const socketDir = this.ensureRunSocketServer(run.id);
2654
-
2655
- const extraMounts = [...(options.extraMounts ?? []), `${socketDir}:/var/run/bond-app`];
3718
+ const extraMounts = [...(options.extraMounts ?? [])];
2656
3719
 
2657
3720
  // 1. Create dedicated user-defined network per run
2658
3721
  const networkName = await this.dockerClient.createNetwork(run.id, this.config.instanceId);
@@ -2670,6 +3733,7 @@ export class Orchestrator {
2670
3733
  memory: this.config.memory,
2671
3734
  pidsLimit: this.config.pidsLimit,
2672
3735
  extraMounts,
3736
+ docker: ticket.docker === true,
2673
3737
  });
2674
3738
 
2675
3739
  containerName = containerInfo.containerName;
@@ -2688,7 +3752,9 @@ export class Orchestrator {
2688
3752
 
2689
3753
  assertQueued();
2690
3754
 
2691
- // P7: install bond-app CLI inside the container
3755
+ // P7 / D6-rev (2026-11-25): per-run docker exec FIFO watcher + 0600 token via stdin + CLI
3756
+ await this.ensureRunPrWatcher(run.id, containerInfo.containerName);
3757
+
2692
3758
  const bondAppScript = `#!/bin/sh
2693
3759
  set -e
2694
3760
 
@@ -2702,34 +3768,53 @@ if [ "$#" -gt 1 ]; then
2702
3768
  exit 1
2703
3769
  fi
2704
3770
 
2705
- SOCK="/var/run/bond-app/bond-app.sock"
2706
- if [ ! -S "$SOCK" ]; then
2707
- echo "Error: bond-app socket not available at $SOCK" >&2
3771
+ PR_ENV="/var/run/bond-app/pr.env"
3772
+ FIFO="/var/run/bond-app/pr.fifo"
3773
+ if [ ! -f "$PR_ENV" ]; then
3774
+ echo "Error: bond-app PR channel not configured at $PR_ENV" >&2
2708
3775
  exit 1
2709
3776
  fi
2710
3777
 
2711
- if command -v curl >/dev/null 2>&1; then
2712
- RES=$(curl -s -S --max-time 600 --unix-socket "$SOCK" -X POST http://localhost/pr)
2713
- else
2714
- RES=$(node -e "
2715
- const http = require('http');
2716
- const req = http.request({ socketPath: '$SOCK', path: '/pr', method: 'POST', timeout: 600000 }, (res) => {
2717
- let data = '';
2718
- res.on('data', (c) => data += c);
2719
- res.on('end', () => { process.stdout.write(data); process.exit(res.statusCode === 200 ? 0 : 1); });
2720
- });
2721
- req.on('timeout', () => { req.destroy(); console.error('timeout'); process.exit(1); });
2722
- req.on('error', (e) => { console.error(e.message); process.exit(1); });
2723
- req.end();
2724
- ")
3778
+ . "$PR_ENV"
3779
+ if [ -z "$BOND_APP_PR_TOKEN" ]; then
3780
+ echo "Error: bond-app PR token missing" >&2
3781
+ exit 1
2725
3782
  fi
2726
3783
 
2727
- echo "$RES"
2728
- if echo "$RES" | grep -q '"ok":true' && echo "$RES" | grep -q '"pr_url"'; then
2729
- exit 0
2730
- else
3784
+ WAITED_FIFO=0
3785
+ while [ ! -p "$FIFO" ] && [ "$WAITED_FIFO" -lt 10 ]; do
3786
+ sleep 0.2
3787
+ WAITED_FIFO=$((WAITED_FIFO + 1))
3788
+ done
3789
+ if [ ! -p "$FIFO" ]; then
3790
+ echo "Error: bond-app PR FIFO not available at $FIFO" >&2
2731
3791
  exit 1
2732
3792
  fi
3793
+
3794
+ REQ_ID="$(date +%s)-$$-$(head -c 6 /dev/urandom | od -An -tx1 | tr -d ' \\n')"
3795
+ RES_FILE="/var/run/bond-app/pr-\${REQ_ID}.json"
3796
+ rm -f "$RES_FILE"
3797
+
3798
+ printf '%s %s\\n' "$BOND_APP_PR_TOKEN" "$REQ_ID" > "$FIFO"
3799
+
3800
+ WAITED=0
3801
+ while [ "$WAITED" -lt 600 ]; do
3802
+ if [ -f "$RES_FILE" ]; then
3803
+ RES=$(cat "$RES_FILE")
3804
+ rm -f "$RES_FILE"
3805
+ echo "$RES"
3806
+ if echo "$RES" | grep -q '"ok":true' && echo "$RES" | grep -q '"pr_url"'; then
3807
+ exit 0
3808
+ else
3809
+ exit 1
3810
+ fi
3811
+ fi
3812
+ sleep 1
3813
+ WAITED=$((WAITED + 1))
3814
+ done
3815
+
3816
+ echo "Error: timed out waiting for bond-app PR response after 600s" >&2
3817
+ exit 1
2733
3818
  `;
2734
3819
 
2735
3820
  await this.dockerClient.injectStdin(
@@ -2777,11 +3862,12 @@ fi
2777
3862
 
2778
3863
  assertQueued();
2779
3864
 
2780
- // N4, D14, M-C: Branch checkout from origin/<base_branch> and existing remote branch check
3865
+ // N4, D14, M-C: Branch checkout from origin/<base_branch> (or origin/<target_branch> for PR/branch tickets, D4)
2781
3866
  const targetBranch = ticket.target_branch || `feat/${ticket.id}`;
2782
3867
  const baseBranch = ticket.base_branch || 'main';
3868
+ const fromRemoteBranch = Boolean(ticket.source_pr_url);
2783
3869
 
2784
- if (!options.allowExistingRemoteBranch) {
3870
+ if (!fromRemoteBranch && !options.allowExistingRemoteBranch) {
2785
3871
  // M-C: Use local rev-parse to check remote branch existence locally and fail closed
2786
3872
  const revParseRes = await this.dockerClient.exec(
2787
3873
  containerInfo.containerName,
@@ -2796,24 +3882,37 @@ fi
2796
3882
  }
2797
3883
  }
2798
3884
 
3885
+ const startPoint = fromRemoteBranch ? `origin/${targetBranch}` : `origin/${baseBranch}`;
2799
3886
  const branchRes = await this.dockerClient.exec(
2800
3887
  containerInfo.containerName,
2801
- ['git', '-C', '/workspace/repo', 'checkout', '-B', targetBranch, `origin/${baseBranch}`],
3888
+ // --no-track: the run's branch never follows its base (a bare `git pull`/`push` would
3889
+ // hit main). A PR's branch follows its own remote branch.
3890
+ ['git', '-C', '/workspace/repo', 'checkout', '--no-track', '-B', targetBranch, startPoint],
2802
3891
  'runner',
2803
3892
  15000
2804
3893
  );
2805
3894
  if (branchRes.exitCode !== 0) {
2806
3895
  throw new Error(`Git branch checkout failed with code ${branchRes.exitCode}: ${branchRes.stderr}`);
2807
3896
  }
3897
+ if (fromRemoteBranch) {
3898
+ await this.dockerClient.exec(containerInfo.containerName,
3899
+ ['git', '-C', '/workspace/repo', 'branch', `--set-upstream-to=origin/${targetBranch}`, targetBranch], 'runner', 15000);
3900
+ }
3901
+ await this.prepareGit(containerInfo.containerName, ticket, { repos: [{ dir: '/workspace/repo', base: baseBranch }], withCredentials: true, runId: run.id });
2808
3902
 
2809
3903
  assertQueued();
2810
3904
  }
2811
3905
 
2812
3906
  // 5. Inject Agent credentials (D7, M7, L6). P5 review M-1: a hub run gets them only
2813
3907
  // when its team starts, after the analysis (the hub agent reads untrusted content).
3908
+ // All configured credentials go into every run: the ticket's agent may delegate to
3909
+ // another one inside the container (bond team panes), and they all belong to the user.
2814
3910
  if (ticket.mode !== 'hub') {
2815
- await this.injectCredentials(containerInfo.containerName, [ticket.agent]);
3911
+ await this.injectCredentials(containerInfo.containerName, this.allConfiguredAgents());
2816
3912
  }
3913
+ // P0 (plan bond-app-azure-jira): the BASH_ENV script always (the hc core starts with
3914
+ // it); the agent credentials too, except in a hub before its team starts (M-1).
3915
+ await this.prepareAgentEnv(containerInfo.containerName, '/home/runner', ticket.mode !== 'hub');
2817
3916
 
2818
3917
  assertQueued();
2819
3918
 
@@ -2838,9 +3937,16 @@ fi
2838
3937
  assertQueued();
2839
3938
  this.runRepo.update(run.id, {});
2840
3939
  };
3940
+ const tokenForRepo = (url: string) =>
3941
+ repoHostOf(url) === 'github' && options.githubToken ? options.githubToken : this.repoAccessFor(url, runId).token;
2841
3942
  const mounted = ticket.hub_url
2842
- ? await session.mountExisting(ticket.hub_url, ticket.hub_base || 'main', githubToken!)
2843
- : await session.createHub(ticket, githubToken!);
3943
+ ? await session.mountExisting(
3944
+ ticket.hub_url,
3945
+ ticket.hub_base || 'main',
3946
+ tokenForRepo,
3947
+ ticket.source_pr_url ? ticket.target_branch : undefined
3948
+ )
3949
+ : await session.createHub(ticket, tokenForRepo);
2844
3950
  this.mountFailures.set(runId, mounted.inaccessible);
2845
3951
  assertQueued();
2846
3952
  if (!this.setState(run.id, 'queued', 'analyzing', null, { started_at: new Date().toISOString() })) {
@@ -2852,6 +3958,7 @@ fi
2852
3958
 
2853
3959
  if (!options.skipClone) {
2854
3960
  await this.bondifyRepo(containerInfo.containerName, ticket, run.id);
3961
+ await this.syncBondRepo(containerInfo.containerName, ticket, run.id);
2855
3962
  }
2856
3963
 
2857
3964
  assertQueued();
@@ -2918,10 +4025,17 @@ fi
2918
4025
  ? 'validation_error'
2919
4026
  : startError instanceof HubMountError
2920
4027
  ? 'hub_mount_failed'
2921
- : 'container_error';
4028
+ : startError instanceof HcError && startError.kind === 'agent_exited'
4029
+ ? 'agent_exited'
4030
+ : 'container_error';
2922
4031
  if (startError instanceof HubMountError) {
2923
4032
  this.agentEvent(latest, 'hub.mount_failed', { error: startError.message.slice(0, 300) });
2924
4033
  }
4034
+ // The start error used to be lost (only the launch dialog saw it): keep it as an
4035
+ // event and in the orchestrator's log, so a failed run says why.
4036
+ const message = startError instanceof Error ? startError.message : String(startError);
4037
+ this.agentEvent(latest, 'run.start_failed', { reason: failureReason, error: message.slice(0, 500) });
4038
+ console.error(`[bond-app] run ${runId} failed to start (${failureReason}): ${message}`);
2925
4039
  const { updated } = this.runRepo.updateStateConditionally(
2926
4040
  runId,
2927
4041
  oldState,
@@ -2951,6 +4065,27 @@ fi
2951
4065
  }
2952
4066
  }
2953
4067
 
4068
+ /** Initial prompt text for a ticket, adding PR/branch context when `source_pr_url` is set. */
4069
+ private initialPromptFor(ticket: Ticket, promptOverride?: string): string {
4070
+ if (promptOverride !== undefined) return promptOverride.trim();
4071
+ const parts: string[] = [];
4072
+ if (ticket.source_pr_url) {
4073
+ const ref = parseSourceUrl(ticket.source_pr_url);
4074
+ if (ref?.kind === 'pr') {
4075
+ parts.push(
4076
+ `Trabajas sobre la PR ${ticket.source_pr_url} (${ticket.title}), en su rama '${ticket.target_branch}'. Al entregar, tus commits se subirán a esta rama y la PR existente se actualizará.`
4077
+ );
4078
+ } else {
4079
+ parts.push(`Trabajas sobre la rama existente '${ticket.target_branch}' (${ticket.source_pr_url}).`);
4080
+ }
4081
+ if (ticket.story?.trim()) parts.push(ticket.story.trim());
4082
+ else if (ticket.description?.trim()) parts.push(ticket.description.trim());
4083
+ if (ticket.prompt?.trim()) parts.push(ticket.prompt.trim());
4084
+ return parts.join('\n\n');
4085
+ }
4086
+ return [ticket.story ?? '', ticket.prompt ?? ''].filter((s) => s.trim()).join('\n\n').trim();
4087
+ }
4088
+
2954
4089
  /**
2955
4090
  * P3: the command for the run's hc terminal: BOND_APP_AGENT_COMMAND if set, else the
2956
4091
  * ticket's agent with the ticket prompt as its first message (interactive, so the user
@@ -2963,8 +4098,7 @@ fi
2963
4098
  if (!isValidAgent(ticket.agent)) {
2964
4099
  throw new ValidationError(`Unsupported agent '${ticket.agent}'`);
2965
4100
  }
2966
- const story = [ticket.story ?? '', ticket.prompt ?? ''].filter((s) => s.trim()).join('\n\n');
2967
- const prompt = (promptOverride ?? story).trim();
4101
+ const prompt = this.initialPromptFor(ticket, promptOverride);
2968
4102
  // P4 & D-M1: the ticket's model for pi (`--model provider/id`), or default_model if ticket has none.
2969
4103
  const defaultModel = ticket.agent === 'pi' ? this.settingsRepo?.getSetupSelection?.()?.default_model : null;
2970
4104
  const model = ticket.agent === 'pi' ? (ticket.model || defaultModel) : null;
@@ -2974,6 +4108,76 @@ fi
2974
4108
  return prompt ? [ticket.agent, prompt] : [ticket.agent];
2975
4109
  }
2976
4110
 
4111
+ /**
4112
+ * Workaround (herdr 0.9.3, reportado upstream): `agent.start` falla si un elemento del
4113
+ * argv del agente contiene `\n`, y bond se queda en la shell sin agente. Un prompt
4114
+ * multilínea nunca viaja como argumento: para pi se escribe a TASK_FILE en el contenedor
4115
+ * y el agente arranca con `@fichero` + una instrucción de una línea; otros agentes
4116
+ * reciben el prompt con los saltos colapsados a espacios (mejor esfuerzo). Los prompts
4117
+ * de una línea viajan literales como siempre.
4118
+ */
4119
+ static readonly TASK_FILE = '/home/runner/.bond-task.md';
4120
+
4121
+ private async writeTaskFile(containerName: string, prompt: string): Promise<boolean> {
4122
+ try {
4123
+ const res = await this.dockerClient.injectStdin(
4124
+ containerName,
4125
+ ['sh', '-c', `cat > ${Orchestrator.TASK_FILE}`],
4126
+ prompt
4127
+ );
4128
+ return res.exitCode === 0;
4129
+ } catch {
4130
+ return false;
4131
+ }
4132
+ }
4133
+
4134
+ /** Elementos del argv con el prompt inicial, garantizados sin `\n`. */
4135
+ async promptArgvFor(
4136
+ containerName: string | null | undefined,
4137
+ ticket: Ticket,
4138
+ promptOverride?: string
4139
+ ): Promise<string[]> {
4140
+ const prompt = this.initialPromptFor(ticket, promptOverride);
4141
+ if (!prompt) return [];
4142
+ if (!prompt.includes('\n')) return [prompt];
4143
+ if (ticket.agent === 'pi' && containerName && (await this.writeTaskFile(containerName, prompt))) {
4144
+ return [`@${Orchestrator.TASK_FILE}`, 'Trabaja la tarea del ticket adjunta en el fichero.'];
4145
+ }
4146
+ return [prompt.replace(/\s*\n\s*/g, ' ')];
4147
+ }
4148
+
4149
+ /** Comando pelado (sin bond) a partir de los elementos de prompt ya resueltos. */
4150
+ bareAgentCommand(ticket: Ticket, promptArgv: string[]): string[] {
4151
+ if (this.config.agentCommand && this.config.agentCommand.length > 0) {
4152
+ return [...this.config.agentCommand];
4153
+ }
4154
+ if (!isValidAgent(ticket.agent)) {
4155
+ throw new ValidationError(`Unsupported agent '${ticket.agent}'`);
4156
+ }
4157
+ if (ticket.agent === 'agy') {
4158
+ // `-i` takes the first message: without one (a ticket with no story nor prompt) agy
4159
+ // prints its usage and exits 2, and the run died as container_error right at start.
4160
+ return ['agy', '--dangerously-skip-permissions', ...(promptArgv.length ? ['-i', ...promptArgv] : [])];
4161
+ }
4162
+ if (ticket.agent === 'claude') {
4163
+ // Unattended in the run's container, as agy (runs are `runner`, never root).
4164
+ return ['claude', '--dangerously-skip-permissions', ...promptArgv];
4165
+ }
4166
+ if (ticket.agent === 'codex') {
4167
+ // Interactive TUI with the ticket as its first message; the container is the sandbox.
4168
+ // --dangerously-bypass-hook-trust: bond's agent-state hook would stop it at «Hooks need review».
4169
+ return ['codex', '--dangerously-bypass-approvals-and-sandbox', '--dangerously-bypass-hook-trust', ...promptArgv];
4170
+ }
4171
+ if (ticket.agent === 'copilot') {
4172
+ // `-i` starts the interactive session with a first message (as agy, only with one).
4173
+ return ['copilot', '--yolo', ...(promptArgv.length ? ['-i', ...promptArgv] : [])];
4174
+ }
4175
+ const defaultModel = ticket.agent === 'pi' ? this.settingsRepo?.getSetupSelection?.()?.default_model : null;
4176
+ const model = ticket.agent === 'pi' ? (ticket.model || defaultModel) : null;
4177
+ const head = ticket.agent === 'pi' && model ? [ticket.agent, '--model', model] : [ticket.agent];
4178
+ return [...head, ...promptArgv];
4179
+ }
4180
+
2977
4181
  /**
2978
4182
  * P4 (D-U): Auto-bondify repository if it lacks .bond/bond.toml.
2979
4183
  * If config.runnerLauncher === 'bond' and ticket.bondify !== false:
@@ -3089,6 +4293,37 @@ fi
3089
4293
  }
3090
4294
  }
3091
4295
 
4296
+ /**
4297
+ * Decision 2026-11-25 (usuario: «una vez usemos las nuevas skills de bond, esas quedan en el
4298
+ * repo»): before the agent starts, `bond sync` with the image's bond in a repo that already
4299
+ * uses bond, and what it rewrote (catalog skills, agent config, manifest, AGENTS.md) goes in
4300
+ * its own commit, `chore: bond sync (bond X.Y.Z)`, signed with the person's identity. The
4301
+ * PR carries it apart from the ticket's work and the agent starts on a clean tree (before,
4302
+ * `bond tui` synced after the start and the changes ended up mixed in the delivery).
4303
+ * Only on a clean tree; a failure is an event, never a stop. Returns whether it committed.
4304
+ */
4305
+ async syncBondRepo(containerName: string | null | undefined, ticket: Ticket, runId: string): Promise<boolean> {
4306
+ if (this.config.runnerLauncher !== 'bond' || ticket.bondify === false || !containerName) return false;
4307
+ try {
4308
+ const res = await this.dockerClient.exec(
4309
+ containerName,
4310
+ ['sh', '-c', BOND_SYNC_COMMIT_SCRIPT],
4311
+ 'runner',
4312
+ 60000
4313
+ );
4314
+ const run = this.runRepo?.get?.(runId);
4315
+ const committed = /^committed$/m.test(res.stdout);
4316
+ if (res.exitCode !== 0) {
4317
+ if (run) this.agentEvent(run, 'bond.sync_failed', { exitCode: res.exitCode, stderr: String(res.stderr).slice(0, 500) });
4318
+ return false;
4319
+ }
4320
+ if (committed && run) this.agentEvent(run, 'bond.sync_done', { commit: /^message=(.*)$/m.exec(res.stdout)?.[1] ?? 'chore: bond sync' });
4321
+ return committed;
4322
+ } catch {
4323
+ return false;
4324
+ }
4325
+ }
4326
+
3092
4327
  /**
3093
4328
  * D-G (image plan): the launch command is `bond tui --agent <agente>` - bond is the
3094
4329
  * harness (skills, AGENTS.md, sync, decisions, the rich agent bar); the ticket prompt
@@ -3102,29 +4337,41 @@ fi
3102
4337
  ticket: Ticket,
3103
4338
  promptOverride?: string
3104
4339
  ): Promise<string[]> {
4340
+ // Workaround herdr: el argv nunca lleva '\n' (ver promptArgvFor); se resuelve antes
4341
+ // porque escribir el fichero de tarea necesita el contenedor.
4342
+ const promptArgv = await this.promptArgvFor(containerName, ticket, promptOverride);
3105
4343
  if (this.config.runnerLauncher !== 'bond' || this.config.agentCommand || !containerName) {
3106
- return this.agentCommandFor(ticket, promptOverride);
4344
+ return this.bareAgentCommand(ticket, promptArgv);
3107
4345
  }
3108
4346
  try {
3109
4347
  const probe = await this.dockerClient.exec(containerName, [
3110
4348
  'sh', '-c',
3111
4349
  'command -v bond >/dev/null 2>&1 && bond tui --help >/dev/null 2>&1 && [ -f "/workspace/repo/.bond/bond.toml" ]',
3112
4350
  ]);
3113
- if (probe.exitCode !== 0) return this.agentCommandFor(ticket, promptOverride);
4351
+ if (probe.exitCode !== 0) return this.bareAgentCommand(ticket, promptArgv);
3114
4352
  } catch {
3115
- return this.agentCommandFor(ticket, promptOverride);
4353
+ return this.bareAgentCommand(ticket, promptArgv);
3116
4354
  }
3117
4355
  if (!isValidAgent(ticket.agent)) {
3118
4356
  throw new ValidationError(`Unsupported agent '${ticket.agent}'`);
3119
4357
  }
3120
- const story = [ticket.story ?? '', ticket.prompt ?? ''].filter((s) => s.trim()).join('\n\n');
3121
- const prompt = (promptOverride ?? story).trim();
3122
4358
  const argv = ['bond', 'tui', '--agent', ticket.agent, '--'];
3123
4359
  // P4 (D-D) & D-M1: el modelo solo aplica a pi; default_model si el ticket no trae modelo.
3124
4360
  const defaultModel = ticket.agent === 'pi' ? this.settingsRepo?.getSetupSelection?.()?.default_model : null;
3125
4361
  const model = ticket.agent === 'pi' ? (ticket.model || defaultModel) : null;
3126
4362
  if (ticket.agent === 'pi' && model) argv.push('--model', model);
3127
- if (prompt) argv.push(prompt);
4363
+ if (ticket.agent === 'agy') {
4364
+ // `-i` only with a first message (see bareAgentCommand): agy exits 2 on a bare `-i`.
4365
+ argv.push('--dangerously-skip-permissions');
4366
+ if (promptArgv.length) argv.push('-i');
4367
+ }
4368
+ if (ticket.agent === 'claude') argv.push('--dangerously-skip-permissions');
4369
+ if (ticket.agent === 'codex') argv.push('--dangerously-bypass-approvals-and-sandbox', '--dangerously-bypass-hook-trust');
4370
+ if (ticket.agent === 'copilot') {
4371
+ argv.push('--yolo');
4372
+ if (promptArgv.length) argv.push('-i');
4373
+ }
4374
+ argv.push(...promptArgv);
3128
4375
  return argv;
3129
4376
  }
3130
4377
 
@@ -3135,11 +4382,10 @@ fi
3135
4382
  * periodic sweep retries it.
3136
4383
  */
3137
4384
  async teardownRunResources(runId: string, containerName?: string | null): Promise<void> {
3138
- const s = this.runServers.get(runId);
3139
- if (s) {
3140
- try { s.server.close(); } catch {}
3141
- try { fs.rmSync(s.socketDir, { recursive: true, force: true }); } catch {}
3142
- this.runServers.delete(runId);
4385
+ const w = this.runPrWatchers.get(runId);
4386
+ if (w) {
4387
+ try { w.stop(); } catch {}
4388
+ this.runPrWatchers.delete(runId);
3143
4389
  }
3144
4390
 
3145
4391
  const cName = containerName || `bond-app-${runId}`;
@@ -3244,24 +4490,19 @@ fi
3244
4490
  const branch = ticket.target_branch;
3245
4491
  const base = ticket.base_branch || 'main';
3246
4492
 
3247
- if (token) {
4493
+ {
3248
4494
  const unmerged: string[] = [];
3249
- const toDelete: Array<{ owner: string; repo: string }> = [];
4495
+ const toDelete: Array<ReturnType<Orchestrator['repoAccessFor']>> = [];
3250
4496
 
3251
4497
  for (const repoUrl of reposToCheck) {
3252
- let owner: string;
3253
- let repo: string;
3254
- try {
3255
- const parsed = parseGitHubRepo(repoUrl);
3256
- owner = parsed.owner;
3257
- repo = parsed.repo;
3258
- } catch {
3259
- continue;
3260
- }
4498
+ // P1 (plan bond-app-azure-jira): GitHub or Azure Repos, each with its own token.
4499
+ if (!validateRepoUrl(repoUrl)) continue;
4500
+ const access = this.repoAccessFor(repoUrl);
4501
+ if (!access.token) continue;
3261
4502
 
3262
4503
  let exists = false;
3263
4504
  try {
3264
- exists = await this.github.remoteBranchExists(token, owner, repo, branch);
4505
+ exists = await access.branchExists(branch);
3265
4506
  } catch {
3266
4507
  continue;
3267
4508
  }
@@ -3269,16 +4510,16 @@ fi
3269
4510
  if (exists) {
3270
4511
  let merged = false;
3271
4512
  try {
3272
- merged = await this.github.isBranchMerged(token, owner, repo, branch, base);
4513
+ merged = await access.branchMerged(branch, base);
3273
4514
  } catch {
3274
4515
  // Fail closed: if check fails or throws, treat as unmerged so user work is protected
3275
4516
  merged = false;
3276
4517
  }
3277
4518
 
3278
4519
  if (!merged) {
3279
- unmerged.push(`${owner}/${repo}`);
4520
+ unmerged.push(access.label);
3280
4521
  }
3281
- toDelete.push({ owner, repo });
4522
+ toDelete.push(access);
3282
4523
  }
3283
4524
  }
3284
4525
 
@@ -3286,9 +4527,9 @@ fi
3286
4527
  throw new UnmergedBranchError(unmerged.join(', '), branch, base);
3287
4528
  }
3288
4529
 
3289
- for (const { owner, repo } of toDelete) {
4530
+ for (const access of toDelete) {
3290
4531
  try {
3291
- await this.github.deleteRemoteBranch(token, owner, repo, branch);
4532
+ await access.deleteBranch(branch);
3292
4533
  } catch {
3293
4534
  // ignore API errors
3294
4535
  }
@@ -3357,26 +4598,28 @@ fi
3357
4598
  const branch = ticket.target_branch;
3358
4599
  const base = ticket.base_branch || 'main';
3359
4600
 
3360
- if (token) {
4601
+ {
3361
4602
  for (const repoUrl of reposToCheck) {
3362
4603
  try {
3363
- const { owner, repo } = parseGitHubRepo(repoUrl);
4604
+ if (!validateRepoUrl(repoUrl)) continue;
4605
+ const access = this.repoAccessFor(repoUrl);
4606
+ if (!access.token) continue;
3364
4607
  let exists = false;
3365
4608
  try {
3366
- exists = await this.github.remoteBranchExists(token, owner, repo, branch);
4609
+ exists = await access.branchExists(branch);
3367
4610
  } catch {
3368
4611
  exists = true;
3369
4612
  }
3370
4613
  let merged = false;
3371
4614
  if (exists) {
3372
4615
  try {
3373
- merged = await this.github.isBranchMerged(token, owner, repo, branch, base);
4616
+ merged = await access.branchMerged(branch, base);
3374
4617
  } catch {
3375
4618
  merged = false;
3376
4619
  }
3377
4620
  if (!merged) requiresForce = true;
3378
4621
  }
3379
- remoteBranches.push({ repo: `${owner}/${repo}`, branch, base, exists, merged });
4622
+ remoteBranches.push({ repo: access.label, branch, base, exists, merged });
3380
4623
  } catch {
3381
4624
  // ignore
3382
4625
  }
@@ -3438,6 +4681,7 @@ fi
3438
4681
  validateTransition(run.state, targetState);
3439
4682
 
3440
4683
  // Teardown resources
4684
+ await this.syncAgyTokenFromContainer(run);
3441
4685
  let teardownFailed = false;
3442
4686
  try {
3443
4687
  await this.teardownRunResources(runId, run.container_name);
@@ -3516,6 +4760,8 @@ fi
3516
4760
  agents?: string[];
3517
4761
  skip_az?: boolean;
3518
4762
  skip_gh?: boolean;
4763
+ tools?: string[];
4764
+ apt_extra?: string[];
3519
4765
  config_dir?: string;
3520
4766
  credentials_file?: string;
3521
4767
  } = {}
@@ -3524,22 +4770,56 @@ fi
3524
4770
  throw new RebuildInProgressError('A rebuild is already in progress');
3525
4771
  }
3526
4772
  this.rebuildInFlight = true;
4773
+ this.rebuildStatus = { running: true, started_at: new Date().toISOString(), finished_at: null, step: 0, total: 0, detail: 'Preparando el build…', ok: null, error: null };
3527
4774
  try {
4775
+ // Without an explicit list, the image keeps the agents chosen in the wizard: a bare
4776
+ // «Rebuild…» from Ajustes used to drop to the minimal image (pi), losing agy/claude.
4777
+ const agents = extras.agents ?? this.selectedImageAgents();
4778
+ // Same for the developer tools (plan bond-app-ajustes-imagen P2): the chosen groups
4779
+ // and extra packages unless the request names its own.
4780
+ const sel = this.settingsRepo?.getSetupSelection?.();
4781
+ const tools = extras.tools ?? sel?.tools_selected;
4782
+ const aptExtra = extras.apt_extra ?? sel?.apt_extra;
3528
4783
  await this.rebuildImpl(this.config.runnerImage, {
3529
4784
  ...versions,
3530
4785
  ...extras,
4786
+ ...(agents ? { agents } : {}),
4787
+ ...(tools ? { tools } : {}),
4788
+ ...(aptExtra ? { apt_extra: aptExtra } : {}),
3531
4789
  data_dir: this.config.dataDir,
4790
+ on_progress: (p) => {
4791
+ this.rebuildStatus = { ...this.rebuildStatus, step: p.step, total: p.total, detail: p.detail };
4792
+ },
3532
4793
  });
4794
+ this.rebuildStatus = { ...this.rebuildStatus, running: false, finished_at: new Date().toISOString(), ok: true, detail: 'Imagen lista' };
3533
4795
  return {
3534
4796
  image: this.config.runnerImage,
3535
4797
  rebuilt_at: new Date().toISOString(),
3536
4798
  credentials_touched: extras.credentials_file !== undefined,
3537
4799
  };
4800
+ } catch (err) {
4801
+ this.rebuildStatus = { ...this.rebuildStatus, running: false, finished_at: new Date().toISOString(), ok: false, error: (err as Error).message };
4802
+ throw err;
3538
4803
  } finally {
3539
4804
  this.rebuildInFlight = false;
3540
4805
  }
3541
4806
  }
3542
4807
 
4808
+ /** Where the image build is (or how the last one ended), for Ajustes' progress bar. */
4809
+ getRebuildStatus(): typeof this.rebuildStatus {
4810
+ return { ...this.rebuildStatus };
4811
+ }
4812
+
4813
+ /** The wizard's agent selection, or undefined when nothing was chosen (setup.sh's default). */
4814
+ private selectedImageAgents(): string[] | undefined {
4815
+ try {
4816
+ const sel = this.settingsRepo?.getSetupSelection?.()?.agents_selected ?? [];
4817
+ return sel.length ? [...sel] : undefined;
4818
+ } catch {
4819
+ return undefined;
4820
+ }
4821
+ }
4822
+
3543
4823
  /**
3544
4824
  * W-P1 (wizard): the aggregated setup state — selection, per-agent credentials, the gh
3545
4825
  * session and the runner image. Recomputed on every call (a stored credential shows up
@@ -3562,9 +4842,21 @@ fi
3562
4842
  suggestions_model: selection.suggestions_model,
3563
4843
  default_model: selection.default_model,
3564
4844
  models: selection.models,
4845
+ tools_selected: selection.tools_selected,
4846
+ apt_extra: selection.apt_extra,
4847
+ recipe: this.currentRecipe(),
3565
4848
  });
3566
4849
  }
3567
4850
 
4851
+ /** The runner recipe's fingerprint; null when the build context is not readable here. */
4852
+ private currentRecipe(): string | undefined {
4853
+ try {
4854
+ return runnerRecipeHash();
4855
+ } catch {
4856
+ return undefined;
4857
+ }
4858
+ }
4859
+
3568
4860
  /** W-P1: persists the wizard's selection; only the given fields change (validated by the API). */
3569
4861
  saveSetup(selection: {
3570
4862
  agents_selected?: string[];
@@ -3572,6 +4864,8 @@ fi
3572
4864
  suggestions_model?: string | null;
3573
4865
  default_model?: string | null;
3574
4866
  models?: string[];
4867
+ tools_selected?: string[];
4868
+ apt_extra?: string[];
3575
4869
  }): void {
3576
4870
  this.settingsRepo.saveSetupSelection(selection);
3577
4871
  }