@jmanuelcorral/bond-app 0.1.6 → 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.
@@ -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';
@@ -12,7 +12,7 @@ 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
14
  import { rebuildRunnerImage as rebuildRunnerImageImpl, runnerRecipeHash, type RunnerBuildOptions, type RunnerVersions } from '../runner/image-builder.ts';
15
- import { GitHubClient, parseGitHubRepo } from '../runner/github-client.ts';
15
+ import { GitHubApiError, GitHubClient, parseGitHubRepo } from '../runner/github-client.ts';
16
16
  import { JiraClient } from '../runner/jira-client.ts';
17
17
  import {
18
18
  assertHubPushTarget,
@@ -27,13 +27,16 @@ import {
27
27
  pullRequestBody,
28
28
  tail,
29
29
  TREE_SCRIPT,
30
+ GIT_SETUP_COMMAND,
31
+ BOND_SYNC_COMMIT_SCRIPT,
30
32
  } from './delivery.ts';
31
33
  import { HubMountError, HubSession, proposeUrls } from './hub-session.ts';
32
- import { AzureDevOpsClient } from '../runner/azure-devops-client.ts';
33
- import { parseAzureRepoUrl, repoHostOf, repoLabel, validateRepoUrl } from './repo-host.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';
34
37
  import { AgyLoginManager, CLAUDE_LOGIN_SPEC, CODEX_LOGIN_SPEC, COPILOT_LOGIN_SPEC, type AgyLoginDriver } from './agy-login.ts';
35
38
  import { buildSetupState } from './setup.ts';
36
- 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';
37
40
  import {
38
41
  validateGitHubUrl,
39
42
  validateGitHubIssueUrl,
@@ -47,6 +50,7 @@ import {
47
50
  type RepoDelivery,
48
51
  type Run,
49
52
  type Ticket,
53
+ type CreateTicketInput,
50
54
  type RunState,
51
55
  type FailureReason,
52
56
  type TeamStatusRow,
@@ -126,6 +130,21 @@ export class GitHubCredentialMissingError extends ValidationError {
126
130
  }
127
131
  }
128
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
+
129
148
  export { PushNotAllowedError };
130
149
 
131
150
  export class RebuildInProgressError extends Error {
@@ -271,8 +290,8 @@ export class Orchestrator {
271
290
  private approving = new Set<string>();
272
291
  // P5 review M-2: a person's instructions for the hub agent («Desbloquear»), per run.
273
292
  private analysisNotes = new Map<string, string>();
274
- // P7: per-run local socket server for 'bond-app pr' channel
275
- 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 }>();
276
295
  public agyLoginManager: AgyLoginManager;
277
296
  /** Plan bond-app-claude-agente P2: `claude setup-token` in a throwaway container. */
278
297
  public claudeLoginManager: AgyLoginManager;
@@ -366,11 +385,10 @@ export class Orchestrator {
366
385
  await this.claudeLoginManager.cancel();
367
386
  await this.codexLoginManager.cancel();
368
387
  await this.copilotLoginManager.cancel();
369
- for (const [, s] of this.runServers.entries()) {
370
- try { s.server.close(); } catch {}
371
- try { fs.rmSync(s.socketDir, { recursive: true, force: true }); } catch {}
388
+ for (const [, w] of this.runPrWatchers.entries()) {
389
+ try { w.stop(); } catch {}
372
390
  }
373
- this.runServers.clear();
391
+ this.runPrWatchers.clear();
374
392
  }
375
393
 
376
394
  /**
@@ -444,6 +462,7 @@ export class Orchestrator {
444
462
 
445
463
  /** The org's Azure repos, cached a few minutes: the repo search asks on every keystroke. */
446
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 }>();
447
466
 
448
467
  /**
449
468
  * Alta de ticket (Qué · Dónde · Quién): the repos to offer for «Dónde», in this order —
@@ -507,6 +526,342 @@ export class Orchestrator {
507
526
  return { repos: [...out.values()].slice(0, 60), errors };
508
527
  }
509
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
+
510
865
  /**
511
866
  * Plan bond-app-azure-jira P1: what bond-app needs to act on a repo's host — the token
512
867
  * for its clone and push (stdin) and the API calls of the delivery and the ticket's
@@ -520,6 +875,7 @@ export class Orchestrator {
520
875
  branchExists: (branch: string) => Promise<boolean>;
521
876
  branchMerged: (branch: string, base: string) => Promise<boolean>;
522
877
  deleteBranch: (branch: string) => Promise<boolean>;
878
+ findPullRequestByHead?: (branch: string) => Promise<{ number: number; url: string } | null>;
523
879
  openPullRequest: (pr: { head: string; base: string; title: string; body: string }) => Promise<{ number: number; url: string; created: boolean }>;
524
880
  } {
525
881
  const label = repoLabel(repoUrl);
@@ -536,6 +892,10 @@ export class Orchestrator {
536
892
  branchExists: (b) => this.azure.remoteBranchExists(token!, repoUrl, b),
537
893
  branchMerged: (b, base) => this.azure.isBranchMerged(token!, repoUrl, b, base),
538
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
+ },
539
899
  openPullRequest: (pr) => this.azure.openPullRequest(token!, repoUrl, pr),
540
900
  };
541
901
  }
@@ -549,10 +909,71 @@ export class Orchestrator {
549
909
  branchExists: (b) => this.github.remoteBranchExists(token!, gh().owner, gh().repo, b),
550
910
  branchMerged: (b, base) => this.github.isBranchMerged(token!, gh().owner, gh().repo, b, base),
551
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
+ },
552
917
  openPullRequest: (pr) => this.github.openPullRequest(token!, repoUrl, pr),
553
918
  };
554
919
  }
555
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
+
556
977
  async prepareAgentEnv(containerName: string, home = '/home/runner', withSources = true): Promise<string[]> {
557
978
  const write = async (dest: string, content: string) => {
558
979
  const res = await this.dockerClient.injectStdin(
@@ -737,7 +1158,7 @@ export class Orchestrator {
737
1158
  }
738
1159
  }
739
1160
 
740
- // 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
741
1162
  for (const r of activeRuns) {
742
1163
  if (
743
1164
  r.container_name &&
@@ -745,7 +1166,9 @@ export class Orchestrator {
745
1166
  ['running', 'analyzing', 'verifying', 'blocked', 'waiting', 'finished'].includes(r.state)
746
1167
  ) {
747
1168
  try {
748
- this.ensureRunSocketServer(r.id);
1169
+ if (!this.runPrWatchers.has(r.id)) {
1170
+ await this.ensureRunPrWatcher(r.id, r.container_name);
1171
+ }
749
1172
  } catch {
750
1173
  // ignore
751
1174
  }
@@ -1179,7 +1602,7 @@ export class Orchestrator {
1179
1602
  return (a.agent_status === 'idle' || a.agent_status === 'done') && seq > 0;
1180
1603
  };
1181
1604
  const isLeader = (a: { cwd?: string; pane_id?: string; name?: string }) => {
1182
- 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') {
1183
1606
  return true;
1184
1607
  }
1185
1608
  const cleanCwd = a.cwd?.replace(/\/+$/, '');
@@ -1225,7 +1648,7 @@ export class Orchestrator {
1225
1648
  return (t.status === 'idle' || t.status === 'done') && (t.turn ?? 0) > 0;
1226
1649
  };
1227
1650
  const isLeader = (t: { name?: string; cwd?: string; address?: string }) => {
1228
- 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') {
1229
1652
  return true;
1230
1653
  }
1231
1654
  const cleanCwd = t.cwd?.replace(/\/+$/, '');
@@ -1468,11 +1891,7 @@ export class Orchestrator {
1468
1891
  // 2. Commit what the agent left on the run's branch and bundle it.
1469
1892
  // The commit's author: the GitHub login (noreply address) or, on Azure Repos, the
1470
1893
  // account the PAT belongs to (P1, plan bond-app-azure-jira).
1471
- const login = this.settingsRepo.getGitHubSummary().login;
1472
- const azureAccount = repoHostOf(ticket.repo_url) === 'azure' ? this.settingsRepo.getAzureDevOpsSummary().account : undefined;
1473
- const azureMatch = azureAccount ? /^(.*?)\s*<([^<>\s]+@[^<>\s]+)>$/.exec(azureAccount) : null;
1474
- const authorName = azureMatch ? azureMatch[1] : azureAccount || login || 'bond-app';
1475
- const authorEmail = azureMatch ? azureMatch[2] : !azureAccount && login ? `${login}@users.noreply.github.com` : 'bond-app@localhost';
1894
+ const { name: authorName, email: authorEmail } = this.gitIdentityFor(ticket.repo_url);
1476
1895
  const commit = await this.dockerClient.exec(
1477
1896
  ctr,
1478
1897
  [
@@ -1505,7 +1924,12 @@ export class Orchestrator {
1505
1924
  if (!token) throw access.missing();
1506
1925
  const shouldRetryPush = (err: unknown) => {
1507
1926
  const msg = String((err as Error).message || err);
1508
- 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
+ );
1509
1933
  };
1510
1934
  const pushed = await this.retryDeliveryStep(
1511
1935
  'push',
@@ -1909,7 +2333,7 @@ export class Orchestrator {
1909
2333
  const terminals = await this.hcClient.getMachineTerminals(machine);
1910
2334
 
1911
2335
  const isLeader = (t: { name?: string; cwd?: string; address?: string }) => {
1912
- 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') {
1913
2337
  return true;
1914
2338
  }
1915
2339
  const cleanCwd = t.cwd?.replace(/\/+$/, '');
@@ -1989,7 +2413,7 @@ export class Orchestrator {
1989
2413
 
1990
2414
  if (isHub) {
1991
2415
  const isLeader = (a: { cwd?: string; pane_id?: string; name?: string }) => {
1992
- 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') {
1993
2417
  return true;
1994
2418
  }
1995
2419
  const cleanCwd = a.cwd?.replace(/\/+$/, '');
@@ -2209,6 +2633,9 @@ export class Orchestrator {
2209
2633
  if (res.exitCode === PUSH_EXIT.mismatch) {
2210
2634
  throw new Error(`not pushed: the bundle does not match the committed head ${expectedSha}`);
2211
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
+ }
2212
2639
  if (res.exitCode !== 0) {
2213
2640
  throw new Error(`push of ${branch} failed (exit ${res.exitCode}): ${out}`);
2214
2641
  }
@@ -2238,7 +2665,7 @@ export class Orchestrator {
2238
2665
  const branch = ticket.target_branch;
2239
2666
  const HUB_KEY = '_hub_';
2240
2667
  const targets = analysis.repos
2241
- .filter((r) => r.url && validateGitHubUrl(r.url))
2668
+ .filter((r) => r.url && validateRepoUrl(r.url))
2242
2669
  .map((r) => ({ key: r.name, dir: `${HUB_DIR}/${r.path}`, url: r.url!, base: r.base, hub: false }));
2243
2670
  if (ticket.hub_url) {
2244
2671
  targets.push({ key: HUB_KEY, dir: HUB_DIR, url: ticket.hub_url, base: ticket.hub_base || 'main', hub: true });
@@ -2316,8 +2743,7 @@ export class Orchestrator {
2316
2743
  }
2317
2744
  }
2318
2745
 
2319
- // 2. Commit, push and PR, repo by repo.
2320
- const token = this.tokenFor(runId);
2746
+ // 2. Commit and push, repo by repo (so every pushed repo is known before opening PRs).
2321
2747
  const login = this.settingsRepo.getGitHubSummary().login;
2322
2748
  const failed: string[] = [];
2323
2749
  for (const t of targets) {
@@ -2326,6 +2752,9 @@ export class Orchestrator {
2326
2752
  if (done(t.key)) continue;
2327
2753
  try {
2328
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;
2329
2758
  if (!(st.status === 'pushed' && st.sha)) {
2330
2759
  if (!(await session.hasBranch(t.dir, branch))) {
2331
2760
  st.status = 'no_changes';
@@ -2360,12 +2789,15 @@ export class Orchestrator {
2360
2789
  if (!stillVerifying()) return current();
2361
2790
  const shouldRetryPush = (err: unknown) => {
2362
2791
  const msg = String((err as Error).message || err);
2363
- 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');
2364
2796
  };
2365
2797
  const pushed = await this.retryDeliveryStep(
2366
2798
  `push_${t.key}`,
2367
2799
  run,
2368
- () => this.pushBundle(run, t.url, branch, bundle, sha, t.base, token),
2800
+ () => this.pushBundle(run, t.url, branch, bundle, sha, t.base, repoToken),
2369
2801
  this.config.deliveryRetryDelaysMs,
2370
2802
  shouldRetryPush
2371
2803
  );
@@ -2379,12 +2811,48 @@ export class Orchestrator {
2379
2811
  delete st.error;
2380
2812
  save();
2381
2813
  }
2382
- if (!stillVerifying()) return current();
2383
- 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 }));
2384
2852
  const pr = await this.retryDeliveryStep(
2385
2853
  `pr_${t.key}`,
2386
2854
  run,
2387
- () => this.github.openPullRequest(token, t.url, {
2855
+ () => access.openPullRequest({
2388
2856
  head: branch,
2389
2857
  base: t.base,
2390
2858
  title: ticket.title,
@@ -2409,7 +2877,6 @@ export class Orchestrator {
2409
2877
  });
2410
2878
  } catch (err) {
2411
2879
  const message = String((err as Error).message || err).slice(0, 300);
2412
- if (st.status !== 'pushed') st.status = 'failed';
2413
2880
  st.error = message;
2414
2881
  save();
2415
2882
  failed.push(nameOf(t));
@@ -2495,7 +2962,7 @@ export class Orchestrator {
2495
2962
  const syncError = await session.sync();
2496
2963
  const checked = await session.check((name) => teamAgentFor(ticket, name));
2497
2964
  warnings.push(...checked.warnings);
2498
- const hub: HubToml = await session.readHubToml();
2965
+ const hub: HubToml = await session.readHubToml(ticket.hub_url);
2499
2966
  // Review H2: a created hub only lists the repos it could add; the ticket's other repos
2500
2967
  // are still part of the session and must show up as gaps.
2501
2968
  if (!ticket.hub_url) {
@@ -2507,12 +2974,12 @@ export class Orchestrator {
2507
2974
  }
2508
2975
  }
2509
2976
 
2510
- // 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.
2511
2978
  const known = this.mountFailures.get(runId) ?? {};
2512
2979
  const inaccessible: Record<string, string> = {};
2513
2980
  const missingBases: string[] = [];
2514
2981
  for (const r of hub.repos) {
2515
- if (!r.url || !validateGitHubUrl(r.url)) continue;
2982
+ if (!r.url || !validateRepoUrl(r.url)) continue;
2516
2983
  // Review M1: an empty submodule dir would answer with the hub's own .git.
2517
2984
  const present = await session.runner(['test', '-e', `${HUB_DIR}/${r.path}/.git`]);
2518
2985
  if (present.exitCode !== 0) {
@@ -2641,6 +3108,12 @@ export class Orchestrator {
2641
3108
  // P0 (plan bond-app-azure-jira): the agent credentials arrive with the team too; every
2642
3109
  // bash of the run re-reads them through BASH_ENV.
2643
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
+ });
2644
3117
  if (!stillAnalyzing()) return current();
2645
3118
  const session = this.hubSessionOf(run);
2646
3119
  // Review L-2: a restart during the launch left the team open: keep it, do not relaunch.
@@ -2652,7 +3125,10 @@ export class Orchestrator {
2652
3125
  } catch {
2653
3126
  live = false;
2654
3127
  }
2655
- 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))));
2656
3132
  }
2657
3133
  if (!reused) {
2658
3134
  const terminal = await session.launchTeam(this.hcClient, run.hc_machine!, ticket, analysis.repos, {
@@ -2694,7 +3170,7 @@ export class Orchestrator {
2694
3170
  throw new ValidationError('El análisis no propone arreglos automáticos: arregla el hub a mano y relanza el run');
2695
3171
  }
2696
3172
  const ticket = this.ticketRepo.get(run.ticket_id)!;
2697
- const token = this.tokenFor(runId);
3173
+ const token = (url: string) => this.repoAccessFor(url, runId).token;
2698
3174
  this.approving.add(runId);
2699
3175
  let result: { applied: string[]; failed: string[] };
2700
3176
  try {
@@ -2745,7 +3221,7 @@ export class Orchestrator {
2745
3221
  return (t.status === 'idle' || t.status === 'done') && (t.turn ?? 0) > 0;
2746
3222
  };
2747
3223
  const isLeader = (t: { name?: string; cwd?: string; address?: string }) => {
2748
- 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') {
2749
3225
  return true;
2750
3226
  }
2751
3227
  const cleanCwd = t.cwd?.replace(/\/+$/, '');
@@ -2784,7 +3260,7 @@ export class Orchestrator {
2784
3260
  });
2785
3261
  if (waitingList.length > 0) {
2786
3262
  const isLeader = (a: { cwd?: string; pane_id?: string; name?: string }) => {
2787
- 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') {
2788
3264
  return true;
2789
3265
  }
2790
3266
  const cleanCwd = a.cwd?.replace(/\/+$/, '');
@@ -2882,7 +3358,7 @@ export class Orchestrator {
2882
3358
  private async unblockHub(run: Run, ticket: Ticket, text: string): Promise<Run> {
2883
3359
  const runId = run.id;
2884
3360
  if (this.analyses.has(runId) || this.approving.has(runId)) throw new ValidationError('El hub ya se está analizando');
2885
- const token = this.tokenFor(runId);
3361
+ const token = (url: string) => this.repoAccessFor(url, runId).token;
2886
3362
  this.approving.add(runId);
2887
3363
  try {
2888
3364
  if (!this.setState(runId, 'blocked', 'analyzing', null)) {
@@ -2893,12 +3369,12 @@ export class Orchestrator {
2893
3369
  const session = this.hubSessionOf(run);
2894
3370
  try {
2895
3371
  // Whatever the person fixed outside (access, a base branch...): mount it again.
2896
- const hub = await session.readHubToml();
3372
+ const hub = await session.readHubToml(ticket.hub_url);
2897
3373
  const missing = new Set<string>();
2898
3374
  for (const r of hub.repos) {
2899
3375
  // P5 debt L-1: validate repo names in unblockHub and prevent _hub_ collision
2900
3376
  if (!NAME_RE.test(r.name) || r.name === '_hub_') continue;
2901
- if (!r.url || !validateGitHubUrl(r.url)) continue;
3377
+ if (!r.url || !validateRepoUrl(r.url)) continue;
2902
3378
  const present = await session.runner(['test', '-e', `${HUB_DIR}/${r.path}/.git`]);
2903
3379
  if (present.exitCode !== 0) {
2904
3380
  await session.removeDir(`/workspace/repos/${r.name}`);
@@ -2970,48 +3446,124 @@ export class Orchestrator {
2970
3446
  }
2971
3447
 
2972
3448
  /**
2973
- * P7 (MEDIUM-3): Dedicated Unix socket server for 'bond-app pr' channel.
2974
- * 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).
2975
3454
  */
2976
- ensureRunSocketServer(runId: string): string {
2977
- const existing = this.runServers.get(runId);
2978
- 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
+ }
3463
+
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
+ };
2979
3471
 
2980
- const socketDir = path.join(os.tmpdir(), `bond-app-sock-${runId}`);
2981
- fs.mkdirSync(socketDir, { recursive: true, mode: 0o777 });
2982
- const hostSocketPath = path.join(socketDir, 'bond-app.sock');
2983
- try { fs.rmSync(hostSocketPath, { force: true }); } catch {}
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
+ );
2984
3479
 
2985
- const socketServer = http.createServer(async (req, res) => {
2986
- if (req.method === 'POST' && req.url === '/pr') {
2987
- try {
2988
- const delivered = await this.deliverRun(runId);
2989
- const isSuccess = delivered.state === 'finished' && Boolean(delivered.pr_url);
2990
- res.writeHead(isSuccess ? 200 : 500, { 'Content-Type': 'application/json' });
2991
- res.end(JSON.stringify({
2992
- ok: isSuccess,
2993
- state: delivered.state,
2994
- pr_url: delivered.pr_url,
2995
- pr_number: delivered.pr_number,
2996
- error: delivered.failure_reason,
2997
- }));
2998
- } catch (err) {
2999
- const msg = String((err as Error).message || err);
3000
- res.writeHead(400, { 'Content-Type': 'application/json' });
3001
- res.end(JSON.stringify({ ok: false, error: msg }));
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);
3002
3549
  }
3003
- } else {
3004
- res.writeHead(404);
3005
- res.end();
3006
3550
  }
3007
3551
  });
