@jmanuelcorral/bond-app 0.1.3 → 0.1.4

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.
@@ -18,15 +18,17 @@ import {
18
18
  assertPushTarget,
19
19
  bundlePathFor,
20
20
  BUNDLE_PATH,
21
+ COMMIT_EXIT,
21
22
  COMMIT_SCRIPT,
22
23
  PUSH_EXIT,
23
24
  PUSH_SCRIPT,
24
25
  PushNotAllowedError,
25
26
  pullRequestBody,
26
27
  tail,
28
+ TREE_SCRIPT,
27
29
  } from './delivery.ts';
28
30
  import { HubMountError, HubSession, proposeUrls } from './hub-session.ts';
29
- import { HUB_DIR, agentGaps, analysisPrompt, buildAnalysis, fixedGaps, parseAgentAnswer, repoNameFromUrl, teamAgentFor, teamAgents, type HubToml } from './hub.ts';
31
+ import { HUB_DIR, NAME_RE, agentGaps, analysisPrompt, buildAnalysis, fixedGaps, parseAgentAnswer, repoNameFromUrl, teamAgentFor, teamAgents, type HubToml } from './hub.ts';
30
32
  import {
31
33
  validateGitHubUrl,
32
34
  validateGitHubIssueUrl,
@@ -43,6 +45,34 @@ import {
43
45
  } from '../types.ts';
44
46
  import type { AppConfig } from '../config.ts';
45
47
 
48
+ export class NotFoundError extends Error {
49
+ constructor(message: string) {
50
+ super(message);
51
+ this.name = 'NotFoundError';
52
+ }
53
+ }
54
+
55
+ export class ConflictError extends Error {
56
+ constructor(message: string) {
57
+ super(message);
58
+ this.name = 'ConflictError';
59
+ }
60
+ }
61
+
62
+ export class JsonParseError extends Error {
63
+ constructor(message: string) {
64
+ super(message);
65
+ this.name = 'JsonParseError';
66
+ }
67
+ }
68
+
69
+ export class PayloadTooLargeError extends Error {
70
+ constructor(message: string) {
71
+ super(message);
72
+ this.name = 'PayloadTooLargeError';
73
+ }
74
+ }
75
+
46
76
  export class UnmergedBranchError extends Error {
47
77
  public readonly repo: string;
48
78
  public readonly branch: string;
@@ -117,6 +147,20 @@ export class Orchestrator {
117
147
  private inFlightTerminations = new Set<string>();
118
148
  private startingRuns = new Set<string>();
119
149
  private isReconciling = false;
150
+ // L2: Cancellation requested while run is starting
151
+ private cancellationRequested = new Set<string>();
152
+
153
+ get startingRunsCount(): number {
154
+ return this.startingRuns.size;
155
+ }
156
+
157
+ get inFlightTerminationsCount(): number {
158
+ return this.inFlightTerminations.size;
159
+ }
160
+
161
+ get isReconcilingInProgress(): boolean {
162
+ return this.isReconciling;
163
+ }
120
164
  // N-1 (P1 debt): strikes per run for consecutive periodic sweeps with the container not Up.
121
165
  private missingContainerStrikes = new Map<string, number>();
122
166
  // P2 criterion 7: guard against concurrent image rebuilds.
@@ -196,7 +240,7 @@ export class Orchestrator {
196
240
  */
197
241
  getAgentConfigPath(agent: string): string {
198
242
  if (!isValidAgent(agent)) {
199
- throw new Error(`Unsupported agent '${agent}' (N8)`);
243
+ throw new ValidationError(`Unsupported agent '${agent}' (N8)`);
200
244
  }
201
245
  switch (agent) {
202
246
  case 'pi':
@@ -457,6 +501,15 @@ export class Orchestrator {
457
501
  continue;
458
502
  }
459
503
  try {
504
+ // Criterion 4: sweep networks with grace period, matching orphan container policy
505
+ const insp = await this.dockerClient.inspectNetwork(n.name);
506
+ if (!insp) continue;
507
+ if (typeof insp.Created === 'string') {
508
+ const createdTime = new Date(insp.Created).getTime();
509
+ if (Date.now() - createdTime <= gracePeriodMs) {
510
+ continue;
511
+ }
512
+ }
460
513
  await this.dockerClient.removeNetwork(n.name);
461
514
  orphanedNetworksRemoved.push(n.name);
462
515
  } catch {
@@ -675,7 +728,7 @@ export class Orchestrator {
675
728
  validateTransition(from, to);
676
729
  const { updated, run } = this.runRepo.updateStateConditionally(runId, from, to, {
677
730
  ...extra,
678
- failure_reason: reason !== undefined ? reason : undefined,
731
+ failure_reason: reason !== undefined ? reason : (from === 'blocked' && to !== 'blocked' ? null : undefined),
679
732
  });
680
733
  if (!updated || !run) return false;
681
734
  this.ticketRepo.updateStatus(run.ticket_id, to);
@@ -933,7 +986,7 @@ export class Orchestrator {
933
986
  const existing = this.deliveries.get(runId);
934
987
  if (existing) return existing;
935
988
  const run = this.runRepo.get(runId);
936
- if (!run) throw new Error(`Run '${runId}' not found`);
989
+ if (!run) throw new NotFoundError(`Run '${runId}' not found`);
937
990
  if (run.state !== 'running' && run.state !== 'verifying' && run.state !== 'finished') {
938
991
  throw new InvalidStateTransitionError(run.state, 'verifying');
939
992
  }
@@ -945,6 +998,41 @@ export class Orchestrator {
945
998
  return p;
946
999
  }
947
1000
 
1001
+ /**
1002
+ * D2: Retry a delivery step (push, PR) up to 3 times with growing backoff.
1003
+ * If exhausted, throws the last error so delivery blocks with the failure reason.
1004
+ */
1005
+ private async retryDeliveryStep<T>(
1006
+ stepName: string,
1007
+ run: Run,
1008
+ fn: (attempt: number) => Promise<T>,
1009
+ delays: number[] = this.config.deliveryRetryDelaysMs ?? [1000, 2000],
1010
+ shouldRetry: (err: unknown) => boolean = () => true
1011
+ ): Promise<T> {
1012
+ let attempt = 1;
1013
+ const maxAttempts = delays.length + 1;
1014
+ while (true) {
1015
+ try {
1016
+ return await fn(attempt);
1017
+ } catch (err) {
1018
+ if (attempt >= maxAttempts || !shouldRetry(err)) {
1019
+ throw err;
1020
+ }
1021
+ const delayMs = delays[attempt - 1] ?? 1000;
1022
+ this.agentEvent(run, `delivery.${stepName}_retry`, {
1023
+ attempt,
1024
+ maxAttempts,
1025
+ delayMs,
1026
+ error: String((err as Error).message || err).slice(0, 200),
1027
+ });
1028
+ if (delayMs > 0) {
1029
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
1030
+ }
1031
+ attempt++;
1032
+ }
1033
+ }
1034
+ }
1035
+
948
1036
  private async runDelivery(runId: string): Promise<Run> {
949
1037
  const run = this.runRepo.get(runId)!;
950
1038
  const ticket = this.ticketRepo.get(run.ticket_id);
@@ -958,6 +1046,25 @@ export class Orchestrator {
958
1046
  const ctr = run.container_name;
959
1047
  try {
960
1048
  // 1. Verification (criterion 3): every command must pass, as runner, in the clone.
1049
+ // MEDIUM-2: capture working tree before running verification commands
1050
+ let expectedTree = '';
1051
+ if (ticket.verify_commands.length > 0) {
1052
+ const treeRes = await this.dockerClient.exec(
1053
+ ctr,
1054
+ ['sh', '-c', TREE_SCRIPT, 'runner-tree', '/workspace/repo'],
1055
+ 'runner',
1056
+ 30_000
1057
+ );
1058
+ if (treeRes.exitCode === 0) {
1059
+ expectedTree = /tree=([0-9a-f]{40})\b/.exec(treeRes.stdout)?.[1] || '';
1060
+ }
1061
+ // M-1: Fail closed if tree capture fails with non-empty verify_commands
1062
+ if (!expectedTree) {
1063
+ this.setState(runId, 'verifying', 'blocked', `delivery_failed: working tree capture failed before verification (exit ${treeRes.exitCode}): ${treeRes.stderr || treeRes.stdout}`);
1064
+ return current();
1065
+ }
1066
+ }
1067
+
961
1068
  const verification: string[] = [];
962
1069
  for (const cmd of ticket.verify_commands) {
963
1070
  let res: { stdout: string; stderr: string; exitCode: number };
@@ -977,6 +1084,25 @@ export class Orchestrator {
977
1084
  if (res.exitCode !== 0) {
978
1085
  return await this.verificationFailed(runId, ticket, cmd, res);
979
1086
  }
1087
+ // M-3: Verify intermediate tree after each verification command to close flip-flops
1088
+ if (expectedTree) {
1089
+ const intermediateTreeRes = await this.dockerClient.exec(
1090
+ ctr,
1091
+ ['sh', '-c', TREE_SCRIPT, 'runner-tree', '/workspace/repo'],
1092
+ 'runner',
1093
+ 30_000
1094
+ );
1095
+ const intermediateTree = intermediateTreeRes.exitCode === 0
1096
+ ? /tree=([0-9a-f]{40})\b/.exec(intermediateTreeRes.stdout)?.[1] || ''
1097
+ : '';
1098
+ if (intermediateTree !== expectedTree) {
1099
+ return await this.verificationFailed(runId, ticket, `intermediate working tree check after '${cmd}'`, {
1100
+ stdout: intermediateTreeRes.stdout,
1101
+ stderr: `working tree changed during verification (${intermediateTree || 'capture failed'} != ${expectedTree})`,
1102
+ exitCode: COMMIT_EXIT.treeChanged,
1103
+ });
1104
+ }
1105
+ }
980
1106
  verification.push(`\`${cmd}\`: OK`);
981
1107
  }
982
1108
  this.agentEvent(run, 'verification.passed', { commands: ticket.verify_commands.length });
@@ -991,6 +1117,9 @@ export class Orchestrator {
991
1117
  `${ticket.title}\n\nbond-app run ${runId} (ticket ${ticket.id})`,
992
1118
  login || 'bond-app',
993
1119
  login ? `${login}@users.noreply.github.com` : 'bond-app@localhost',
1120
+ '/workspace/repo',
1121
+ BUNDLE_PATH,
1122
+ expectedTree,
994
1123
  ],
995
1124
  'runner',
996
1125
  120_000
@@ -1006,23 +1135,66 @@ export class Orchestrator {
1006
1135
  // 3. Push only the ticket's branch to the ticket's repo (criterion 2). Root decides
1007
1136
  // on the exact object pushed: it is the committed head, adds commits to the real base
1008
1137
  // from GitHub and changes nothing under .github/workflows (review HIGH-1).
1138
+ // D2: push retries up to 3 times with growing backoff; exhausted -> blocked.
1009
1139
  const token = this.runTokens.get(runId) || this.settingsRepo.getGitHubToken();
1010
1140
  if (!token) throw new GitHubCredentialMissingError();
1011
- const pushed = await this.pushRunBranch(runId, ticket.repo_url, ticket.target_branch, headSha, token);
1141
+ const shouldRetryPush = (err: unknown) => {
1142
+ const msg = String((err as Error).message || err);
1143
+ return !msg.includes('nothing to deliver') && !msg.includes('.github/workflows') && !msg.includes('does not match the committed head');
1144
+ };
1145
+ const pushed = await this.retryDeliveryStep(
1146
+ 'push',
1147
+ run,
1148
+ () => this.pushRunBranch(runId, ticket.repo_url, ticket.target_branch, headSha, token),
1149
+ this.config.deliveryRetryDelaysMs,
1150
+ shouldRetryPush
1151
+ );
1012
1152
  if (pushed === 'nothing_to_deliver') {
1013
1153
  this.agentEvent(run, 'delivery.no_changes', { branch: ticket.target_branch });
1014
1154
  return await this.terminateRun(runId, 'failed', 'no_changes');
1015
1155
  }
1156
+ // LOW-4: record pushed branch immediately so a cancel between push and PR leaves branch linked
1157
+ this.runRepo.update(runId, {
1158
+ repo_states: {
1159
+ [ticket.repo_url]: {
1160
+ url: ticket.repo_url,
1161
+ base: ticket.base_branch,
1162
+ branch: ticket.target_branch,
1163
+ status: 'pushed',
1164
+ sha: headSha,
1165
+ },
1166
+ },
1167
+ });
1016
1168
  if (!stillVerifying()) return current();
1017
1169
 
1018
- // 4. The pull request, with the ticket summary (criterion 1).
1019
- const pr = await this.github.openPullRequest(token, ticket.repo_url, {
1020
- head: ticket.target_branch,
1021
- base: ticket.base_branch,
1022
- title: ticket.title,
1023
- body: pullRequestBody(ticket, run, verification),
1170
+ // 4. The pull request, with the ticket summary (criterion 1 & D2).
1171
+ // D2: PR retries up to 3 times with growing backoff; an existing PR is linked.
1172
+ const pr = await this.retryDeliveryStep(
1173
+ 'pr',
1174
+ run,
1175
+ () => this.github.openPullRequest(token, ticket.repo_url, {
1176
+ head: ticket.target_branch,
1177
+ base: ticket.base_branch,
1178
+ title: ticket.title,
1179
+ body: pullRequestBody(ticket, run, verification),
1180
+ }),
1181
+ this.config.deliveryRetryDelaysMs
1182
+ );
1183
+ this.runRepo.update(runId, {
1184
+ pr_url: pr.url,
1185
+ pr_number: pr.number,
1186
+ repo_states: {
1187
+ [ticket.repo_url]: {
1188
+ url: ticket.repo_url,
1189
+ base: ticket.base_branch,
1190
+ branch: ticket.target_branch,
1191
+ status: 'pr_opened',
1192
+ sha: headSha,
1193
+ pr_url: pr.url,
1194
+ pr_number: pr.number,
1195
+ },
1196
+ },
1024
1197
  });
1025
- this.runRepo.update(runId, { pr_url: pr.url, pr_number: pr.number });
1026
1198
  if (!stillVerifying()) {
1027
1199
  // Cancelled while the PR was being opened: keep its link, but the run is over.
1028
1200
  this.agentEvent(run, 'delivery.pr_after_cancel', { pr_url: pr.url });
@@ -1128,7 +1300,7 @@ export class Orchestrator {
1128
1300
  */
1129
1301
  async nudgeRun(runId: string, message: string): Promise<Run> {
1130
1302
  const run = this.runRepo.get(runId);
1131
- if (!run) throw new Error(`Run '${runId}' not found`);
1303
+ if (!run) throw new NotFoundError(`Run '${runId}' not found`);
1132
1304
  const text = typeof message === 'string' ? message.trim() : '';
1133
1305
  if (!text || text.length > 4000) throw new ValidationError("'message' must be 1 to 4000 characters");
1134
1306
  if (this.deliveries.has(runId)) {
@@ -1138,7 +1310,7 @@ export class Orchestrator {
1138
1310
  throw new ValidationError(`Only a blocked or running run can be nudged (this one is '${run.state}')`);
1139
1311
  }
1140
1312
  const ticket = this.ticketRepo.get(run.ticket_id);
1141
- if (!ticket) throw new Error(`Ticket '${run.ticket_id}' not found`);
1313
+ if (!ticket) throw new NotFoundError(`Ticket '${run.ticket_id}' not found`);
1142
1314
  if (ticket.mode === 'hub') return this.nudgeTeam(run, ticket, text);
1143
1315
  const terminal = await this.notifyAgent(runId, ticket, text);
1144
1316
  this.agentEvent(run, 'nudge', { terminal, message: text, from_state: run.state });
@@ -1211,7 +1383,7 @@ export class Orchestrator {
1211
1383
  leaderStatus = 'blocked';
1212
1384
  } else if ((leader.status === 'idle' || leader.status === 'done') && (leader.turn ?? 0) > 0) {
1213
1385
  leaderState = 'bloqueado';
1214
- leaderStatus = 'idle-waiting';
1386
+ leaderStatus = 'en espera';
1215
1387
  } else if (leader.status === 'working') {
1216
1388
  leaderState = 'trabajando';
1217
1389
  leaderStatus = 'working';
@@ -1358,7 +1530,7 @@ export class Orchestrator {
1358
1530
  leaderStatus = 'blocked';
1359
1531
  } else if ((leaderAgent.agent_status === 'idle' || leaderAgent.agent_status === 'done') && seq > 0) {
1360
1532
  leaderState = 'bloqueado';
1361
- leaderStatus = 'idle-waiting';
1533
+ leaderStatus = 'en espera';
1362
1534
  } else if (leaderAgent.agent_status === 'working') {
1363
1535
  leaderState = 'trabajando';
1364
1536
  leaderStatus = 'working';
@@ -1415,9 +1587,9 @@ export class Orchestrator {
1415
1587
  token?: string
1416
1588
  ): Promise<'pushed' | 'nothing_to_deliver'> {
1417
1589
  const run = this.runRepo.get(runId);
1418
- if (!run) throw new Error(`Run '${runId}' not found`);
1590
+ if (!run) throw new NotFoundError(`Run '${runId}' not found`);
1419
1591
  const ticket = this.ticketRepo.get(run.ticket_id);
1420
- if (!ticket) throw new Error(`Ticket '${run.ticket_id}' not found`);
1592
+ if (!ticket) throw new NotFoundError(`Ticket '${run.ticket_id}' not found`);
1421
1593
  assertPushTarget(ticket, repoUrl, branch);
1422
1594
  if (!/^[0-9a-f]{40}$/.test(expectedSha)) throw new Error('Invalid expected head sha');
1423
1595
  if (!run.container_name) throw new Error('The run has no container');
@@ -1505,11 +1677,30 @@ export class Orchestrator {
1505
1677
 
1506
1678
  try {
1507
1679
  // 1. Verification in each repo still to deliver (criterion 3 of P4, per repo).
1680
+ // MEDIUM-2: capture working tree before running verification commands
1681
+ const expectedTrees: Record<string, string> = {};
1508
1682
  const verification: string[] = [];
1509
1683
  const secs = Math.max(1, Math.floor(this.config.verifyTimeoutMs / 1000));
1510
1684
  for (const t of targets.filter((x) => !x.hub && !done(x.key))) {
1511
1685
  const wt = await session.worktreeOf(t.dir, branch);
1512
1686
  if (!wt) continue;
1687
+ if (ticket.verify_commands.length > 0) {
1688
+ const treeRes = await this.dockerClient.exec(
1689
+ run.container_name,
1690
+ ['sh', '-c', TREE_SCRIPT, 'runner-tree', wt],
1691
+ 'runner',
1692
+ 30_000
1693
+ );
1694
+ let tree = '';
1695
+ if (treeRes.exitCode === 0) {
1696
+ tree = /tree=([0-9a-f]{40})\b/.exec(treeRes.stdout)?.[1] || '';
1697
+ if (tree) expectedTrees[t.key] = tree;
1698
+ }
1699
+ // M-1: Fail closed if tree capture fails with non-empty verify_commands
1700
+ if (!tree) {
1701
+ return await this.verificationFailed(runId, ticket, `${t.key}: working tree capture failed before verification (exit ${treeRes.exitCode})`, treeRes);
1702
+ }
1703
+ }
1513
1704
  for (const cmd of ticket.verify_commands) {
1514
1705
  let res: { stdout: string; stderr: string; exitCode: number };
1515
1706
  try {
@@ -1524,6 +1715,25 @@ export class Orchestrator {
1524
1715
  }
1525
1716
  if (!stillVerifying()) return current();
1526
1717
  if (res.exitCode !== 0) return await this.verificationFailed(runId, ticket, `${t.key}: ${cmd}`, res);
1718
+ // M-3: Verify intermediate tree after each verification command to close flip-flops
1719
+ if (expectedTrees[t.key]) {
1720
+ const intermediateTreeRes = await this.dockerClient.exec(
1721
+ run.container_name,
1722
+ ['sh', '-c', TREE_SCRIPT, 'runner-tree', wt],
1723
+ 'runner',
1724
+ 30_000
1725
+ );
1726
+ const intermediateTree = intermediateTreeRes.exitCode === 0
1727
+ ? /tree=([0-9a-f]{40})\b/.exec(intermediateTreeRes.stdout)?.[1] || ''
1728
+ : '';
1729
+ if (intermediateTree !== expectedTrees[t.key]) {
1730
+ return await this.verificationFailed(runId, ticket, `${t.key}: intermediate working tree check after '${cmd}'`, {
1731
+ stdout: intermediateTreeRes.stdout,
1732
+ stderr: `working tree changed during verification (${intermediateTree || 'capture failed'} != ${expectedTrees[t.key]})`,
1733
+ exitCode: COMMIT_EXIT.treeChanged,
1734
+ });
1735
+ }
1736
+ }
1527
1737
  verification.push(`${t.key}: \`${cmd}\`: OK`);
1528
1738
  }
1529
1739
  }
@@ -1555,7 +1765,7 @@ export class Orchestrator {
1555
1765
  `${ticket.title}\n\nbond-app run ${runId} (ticket ${ticket.id})`,
1556
1766
  login || 'bond-app',
1557
1767
  login ? `${login}@users.noreply.github.com` : 'bond-app@localhost',
1558
- wt, bundle,
1768
+ wt, bundle, expectedTrees[t.key] || '',
1559
1769
  ],
1560
1770
  'runner',
1561
1771
  120_000
@@ -1570,7 +1780,17 @@ export class Orchestrator {
1570
1780
  sha = await session.bundleBranch(t.dir, branch, bundle);
1571
1781
  }
1572
1782
  if (!stillVerifying()) return current();
1573
- const pushed = await this.pushBundle(run, t.url, branch, bundle, sha, t.base, token);
1783
+ const shouldRetryPush = (err: unknown) => {
1784
+ const msg = String((err as Error).message || err);
1785
+ return !msg.includes('nothing to deliver') && !msg.includes('.github/workflows') && !msg.includes('does not match the committed head');
1786
+ };
1787
+ const pushed = await this.retryDeliveryStep(
1788
+ `push_${t.key}`,
1789
+ run,
1790
+ () => this.pushBundle(run, t.url, branch, bundle, sha, t.base, token),
1791
+ this.config.deliveryRetryDelaysMs,
1792
+ shouldRetryPush
1793
+ );
1574
1794
  st.sha = sha;
1575
1795
  if (pushed === 'nothing_to_deliver') {
1576
1796
  st.status = 'no_changes';
@@ -1583,12 +1803,17 @@ export class Orchestrator {
1583
1803
  }
1584
1804
  if (!stillVerifying()) return current();
1585
1805
  const others = targets.filter((o) => o !== t).map(nameOf);
1586
- const pr = await this.github.openPullRequest(token, t.url, {
1587
- head: branch,
1588
- base: t.base,
1589
- title: ticket.title,
1590
- body: pullRequestBody(ticket, run, verification, { base: t.base, others }),
1591
- });
1806
+ const pr = await this.retryDeliveryStep(
1807
+ `pr_${t.key}`,
1808
+ run,
1809
+ () => this.github.openPullRequest(token, t.url, {
1810
+ head: branch,
1811
+ base: t.base,
1812
+ title: ticket.title,
1813
+ body: pullRequestBody(ticket, run, verification, { base: t.base, others }),
1814
+ }),
1815
+ this.config.deliveryRetryDelaysMs
1816
+ );
1592
1817
  st.status = 'pr_opened';
1593
1818
  st.pr_url = pr.url;
1594
1819
  st.pr_number = pr.number;
@@ -1666,7 +1891,7 @@ export class Orchestrator {
1666
1891
 
1667
1892
  private hubSessionOf(run: Run): HubSession {
1668
1893
  if (!run.container_name) throw new HubMountError('The run has no container');
1669
- return new HubSession(this.dockerClient, run.container_name);
1894
+ return new HubSession(this.dockerClient, run.container_name, this.hcClient, run.hc_machine || machineNameForRun(run.id));
1670
1895
  }
1671
1896
 
1672
1897
  private tokenFor(runId: string): string {
@@ -1683,9 +1908,9 @@ export class Orchestrator {
1683
1908
  */
1684
1909
  async analyzeHub(runId: string): Promise<HubAnalysis> {
1685
1910
  const run = this.runRepo.get(runId);
1686
- if (!run) throw new Error(`Run '${runId}' not found`);
1911
+ if (!run) throw new NotFoundError(`Run '${runId}' not found`);
1687
1912
  const ticket = this.ticketRepo.get(run.ticket_id);
1688
- if (!ticket) throw new Error(`Ticket '${run.ticket_id}' not found`);
1913
+ if (!ticket) throw new NotFoundError(`Ticket '${run.ticket_id}' not found`);
1689
1914
  const session = this.hubSessionOf(run);
1690
1915
  const warnings: string[] = [];
1691
1916
 
@@ -1746,7 +1971,9 @@ export class Orchestrator {
1746
1971
  let res: { stdout: string; stderr: string; exitCode: number };
1747
1972
  try {
1748
1973
  if (argv[0] === 'pi') await this.injectCredentials(run.container_name!, ['pi'], home);
1749
- res = await session.runAgent(argv, analysisPrompt(ticket, hub, this.analysisNotes.get(runId)), this.config.analysisTimeoutMs, home);
1974
+ const note = this.analysisNotes.get(runId);
1975
+ this.analysisNotes.delete(runId);
1976
+ res = await session.runAgent(argv, analysisPrompt(ticket, hub, note), this.config.analysisTimeoutMs, home);
1750
1977
  } finally {
1751
1978
  await session.removeDir(home);
1752
1979
  }
@@ -1770,20 +1997,22 @@ export class Orchestrator {
1770
1997
  warnings.push('Sin agente de hub: solo cuentan las comprobaciones fijas');
1771
1998
  }
1772
1999
 
2000
+ if (!ticket.hub_url) {
2001
+ warnings.push('El hub se creó desde una lista de repositorios y no tiene URL remota: los cambios en el hub no se entregarán');
2002
+ }
2003
+
1773
2004
  return buildAnalysis({ hub, created: !ticket.hub_url, gaps, warnings, agentSummary });
1774
2005
  }
1775
2006
 
1776
- /** The hub agent's command: the override, or the ticket's pi in print mode, read-only. */
2007
+ /** The hub agent's command: the override, or pi in print mode, read-only. */
1777
2008
  private analysisArgv(ticket: Ticket): string[] | null {
1778
2009
  const cmd = this.config.analysisCommand;
1779
2010
  if (cmd === 'off') return null;
1780
2011
  if (cmd) return [...cmd];
1781
- if (ticket.agent !== 'pi') return null;
1782
- // Review M2: --no-approve ignores the hub's .pi (extensions, MCP, settings): the hub's
1783
- // content is untrusted until a person approves the run.
2012
+ // Hub agent runs read-only pi in print mode regardless of the ticket's agent (P3 criterion 5)
1784
2013
  const argv = ['pi', '-p', '--no-session', '--no-approve', '--tools', 'read,grep,find,ls'];
1785
- // Review L-4: same model check as the team's.
1786
- if (ticket.model && /^[A-Za-z0-9_./:@-]{1,120}$/.test(ticket.model)) argv.push('--model', ticket.model);
2014
+ // Review L-4 / M-4: pass model only when ticket.agent is pi
2015
+ if (ticket.agent === 'pi' && ticket.model && /^[A-Za-z0-9_./:@-]{1,120}$/.test(ticket.model)) argv.push('--model', ticket.model);
1787
2016
  return argv;
1788
2017
  }
1789
2018
 
@@ -1830,7 +2059,7 @@ export class Orchestrator {
1830
2059
  } catch {
1831
2060
  live = false;
1832
2061
  }
1833
- reused = live && (await session.teamOpen(ticket.target_branch, analysis.repos.length, ticket.team_engine || 'hc'));
2062
+ reused = live && (await session.teamOpen(ticket.target_branch, analysis.repos.length, ticket.team_engine || 'hc', this.hcClient, run.hc_machine || machineNameForRun(run.id)));
1834
2063
  }
1835
2064
  if (!reused) {
1836
2065
  const terminal = await session.launchTeam(this.hcClient, run.hc_machine!, ticket, analysis.repos, {
@@ -1861,7 +2090,7 @@ export class Orchestrator {
1861
2090
  */
1862
2091
  async approveHubFixes(runId: string): Promise<{ run: Run; applied: string[]; failed: string[] }> {
1863
2092
  const run = this.runRepo.get(runId);
1864
- if (!run) throw new Error(`Run '${runId}' not found`);
2093
+ if (!run) throw new NotFoundError(`Run '${runId}' not found`);
1865
2094
  if (run.state !== 'blocked' || run.failure_reason !== 'hub_incomplete' || !run.hub_analysis) {
1866
2095
  throw new ValidationError('Solo se aprueban arreglos de un run bloqueado por un hub incompleto');
1867
2096
  }
@@ -2014,8 +2243,16 @@ export class Orchestrator {
2014
2243
  (t) => t.state === 'live' && t.labels?.['bond.branch'] === ticket.target_branch && t.address
2015
2244
  );
2016
2245
  if (branchTerminals.length > 0) {
2246
+ const errors: string[] = [];
2017
2247
  for (const term of branchTerminals) {
2018
- await this.hcClient.sendText(term.address!, text);
2248
+ try {
2249
+ await this.hcClient.sendText(term.address!, text);
2250
+ } catch (err) {
2251
+ errors.push(`${term.address}: ${(err as Error).message || String(err)}`);
2252
+ }
2253
+ }
2254
+ if (errors.length > 0) {
2255
+ throw new ValidationError(`Fallo al enviar mensaje a terminales: ${errors.join(', ')}`);
2019
2256
  }
2020
2257
  return;
2021
2258
  }
@@ -2023,10 +2260,15 @@ export class Orchestrator {
2023
2260
  (t) => t.state === 'live' && (t.name === 'hub-leader' || t.name === 'hub leader' || t.address?.endsWith('/t1')) && t.address
2024
2261
  );
2025
2262
  if (leader) {
2026
- await this.hcClient.sendText(leader.address!, text);
2027
- return;
2263
+ try {
2264
+ await this.hcClient.sendText(leader.address!, text);
2265
+ return;
2266
+ } catch (err) {
2267
+ throw new ValidationError(`Fallo al enviar mensaje al líder ${leader.address}: ${(err as Error).message || String(err)}`);
2268
+ }
2028
2269
  }
2029
- } catch {
2270
+ } catch (err) {
2271
+ if (err instanceof ValidationError) throw err;
2030
2272
  // Fall back to bond team prompt with BOND_TEAM_ENGINE=hc below
2031
2273
  }
2032
2274
  }
@@ -2060,6 +2302,8 @@ export class Orchestrator {
2060
2302
  const hub = await session.readHubToml();
2061
2303
  const missing = new Set<string>();
2062
2304
  for (const r of hub.repos) {
2305
+ // P5 debt L-1: validate repo names in unblockHub and prevent _hub_ collision
2306
+ if (!NAME_RE.test(r.name) || r.name === '_hub_') continue;
2063
2307
  if (!r.url || !validateGitHubUrl(r.url)) continue;
2064
2308
  const present = await session.runner(['test', '-e', `${HUB_DIR}/${r.path}/.git`]);
2065
2309
  if (present.exitCode !== 0) {
@@ -2076,7 +2320,7 @@ export class Orchestrator {
2076
2320
  if (!ticket.hub_url) {
2077
2321
  const adds: HubFix[] = ticket.repos
2078
2322
  .map((r) => ({ name: repoNameFromUrl(r.url), url: r.url, base: r.base_branch }))
2079
- .filter((r) => !hub.repos.some((h) => h.name === r.name))
2323
+ .filter((r) => NAME_RE.test(r.name) && r.name !== '_hub_' && !hub.repos.some((h) => h.name === r.name))
2080
2324
  .map((r) => ({ action: 'hub_add' as const, name: r.name, url: r.url, base_branch: r.base }));
2081
2325
  for (const fix of adds) await session.removeDir(`/workspace/repos/${fix.name}`);
2082
2326
  if (adds.length > 0) await session.applyFixes(adds, ticket.target_branch, token);
@@ -2098,14 +2342,14 @@ export class Orchestrator {
2098
2342
  createRun(ticketId: string): Run {
2099
2343
  const ticket = this.ticketRepo.get(ticketId);
2100
2344
  if (!ticket) {
2101
- throw new Error(`Ticket '${ticketId}' not found`);
2345
+ throw new NotFoundError(`Ticket '${ticketId}' not found`);
2102
2346
  }
2103
2347
 
2104
2348
  // M10: Refuse second active run per ticket
2105
2349
  const activeRuns = this.runRepo.listActive();
2106
2350
  const existingActive = activeRuns.find((r) => r.ticket_id === ticketId);
2107
2351
  if (existingActive) {
2108
- throw new Error(`Cannot create a new run: ticket '${ticketId}' already has an active run '${existingActive.id}'`);
2352
+ throw new ValidationError(`Cannot create a new run: ticket '${ticketId}' already has an active run '${existingActive.id}'`);
2109
2353
  }
2110
2354
 
2111
2355
  const run = this.runRepo.create(ticketId);
@@ -2114,10 +2358,14 @@ export class Orchestrator {
2114
2358
  }
2115
2359
 
2116
2360
  /**
2117
- * Start executing a run.
2361
+ * Start executing a run. Filters options so test-only options cannot be passed (P3 criterion 4).
2118
2362
  */
2119
2363
  async startRun(runId: string, options: StartRunOptions = {}): Promise<Run> {
2120
- return this.internalStartRun(runId, options);
2364
+ const filtered: StartRunOptions = {
2365
+ githubToken: typeof options?.githubToken === 'string' ? options.githubToken : undefined,
2366
+ allowExistingRemoteBranch: Boolean(options?.allowExistingRemoteBranch),
2367
+ };
2368
+ return this.internalStartRun(runId, filtered);
2121
2369
  }
2122
2370
 
2123
2371
  /**
@@ -2175,11 +2423,11 @@ export class Orchestrator {
2175
2423
  private async internalStartRun(runId: string, options: TestStartRunOptions = {}): Promise<Run> {
2176
2424
  const run = this.runRepo.get(runId);
2177
2425
  if (!run) {
2178
- throw new Error(`Run '${runId}' not found`);
2426
+ throw new NotFoundError(`Run '${runId}' not found`);
2179
2427
  }
2180
2428
  let ticket = this.ticketRepo.get(run.ticket_id);
2181
2429
  if (!ticket) {
2182
- throw new Error(`Ticket '${run.ticket_id}' not found`);
2430
+ throw new NotFoundError(`Ticket '${run.ticket_id}' not found`);
2183
2431
  }
2184
2432
 
2185
2433
  // L1: Validate input BEFORE creating any resources (network, container, hc machine).
@@ -2396,7 +2644,7 @@ fi
2396
2644
  15000
2397
2645
  );
2398
2646
  if (revParseRes.exitCode === 0) {
2399
- throw new Error(`Remote branch '${targetBranch}' already exists on origin (N4)`);
2647
+ throw new ValidationError(`Remote branch '${targetBranch}' already exists on origin (N4)`);
2400
2648
  } else if (revParseRes.exitCode > 1) {
2401
2649
  throw new Error(`Failed to check remote branch: ${revParseRes.stderr}`);
2402
2650
  }
@@ -2490,52 +2738,63 @@ fi
2490
2738
  startError = err;
2491
2739
  throw err;
2492
2740
  } finally {
2493
- this.startingRuns.delete(runId);
2494
- if (startError) {
2495
- this.runTokens.delete(runId);
2496
- this.mountFailures.delete(runId);
2497
- this.analysisNotes.delete(runId);
2498
- // M-D: Teardown resources unconditionally in finally
2499
- try {
2500
- await this.teardownRunResources(runId, containerName);
2501
- } catch {
2502
- // teardown failure sets cleanup_pending in DB
2503
- }
2741
+ try {
2742
+ if (startError) {
2743
+ this.runTokens.delete(runId);
2744
+ this.mountFailures.delete(runId);
2745
+ this.analysisNotes.delete(runId);
2746
+ // M-D: Teardown resources unconditionally in finally
2747
+ try {
2748
+ await this.teardownRunResources(runId, containerName);
2749
+ } catch {
2750
+ // teardown failure sets cleanup_pending in DB
2751
+ }
2504
2752
 
2505
- // L2: Mark run failed if not already terminal, preserving any concurrent cancellation reason
2506
- const latest = this.runRepo.get(runId);
2507
- if (latest && latest.state !== 'failed' && latest.state !== 'pr_ready') {
2508
- const oldState = latest.state;
2509
- const failureReason =
2510
- startError instanceof ValidationError
2511
- ? 'validation_error'
2512
- : startError instanceof HubMountError
2513
- ? 'hub_mount_failed'
2514
- : 'container_error';
2515
- if (startError instanceof HubMountError) {
2516
- this.agentEvent(latest, 'hub.mount_failed', { error: startError.message.slice(0, 300) });
2753
+ // L2: Wait for in-flight termination so we do not race with concurrent cancelRun
2754
+ while (this.inFlightTerminations.has(runId)) {
2755
+ await new Promise((r) => setTimeout(r, 20));
2517
2756
  }
2518
- const { updated } = this.runRepo.updateStateConditionally(
2519
- runId,
2520
- oldState,
2521
- 'failed',
2522
- {
2523
- failure_reason: failureReason,
2524
- finished_at: new Date().toISOString(),
2757
+
2758
+ // L2: Mark run failed if not already terminal, preserving any concurrent cancellation reason
2759
+ const latest = this.runRepo.get(runId);
2760
+ if (latest && latest.state !== 'failed' && latest.state !== 'pr_ready') {
2761
+ const oldState = latest.state;
2762
+ const failureReason =
2763
+ this.cancellationRequested.has(runId)
2764
+ ? 'cancelled'
2765
+ : startError instanceof ValidationError
2766
+ ? 'validation_error'
2767
+ : startError instanceof HubMountError
2768
+ ? 'hub_mount_failed'
2769
+ : 'container_error';
2770
+ if (startError instanceof HubMountError) {
2771
+ this.agentEvent(latest, 'hub.mount_failed', { error: startError.message.slice(0, 300) });
2772
+ }
2773
+ const { updated } = this.runRepo.updateStateConditionally(
2774
+ runId,
2775
+ oldState,
2776
+ 'failed',
2777
+ {
2778
+ failure_reason: failureReason,
2779
+ finished_at: new Date().toISOString(),
2780
+ }
2781
+ );
2782
+ if (updated) {
2783
+ this.ticketRepo.updateStatus(ticket.id, 'failed');
2784
+ this.eventBus.publish(runId, ticket.id, 'run.state_changed', {
2785
+ run_id: runId,
2786
+ ticket_id: ticket.id,
2787
+ old_state: oldState,
2788
+ new_state: 'failed',
2789
+ reason: failureReason,
2790
+ timestamp: Date.now(),
2791
+ });
2525
2792
  }
2526
- );
2527
- if (updated) {
2528
- this.ticketRepo.updateStatus(ticket.id, 'failed');
2529
- this.eventBus.publish(runId, ticket.id, 'run.state_changed', {
2530
- run_id: runId,
2531
- ticket_id: ticket.id,
2532
- old_state: oldState,
2533
- new_state: 'failed',
2534
- reason: failureReason,
2535
- timestamp: Date.now(),
2536
- });
2537
2793
  }
2538
2794
  }
2795
+ } finally {
2796
+ this.startingRuns.delete(runId);
2797
+ this.cancellationRequested.delete(runId);
2539
2798
  }
2540
2799
  }
2541
2800
  }
@@ -2615,7 +2874,7 @@ fi
2615
2874
  async cancelRun(runId: string, reason: FailureReason = 'cancelled'): Promise<{ durationMs: number; run: Run }> {
2616
2875
  const run = this.runRepo.get(runId);
2617
2876
  if (!run) {
2618
- throw new Error(`Run '${runId}' not found`);
2877
+ throw new NotFoundError(`Run '${runId}' not found`);
2619
2878
  }
2620
2879
 
2621
2880
  const t0 = Date.now();
@@ -2626,11 +2885,18 @@ fi
2626
2885
  return { durationMs: Date.now() - t0, run: this.runRepo.get(runId)! };
2627
2886
  }
2628
2887
 
2629
- const updated = await this.terminateRun(runId, 'failed', reason);
2630
- return {
2631
- durationMs: Date.now() - t0,
2632
- run: updated,
2633
- };
2888
+ this.cancellationRequested.add(runId);
2889
+ try {
2890
+ const updated = await this.terminateRun(runId, 'failed', reason);
2891
+ return {
2892
+ durationMs: Date.now() - t0,
2893
+ run: updated,
2894
+ };
2895
+ } finally {
2896
+ if (!this.startingRuns.has(runId)) {
2897
+ this.cancellationRequested.delete(runId);
2898
+ }
2899
+ }
2634
2900
  }
2635
2901
 
2636
2902
  /**
@@ -2643,7 +2909,7 @@ fi
2643
2909
  async deleteTicket(ticketId: string, options: { force?: boolean } = {}): Promise<{ success: boolean }> {
2644
2910
  const ticket = this.ticketRepo.get(ticketId);
2645
2911
  if (!ticket) {
2646
- throw new Error(`Ticket '${ticketId}' not found`);
2912
+ throw new NotFoundError(`Ticket '${ticketId}' not found`);
2647
2913
  }
2648
2914
 
2649
2915
  const runs = this.runRepo.list({ ticketId });
@@ -2754,7 +3020,7 @@ fi
2754
3020
  requires_force: boolean;
2755
3021
  }> {
2756
3022
  const ticket = this.ticketRepo.get(ticketId);
2757
- if (!ticket) throw new Error(`Ticket '${ticketId}' not found`);
3023
+ if (!ticket) throw new NotFoundError(`Ticket '${ticketId}' not found`);
2758
3024
 
2759
3025
  const runs = this.runRepo.list({ ticketId });
2760
3026
  const latestRun = runs[0] ?? null;
@@ -2853,7 +3119,7 @@ fi
2853
3119
  try {
2854
3120
  const run = this.runRepo.get(runId);
2855
3121
  if (!run) {
2856
- throw new Error(`Run '${runId}' not found`);
3122
+ throw new NotFoundError(`Run '${runId}' not found`);
2857
3123
  }
2858
3124
 
2859
3125
  if (run.state === 'failed' || run.state === 'pr_ready' || run.state === 'finished') {
@@ -2873,9 +3139,24 @@ fi
2873
3139
 
2874
3140
  // Re-read run state after async teardown
2875
3141
  const latest = this.runRepo.get(runId);
2876
- if (!latest || latest.state === 'failed' || latest.state === 'pr_ready' || latest.state === 'finished') {
3142
+ if (!latest || latest.state === 'pr_ready' || latest.state === 'finished') {
2877
3143
  return latest || run;
2878
3144
  }
3145
+ if (latest.state === 'failed') {
3146
+ if (reason && latest.failure_reason !== reason) {
3147
+ this.runRepo.update(runId, { failure_reason: reason });
3148
+ this.eventBus.publish(runId, latest.ticket_id, 'run.state_changed', {
3149
+ run_id: runId,
3150
+ ticket_id: latest.ticket_id,
3151
+ old_state: 'failed',
3152
+ new_state: 'failed',
3153
+ reason: reason,
3154
+ timestamp: Date.now(),
3155
+ });
3156
+ return this.runRepo.get(runId)!;
3157
+ }
3158
+ return latest;
3159
+ }
2879
3160
 
2880
3161
  const oldState = latest.state;
2881
3162
  const updates: Partial<Run> = {
@@ -2907,6 +3188,9 @@ fi
2907
3188
  return this.runRepo.get(runId)!;
2908
3189
  } finally {
2909
3190
  this.inFlightTerminations.delete(runId);
3191
+ if (!this.startingRuns.has(runId)) {
3192
+ this.cancellationRequested.delete(runId);
3193
+ }
2910
3194
  }
2911
3195
  }
2912
3196
 
@@ -2938,7 +3222,7 @@ fi
2938
3222
  async transitionRun(runId: string, newState: RunState, reason?: string | null): Promise<Run> {
2939
3223
  const run = this.runRepo.get(runId);
2940
3224
  if (!run) {
2941
- throw new Error(`Run '${runId}' not found`);
3225
+ throw new NotFoundError(`Run '${runId}' not found`);
2942
3226
  }
2943
3227
 
2944
3228
  if (newState === 'failed' || newState === 'pr_ready') {
@@ -2949,7 +3233,7 @@ fi
2949
3233
 
2950
3234
  const oldState = run.state;
2951
3235
  const updates: Partial<Run> = {
2952
- failure_reason: reason || undefined,
3236
+ failure_reason: reason !== undefined ? (reason || null) : (oldState === 'blocked' && newState !== 'blocked' ? null : undefined),
2953
3237
  };
2954
3238
  if (newState === 'running' && !run.started_at) {
2955
3239
  updates.started_at = new Date().toISOString();