3008
- socketServer.on('error', () => {});
3009
- socketServer.listen(hostSocketPath, () => {
3010
- 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
+ }
3011
3563
  });
3012
- socketServer.unref();
3013
- this.runServers.set(runId, { server: socketServer, socketDir });
3014
- return socketDir;
3564
+
3565
+ this.runPrWatchers.set(runId, { token, stop });
3566
+ return { token };
3015
3567
  }
3016
3568
 
3017
3569
  private async internalStartRun(runId: string, options: TestStartRunOptions = {}): Promise<Run> {
@@ -3030,7 +3582,7 @@ export class Orchestrator {
3030
3582
  // container only on stdin (D8).
3031
3583
  // P1 (plan bond-app-azure-jira): the clone token is the one of the repo's host — the
3032
3584
  // GitHub token as always, or the Azure DevOps PAT for an Azure Repos ticket.
3033
- const onAzure = ticket.mode !== 'hub' && repoHostOf(ticket.repo_url) === 'azure';
3585
+ const onAzure = repoHostOf(ticket.repo_url) === 'azure';
3034
3586
  const githubToken = options.skipClone
3035
3587
  ? undefined
3036
3588
  : onAzure
@@ -3041,7 +3593,7 @@ export class Orchestrator {
3041
3593
  throw onAzure ? new AzureDevOpsCredentialMissingError() : new GitHubCredentialMissingError();
3042
3594
  }
3043
3595
  if (options.githubToken && !onAzure) this.runTokens.set(runId, options.githubToken);
3044
- if (!(ticket.mode === 'hub' ? validateGitHubUrl(ticket.repo_url) : validateRepoUrl(ticket.repo_url))) {
3596
+ if (!validateRepoUrl(ticket.repo_url)) {
3045
3597
  throw new ValidationError(`Invalid repo_url '${ticket.repo_url}'`);
3046
3598
  }
3047
3599
  } else if (ticket.mode === 'hub') {
@@ -3163,10 +3715,7 @@ export class Orchestrator {
3163
3715
  try {
3164
3716
  assertQueued();
3165
3717
 
3166
- // P7: Dedicated Unix socket server for 'bond-app pr' channel
3167
- const socketDir = this.ensureRunSocketServer(run.id);
3168
-
3169
- const extraMounts = [...(options.extraMounts ?? []), `${socketDir}:/var/run/bond-app`];
3718
+ const extraMounts = [...(options.extraMounts ?? [])];
3170
3719
 
3171
3720
  // 1. Create dedicated user-defined network per run
3172
3721
  const networkName = await this.dockerClient.createNetwork(run.id, this.config.instanceId);
@@ -3203,7 +3752,9 @@ export class Orchestrator {
3203
3752
 
3204
3753
  assertQueued();
3205
3754
 
3206
- // 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
+
3207
3758
  const bondAppScript = `#!/bin/sh
3208
3759
  set -e
3209
3760
 
@@ -3217,34 +3768,53 @@ if [ "$#" -gt 1 ]; then
3217
3768
  exit 1
3218
3769
  fi
3219
3770
 
3220
- SOCK="/var/run/bond-app/bond-app.sock"
3221
- if [ ! -S "$SOCK" ]; then
3222
- 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
3223
3775
  exit 1
3224
3776
  fi
3225
3777
 
3226
- if command -v curl >/dev/null 2>&1; then
3227
- RES=$(curl -s -S --max-time 600 --unix-socket "$SOCK" -X POST http://localhost/pr)
3228
- else
3229
- RES=$(node -e "
3230
- const http = require('http');
3231
- const req = http.request({ socketPath: '$SOCK', path: '/pr', method: 'POST', timeout: 600000 }, (res) => {
3232
- let data = '';
3233
- res.on('data', (c) => data += c);
3234
- res.on('end', () => { process.stdout.write(data); process.exit(res.statusCode === 200 ? 0 : 1); });
3235
- });
3236
- req.on('timeout', () => { req.destroy(); console.error('timeout'); process.exit(1); });
3237
- req.on('error', (e) => { console.error(e.message); process.exit(1); });
3238
- req.end();
3239
- ")
3778
+ . "$PR_ENV"
3779
+ if [ -z "$BOND_APP_PR_TOKEN" ]; then
3780
+ echo "Error: bond-app PR token missing" >&2
3781
+ exit 1
3240
3782
  fi
3241
3783
 
3242
- echo "$RES"
3243
- if echo "$RES" | grep -q '"ok":true' && echo "$RES" | grep -q '"pr_url"'; then
3244
- exit 0
3245
- 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
3246
3791
  exit 1
3247
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
3248
3818
  `;
3249
3819
 
3250
3820
  await this.dockerClient.injectStdin(
@@ -3292,11 +3862,12 @@ fi
3292
3862
 
3293
3863
  assertQueued();
3294
3864
 
3295
- // 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)
3296
3866
  const targetBranch = ticket.target_branch || `feat/${ticket.id}`;
3297
3867
  const baseBranch = ticket.base_branch || 'main';
3868
+ const fromRemoteBranch = Boolean(ticket.source_pr_url);
3298
3869
 
3299
- if (!options.allowExistingRemoteBranch) {
3870
+ if (!fromRemoteBranch && !options.allowExistingRemoteBranch) {
3300
3871
  // M-C: Use local rev-parse to check remote branch existence locally and fail closed
3301
3872
  const revParseRes = await this.dockerClient.exec(
3302
3873
  containerInfo.containerName,
@@ -3311,15 +3882,23 @@ fi
3311
3882
  }
3312
3883
  }
3313
3884
 
3885
+ const startPoint = fromRemoteBranch ? `origin/${targetBranch}` : `origin/${baseBranch}`;
3314
3886
  const branchRes = await this.dockerClient.exec(
3315
3887
  containerInfo.containerName,
3316
- ['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],
3317
3891
  'runner',
3318
3892
  15000
3319
3893
  );
3320
3894
  if (branchRes.exitCode !== 0) {
3321
3895
  throw new Error(`Git branch checkout failed with code ${branchRes.exitCode}: ${branchRes.stderr}`);
3322
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 });
3323
3902
 
3324
3903
  assertQueued();
3325
3904
  }
@@ -3358,9 +3937,16 @@ fi
3358
3937
  assertQueued();
3359
3938
  this.runRepo.update(run.id, {});
3360
3939
  };
3940
+ const tokenForRepo = (url: string) =>
3941
+ repoHostOf(url) === 'github' && options.githubToken ? options.githubToken : this.repoAccessFor(url, runId).token;
3361
3942
  const mounted = ticket.hub_url
3362
- ? await session.mountExisting(ticket.hub_url, ticket.hub_base || 'main', githubToken!)
3363
- : 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);
3364
3950
  this.mountFailures.set(runId, mounted.inaccessible);
3365
3951
  assertQueued();
3366
3952
  if (!this.setState(run.id, 'queued', 'analyzing', null, { started_at: new Date().toISOString() })) {
@@ -3372,6 +3958,7 @@ fi
3372
3958
 
3373
3959
  if (!options.skipClone) {
3374
3960
  await this.bondifyRepo(containerInfo.containerName, ticket, run.id);
3961
+ await this.syncBondRepo(containerInfo.containerName, ticket, run.id);
3375
3962
  }
3376
3963
 
3377
3964
  assertQueued();
@@ -3478,6 +4065,27 @@ fi
3478
4065
  }
3479
4066
  }
3480
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
+
3481
4089
  /**
3482
4090
  * P3: the command for the run's hc terminal: BOND_APP_AGENT_COMMAND if set, else the
3483
4091
  * ticket's agent with the ticket prompt as its first message (interactive, so the user
@@ -3490,8 +4098,7 @@ fi
3490
4098
  if (!isValidAgent(ticket.agent)) {
3491
4099
  throw new ValidationError(`Unsupported agent '${ticket.agent}'`);
3492
4100
  }
3493
- const story = [ticket.story ?? '', ticket.prompt ?? ''].filter((s) => s.trim()).join('\n\n');
3494
- const prompt = (promptOverride ?? story).trim();
4101
+ const prompt = this.initialPromptFor(ticket, promptOverride);
3495
4102
  // P4 & D-M1: the ticket's model for pi (`--model provider/id`), or default_model if ticket has none.
3496
4103
  const defaultModel = ticket.agent === 'pi' ? this.settingsRepo?.getSetupSelection?.()?.default_model : null;
3497
4104
  const model = ticket.agent === 'pi' ? (ticket.model || defaultModel) : null;
@@ -3530,8 +4137,7 @@ fi
3530
4137
  ticket: Ticket,
3531
4138
  promptOverride?: string
3532
4139
  ): Promise<string[]> {
3533
- const story = [ticket.story ?? '', ticket.prompt ?? ''].filter((s) => s.trim()).join('\n\n');
3534
- const prompt = (promptOverride ?? story).trim();
4140
+ const prompt = this.initialPromptFor(ticket, promptOverride);
3535
4141
  if (!prompt) return [];
3536
4142
  if (!prompt.includes('\n')) return [prompt];
3537
4143
  if (ticket.agent === 'pi' && containerName && (await this.writeTaskFile(containerName, prompt))) {
@@ -3687,6 +4293,37 @@ fi
3687
4293
  }
3688
4294
  }
3689
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
+
3690
4327
  /**
3691
4328
  * D-G (image plan): the launch command is `bond tui --agent <agente>` - bond is the
3692
4329
  * harness (skills, AGENTS.md, sync, decisions, the rich agent bar); the ticket prompt
@@ -3745,11 +4382,10 @@ fi
3745
4382
  * periodic sweep retries it.
3746
4383
  */
3747
4384
  async teardownRunResources(runId: string, containerName?: string | null): Promise<void> {
3748
- const s = this.runServers.get(runId);
3749
- if (s) {
3750
- try { s.server.close(); } catch {}
3751
- try { fs.rmSync(s.socketDir, { recursive: true, force: true }); } catch {}
3752
- this.runServers.delete(runId);
4385
+ const w = this.runPrWatchers.get(runId);
4386
+ if (w) {
4387
+ try { w.stop(); } catch {}
4388
+ this.runPrWatchers.delete(runId);
3753
4389
  }
3754
4390
 
3755
4391
  const cName = containerName || `bond-app-${runId}`;