@jmanuelcorral/bond-app 0.1.3 → 0.1.5
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.
- package/README.md +41 -1
- package/app/mods/bond-agents/config.js +4 -0
- package/app/mods/bond-agents/main.js +10 -5
- package/app/mods/bond-agents/model.js +52 -4
- package/app/mods/bond-board/config.js +4 -0
- package/app/mods/bond-board/main.js +555 -84
- package/app/mods/bond-board/model.js +115 -2
- package/app/mods/bond-settings/config.js +4 -0
- package/app/mods/bond-settings/main.js +689 -12
- package/app/mods/bond-settings/pi-models.js +144 -0
- package/app/mods/bond-status/config.js +4 -0
- package/app/mods/bond-titlebar/main.js +63 -46
- package/package.json +1 -1
- package/runner/Dockerfile +42 -13
- package/runner/SPIKE-BOND.md +85 -0
- package/runner/build-config/.none +0 -0
- package/runner/build-creds/.none +0 -0
- package/runner/config.example/README.md +27 -0
- package/runner/config.example/pi/models.json +22 -0
- package/runner/credentials.example.env +27 -0
- package/runner/setup.sh +496 -0
- package/runner/versions.env +30 -0
- package/scripts/app-install.ts +38 -7
- package/src/config.ts +11 -0
- package/src/core/delivery.ts +61 -7
- package/src/core/hub-session.ts +154 -17
- package/src/core/hub.ts +55 -20
- package/src/core/orchestrator.ts +844 -200
- package/src/core/setup.ts +178 -0
- package/src/core/watchdog.ts +2 -2
- package/src/db/database.ts +14 -0
- package/src/db/run-repo.ts +8 -1
- package/src/db/settings-repo.ts +108 -0
- package/src/db/ticket-repo.ts +34 -4
- package/src/runner/docker-client.ts +42 -0
- package/src/runner/github-client.ts +126 -2
- package/src/runner/hc-client.ts +67 -9
- package/src/runner/image-builder.ts +146 -6
- package/src/server/app.ts +263 -36
- package/src/types.ts +40 -0
package/src/core/orchestrator.ts
CHANGED
|
@@ -9,24 +9,27 @@ import { EventBus } from '../sse/event-bus.ts';
|
|
|
9
9
|
import { DockerClient, type DockerContainerSummary } from '../runner/docker-client.ts';
|
|
10
10
|
import { Watchdog } from './watchdog.ts';
|
|
11
11
|
import { CostTracker } from './cost-tracker.ts';
|
|
12
|
-
import { HcClient, HcError, machineNameForRun, type HcMachineInfo } from '../runner/hc-client.ts';
|
|
12
|
+
import { HcClient, HcError, machineNameForRun, type HcMachineInfo, type HcTerminalDetails } from '../runner/hc-client.ts';
|
|
13
13
|
import { validateTransition, InvalidStateTransitionError } from './state-machine.ts';
|
|
14
|
-
import { rebuildRunnerImage as rebuildRunnerImageImpl, type RunnerVersions } from '../runner/image-builder.ts';
|
|
14
|
+
import { rebuildRunnerImage as rebuildRunnerImageImpl, type RunnerBuildOptions, type RunnerVersions } from '../runner/image-builder.ts';
|
|
15
15
|
import { GitHubClient, parseGitHubRepo } from '../runner/github-client.ts';
|
|
16
16
|
import {
|
|
17
17
|
assertHubPushTarget,
|
|
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 {
|
|
31
|
+
import { buildSetupState } from './setup.ts';
|
|
32
|
+
import { HUB_DIR, NAME_RE, agentGaps, analysisPrompt, buildAnalysis, fixedGaps, parseAgentAnswer, repoNameFromUrl, teamAgentFor, teamAgents, type HubToml } from './hub.ts';
|
|
30
33
|
import {
|
|
31
34
|
validateGitHubUrl,
|
|
32
35
|
validateGitHubIssueUrl,
|
|
@@ -40,9 +43,39 @@ import {
|
|
|
40
43
|
type RunState,
|
|
41
44
|
type FailureReason,
|
|
42
45
|
type TeamStatusRow,
|
|
46
|
+
type RunnerImageInfo,
|
|
47
|
+
type SetupState,
|
|
43
48
|
} from '../types.ts';
|
|
44
49
|
import type { AppConfig } from '../config.ts';
|
|
45
50
|
|
|
51
|
+
export class NotFoundError extends Error {
|
|
52
|
+
constructor(message: string) {
|
|
53
|
+
super(message);
|
|
54
|
+
this.name = 'NotFoundError';
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export class ConflictError extends Error {
|
|
59
|
+
constructor(message: string) {
|
|
60
|
+
super(message);
|
|
61
|
+
this.name = 'ConflictError';
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export class JsonParseError extends Error {
|
|
66
|
+
constructor(message: string) {
|
|
67
|
+
super(message);
|
|
68
|
+
this.name = 'JsonParseError';
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export class PayloadTooLargeError extends Error {
|
|
73
|
+
constructor(message: string) {
|
|
74
|
+
super(message);
|
|
75
|
+
this.name = 'PayloadTooLargeError';
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
46
79
|
export class UnmergedBranchError extends Error {
|
|
47
80
|
public readonly repo: string;
|
|
48
81
|
public readonly branch: string;
|
|
@@ -117,11 +150,25 @@ export class Orchestrator {
|
|
|
117
150
|
private inFlightTerminations = new Set<string>();
|
|
118
151
|
private startingRuns = new Set<string>();
|
|
119
152
|
private isReconciling = false;
|
|
153
|
+
// L2: Cancellation requested while run is starting
|
|
154
|
+
private cancellationRequested = new Set<string>();
|
|
155
|
+
|
|
156
|
+
get startingRunsCount(): number {
|
|
157
|
+
return this.startingRuns.size;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
get inFlightTerminationsCount(): number {
|
|
161
|
+
return this.inFlightTerminations.size;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
get isReconcilingInProgress(): boolean {
|
|
165
|
+
return this.isReconciling;
|
|
166
|
+
}
|
|
120
167
|
// N-1 (P1 debt): strikes per run for consecutive periodic sweeps with the container not Up.
|
|
121
168
|
private missingContainerStrikes = new Map<string, number>();
|
|
122
169
|
// P2 criterion 7: guard against concurrent image rebuilds.
|
|
123
170
|
private rebuildInFlight = false;
|
|
124
|
-
private rebuildImpl: (image: string,
|
|
171
|
+
private rebuildImpl: (image: string, options?: RunnerBuildOptions) => Promise<void>;
|
|
125
172
|
// P4: deliveries in progress (verify, commit, push, PR), one per run.
|
|
126
173
|
private deliveries = new Map<string, Promise<Run>>();
|
|
127
174
|
// P4: a token given explicitly at start (not stored); delivery falls back to the stored one.
|
|
@@ -146,7 +193,7 @@ export class Orchestrator {
|
|
|
146
193
|
dockerClient: DockerClient,
|
|
147
194
|
config: AppConfig,
|
|
148
195
|
// P2 criterion 7: injectable for tests; the real docker build is never run in unit/UI tests.
|
|
149
|
-
rebuildImpl: (image: string,
|
|
196
|
+
rebuildImpl: (image: string, options?: RunnerBuildOptions) => Promise<void> = rebuildRunnerImageImpl,
|
|
150
197
|
hcClient: HcClient = new HcClient(),
|
|
151
198
|
github: GitHubClient = new GitHubClient()
|
|
152
199
|
) {
|
|
@@ -196,7 +243,7 @@ export class Orchestrator {
|
|
|
196
243
|
*/
|
|
197
244
|
getAgentConfigPath(agent: string): string {
|
|
198
245
|
if (!isValidAgent(agent)) {
|
|
199
|
-
throw new
|
|
246
|
+
throw new ValidationError(`Unsupported agent '${agent}' (N8)`);
|
|
200
247
|
}
|
|
201
248
|
switch (agent) {
|
|
202
249
|
case 'pi':
|
|
@@ -222,7 +269,8 @@ export class Orchestrator {
|
|
|
222
269
|
*/
|
|
223
270
|
async injectCredentials(containerName: string, agents: string[], home = '/home/runner'): Promise<string[]> {
|
|
224
271
|
const written: string[] = [];
|
|
225
|
-
|
|
272
|
+
const wanted = new Set(agents);
|
|
273
|
+
for (const agent of wanted) {
|
|
226
274
|
const credential = this.settingsRepo.getCredential(agent);
|
|
227
275
|
if (!credential) continue;
|
|
228
276
|
const destPath = home + this.getAgentConfigPath(agent).slice('/home/runner'.length);
|
|
@@ -237,6 +285,26 @@ export class Orchestrator {
|
|
|
237
285
|
}
|
|
238
286
|
written.push(destPath);
|
|
239
287
|
}
|
|
288
|
+
// W-P4: prompt-suggestions config for supi, written next to pi's models.json when a
|
|
289
|
+
// suggestions model is stored (null = «sin sugerencias» writes nothing). The supi
|
|
290
|
+
// package itself comes with the runner image (image plan P2); until then the file is
|
|
291
|
+
// simply inert, so this never depends on the image's contents.
|
|
292
|
+
if (wanted.has('pi')) {
|
|
293
|
+
const model = this.settingsRepo.getSetupSelection().suggestions_model;
|
|
294
|
+
if (model) {
|
|
295
|
+
const destPath = `${home}/.pi/agent/supi/config.json`;
|
|
296
|
+
const res = await this.dockerClient.injectStdin(
|
|
297
|
+
containerName,
|
|
298
|
+
['sh', '-c', 'umask 077; mkdir -p "$(dirname "$1")" && cat > "$1"', '--', destPath],
|
|
299
|
+
JSON.stringify({ promptSuggestions: { model } }, null, 2),
|
|
300
|
+
'runner'
|
|
301
|
+
);
|
|
302
|
+
if (res.exitCode !== 0) {
|
|
303
|
+
throw new Error(`Supi suggestions config failed with code ${res.exitCode}: ${res.stderr}`);
|
|
304
|
+
}
|
|
305
|
+
written.push(destPath);
|
|
306
|
+
}
|
|
307
|
+
}
|
|
240
308
|
return written;
|
|
241
309
|
}
|
|
242
310
|
|
|
@@ -457,6 +525,15 @@ export class Orchestrator {
|
|
|
457
525
|
continue;
|
|
458
526
|
}
|
|
459
527
|
try {
|
|
528
|
+
// Criterion 4: sweep networks with grace period, matching orphan container policy
|
|
529
|
+
const insp = await this.dockerClient.inspectNetwork(n.name);
|
|
530
|
+
if (!insp) continue;
|
|
531
|
+
if (typeof insp.Created === 'string') {
|
|
532
|
+
const createdTime = new Date(insp.Created).getTime();
|
|
533
|
+
if (Date.now() - createdTime <= gracePeriodMs) {
|
|
534
|
+
continue;
|
|
535
|
+
}
|
|
536
|
+
}
|
|
460
537
|
await this.dockerClient.removeNetwork(n.name);
|
|
461
538
|
orphanedNetworksRemoved.push(n.name);
|
|
462
539
|
} catch {
|
|
@@ -675,7 +752,7 @@ export class Orchestrator {
|
|
|
675
752
|
validateTransition(from, to);
|
|
676
753
|
const { updated, run } = this.runRepo.updateStateConditionally(runId, from, to, {
|
|
677
754
|
...extra,
|
|
678
|
-
failure_reason: reason !== undefined ? reason : undefined,
|
|
755
|
+
failure_reason: reason !== undefined ? reason : (from === 'blocked' && to !== 'blocked' ? null : undefined),
|
|
679
756
|
});
|
|
680
757
|
if (!updated || !run) return false;
|
|
681
758
|
this.ticketRepo.updateStatus(run.ticket_id, to);
|
|
@@ -933,7 +1010,7 @@ export class Orchestrator {
|
|
|
933
1010
|
const existing = this.deliveries.get(runId);
|
|
934
1011
|
if (existing) return existing;
|
|
935
1012
|
const run = this.runRepo.get(runId);
|
|
936
|
-
if (!run) throw new
|
|
1013
|
+
if (!run) throw new NotFoundError(`Run '${runId}' not found`);
|
|
937
1014
|
if (run.state !== 'running' && run.state !== 'verifying' && run.state !== 'finished') {
|
|
938
1015
|
throw new InvalidStateTransitionError(run.state, 'verifying');
|
|
939
1016
|
}
|
|
@@ -945,6 +1022,41 @@ export class Orchestrator {
|
|
|
945
1022
|
return p;
|
|
946
1023
|
}
|
|
947
1024
|
|
|
1025
|
+
/**
|
|
1026
|
+
* D2: Retry a delivery step (push, PR) up to 3 times with growing backoff.
|
|
1027
|
+
* If exhausted, throws the last error so delivery blocks with the failure reason.
|
|
1028
|
+
*/
|
|
1029
|
+
private async retryDeliveryStep<T>(
|
|
1030
|
+
stepName: string,
|
|
1031
|
+
run: Run,
|
|
1032
|
+
fn: (attempt: number) => Promise<T>,
|
|
1033
|
+
delays: number[] = this.config.deliveryRetryDelaysMs ?? [1000, 2000],
|
|
1034
|
+
shouldRetry: (err: unknown) => boolean = () => true
|
|
1035
|
+
): Promise<T> {
|
|
1036
|
+
let attempt = 1;
|
|
1037
|
+
const maxAttempts = delays.length + 1;
|
|
1038
|
+
while (true) {
|
|
1039
|
+
try {
|
|
1040
|
+
return await fn(attempt);
|
|
1041
|
+
} catch (err) {
|
|
1042
|
+
if (attempt >= maxAttempts || !shouldRetry(err)) {
|
|
1043
|
+
throw err;
|
|
1044
|
+
}
|
|
1045
|
+
const delayMs = delays[attempt - 1] ?? 1000;
|
|
1046
|
+
this.agentEvent(run, `delivery.${stepName}_retry`, {
|
|
1047
|
+
attempt,
|
|
1048
|
+
maxAttempts,
|
|
1049
|
+
delayMs,
|
|
1050
|
+
error: String((err as Error).message || err).slice(0, 200),
|
|
1051
|
+
});
|
|
1052
|
+
if (delayMs > 0) {
|
|
1053
|
+
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
1054
|
+
}
|
|
1055
|
+
attempt++;
|
|
1056
|
+
}
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
|
|
948
1060
|
private async runDelivery(runId: string): Promise<Run> {
|
|
949
1061
|
const run = this.runRepo.get(runId)!;
|
|
950
1062
|
const ticket = this.ticketRepo.get(run.ticket_id);
|
|
@@ -958,6 +1070,25 @@ export class Orchestrator {
|
|
|
958
1070
|
const ctr = run.container_name;
|
|
959
1071
|
try {
|
|
960
1072
|
// 1. Verification (criterion 3): every command must pass, as runner, in the clone.
|
|
1073
|
+
// MEDIUM-2: capture working tree before running verification commands
|
|
1074
|
+
let expectedTree = '';
|
|
1075
|
+
if (ticket.verify_commands.length > 0) {
|
|
1076
|
+
const treeRes = await this.dockerClient.exec(
|
|
1077
|
+
ctr,
|
|
1078
|
+
['sh', '-c', TREE_SCRIPT, 'runner-tree', '/workspace/repo'],
|
|
1079
|
+
'runner',
|
|
1080
|
+
30_000
|
|
1081
|
+
);
|
|
1082
|
+
if (treeRes.exitCode === 0) {
|
|
1083
|
+
expectedTree = /tree=([0-9a-f]{40})\b/.exec(treeRes.stdout)?.[1] || '';
|
|
1084
|
+
}
|
|
1085
|
+
// M-1: Fail closed if tree capture fails with non-empty verify_commands
|
|
1086
|
+
if (!expectedTree) {
|
|
1087
|
+
this.setState(runId, 'verifying', 'blocked', `delivery_failed: working tree capture failed before verification (exit ${treeRes.exitCode}): ${treeRes.stderr || treeRes.stdout}`);
|
|
1088
|
+
return current();
|
|
1089
|
+
}
|
|
1090
|
+
}
|
|
1091
|
+
|
|
961
1092
|
const verification: string[] = [];
|
|
962
1093
|
for (const cmd of ticket.verify_commands) {
|
|
963
1094
|
let res: { stdout: string; stderr: string; exitCode: number };
|
|
@@ -977,6 +1108,25 @@ export class Orchestrator {
|
|
|
977
1108
|
if (res.exitCode !== 0) {
|
|
978
1109
|
return await this.verificationFailed(runId, ticket, cmd, res);
|
|
979
1110
|
}
|
|
1111
|
+
// M-3: Verify intermediate tree after each verification command to close flip-flops
|
|
1112
|
+
if (expectedTree) {
|
|
1113
|
+
const intermediateTreeRes = await this.dockerClient.exec(
|
|
1114
|
+
ctr,
|
|
1115
|
+
['sh', '-c', TREE_SCRIPT, 'runner-tree', '/workspace/repo'],
|
|
1116
|
+
'runner',
|
|
1117
|
+
30_000
|
|
1118
|
+
);
|
|
1119
|
+
const intermediateTree = intermediateTreeRes.exitCode === 0
|
|
1120
|
+
? /tree=([0-9a-f]{40})\b/.exec(intermediateTreeRes.stdout)?.[1] || ''
|
|
1121
|
+
: '';
|
|
1122
|
+
if (intermediateTree !== expectedTree) {
|
|
1123
|
+
return await this.verificationFailed(runId, ticket, `intermediate working tree check after '${cmd}'`, {
|
|
1124
|
+
stdout: intermediateTreeRes.stdout,
|
|
1125
|
+
stderr: `working tree changed during verification (${intermediateTree || 'capture failed'} != ${expectedTree})`,
|
|
1126
|
+
exitCode: COMMIT_EXIT.treeChanged,
|
|
1127
|
+
});
|
|
1128
|
+
}
|
|
1129
|
+
}
|
|
980
1130
|
verification.push(`\`${cmd}\`: OK`);
|
|
981
1131
|
}
|
|
982
1132
|
this.agentEvent(run, 'verification.passed', { commands: ticket.verify_commands.length });
|
|
@@ -991,6 +1141,9 @@ export class Orchestrator {
|
|
|
991
1141
|
`${ticket.title}\n\nbond-app run ${runId} (ticket ${ticket.id})`,
|
|
992
1142
|
login || 'bond-app',
|
|
993
1143
|
login ? `${login}@users.noreply.github.com` : 'bond-app@localhost',
|
|
1144
|
+
'/workspace/repo',
|
|
1145
|
+
BUNDLE_PATH,
|
|
1146
|
+
expectedTree,
|
|
994
1147
|
],
|
|
995
1148
|
'runner',
|
|
996
1149
|
120_000
|
|
@@ -1006,23 +1159,66 @@ export class Orchestrator {
|
|
|
1006
1159
|
// 3. Push only the ticket's branch to the ticket's repo (criterion 2). Root decides
|
|
1007
1160
|
// on the exact object pushed: it is the committed head, adds commits to the real base
|
|
1008
1161
|
// from GitHub and changes nothing under .github/workflows (review HIGH-1).
|
|
1162
|
+
// D2: push retries up to 3 times with growing backoff; exhausted -> blocked.
|
|
1009
1163
|
const token = this.runTokens.get(runId) || this.settingsRepo.getGitHubToken();
|
|
1010
1164
|
if (!token) throw new GitHubCredentialMissingError();
|
|
1011
|
-
const
|
|
1165
|
+
const shouldRetryPush = (err: unknown) => {
|
|
1166
|
+
const msg = String((err as Error).message || err);
|
|
1167
|
+
return !msg.includes('nothing to deliver') && !msg.includes('.github/workflows') && !msg.includes('does not match the committed head');
|
|
1168
|
+
};
|
|
1169
|
+
const pushed = await this.retryDeliveryStep(
|
|
1170
|
+
'push',
|
|
1171
|
+
run,
|
|
1172
|
+
() => this.pushRunBranch(runId, ticket.repo_url, ticket.target_branch, headSha, token),
|
|
1173
|
+
this.config.deliveryRetryDelaysMs,
|
|
1174
|
+
shouldRetryPush
|
|
1175
|
+
);
|
|
1012
1176
|
if (pushed === 'nothing_to_deliver') {
|
|
1013
1177
|
this.agentEvent(run, 'delivery.no_changes', { branch: ticket.target_branch });
|
|
1014
1178
|
return await this.terminateRun(runId, 'failed', 'no_changes');
|
|
1015
1179
|
}
|
|
1180
|
+
// LOW-4: record pushed branch immediately so a cancel between push and PR leaves branch linked
|
|
1181
|
+
this.runRepo.update(runId, {
|
|
1182
|
+
repo_states: {
|
|
1183
|
+
[ticket.repo_url]: {
|
|
1184
|
+
url: ticket.repo_url,
|
|
1185
|
+
base: ticket.base_branch,
|
|
1186
|
+
branch: ticket.target_branch,
|
|
1187
|
+
status: 'pushed',
|
|
1188
|
+
sha: headSha,
|
|
1189
|
+
},
|
|
1190
|
+
},
|
|
1191
|
+
});
|
|
1016
1192
|
if (!stillVerifying()) return current();
|
|
1017
1193
|
|
|
1018
|
-
// 4. The pull request, with the ticket summary (criterion 1).
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1194
|
+
// 4. The pull request, with the ticket summary (criterion 1 & D2).
|
|
1195
|
+
// D2: PR retries up to 3 times with growing backoff; an existing PR is linked.
|
|
1196
|
+
const pr = await this.retryDeliveryStep(
|
|
1197
|
+
'pr',
|
|
1198
|
+
run,
|
|
1199
|
+
() => this.github.openPullRequest(token, ticket.repo_url, {
|
|
1200
|
+
head: ticket.target_branch,
|
|
1201
|
+
base: ticket.base_branch,
|
|
1202
|
+
title: ticket.title,
|
|
1203
|
+
body: pullRequestBody(ticket, run, verification),
|
|
1204
|
+
}),
|
|
1205
|
+
this.config.deliveryRetryDelaysMs
|
|
1206
|
+
);
|
|
1207
|
+
this.runRepo.update(runId, {
|
|
1208
|
+
pr_url: pr.url,
|
|
1209
|
+
pr_number: pr.number,
|
|
1210
|
+
repo_states: {
|
|
1211
|
+
[ticket.repo_url]: {
|
|
1212
|
+
url: ticket.repo_url,
|
|
1213
|
+
base: ticket.base_branch,
|
|
1214
|
+
branch: ticket.target_branch,
|
|
1215
|
+
status: 'pr_opened',
|
|
1216
|
+
sha: headSha,
|
|
1217
|
+
pr_url: pr.url,
|
|
1218
|
+
pr_number: pr.number,
|
|
1219
|
+
},
|
|
1220
|
+
},
|
|
1024
1221
|
});
|
|
1025
|
-
this.runRepo.update(runId, { pr_url: pr.url, pr_number: pr.number });
|
|
1026
1222
|
if (!stillVerifying()) {
|
|
1027
1223
|
// Cancelled while the PR was being opened: keep its link, but the run is over.
|
|
1028
1224
|
this.agentEvent(run, 'delivery.pr_after_cancel', { pr_url: pr.url });
|
|
@@ -1113,7 +1309,7 @@ export class Orchestrator {
|
|
|
1113
1309
|
const n = Number(/\/t(\d+)$/.exec(run.hc_terminal || '')?.[1] || '1') + 1;
|
|
1114
1310
|
const terminal = await this.hcClient.startTerminal(
|
|
1115
1311
|
run.hc_machine,
|
|
1116
|
-
this.
|
|
1312
|
+
await this.resolveAgentCommand(run.container_name, ticket, message),
|
|
1117
1313
|
'/workspace/repo',
|
|
1118
1314
|
`agent-${n}`
|
|
1119
1315
|
);
|
|
@@ -1128,7 +1324,7 @@ export class Orchestrator {
|
|
|
1128
1324
|
*/
|
|
1129
1325
|
async nudgeRun(runId: string, message: string): Promise<Run> {
|
|
1130
1326
|
const run = this.runRepo.get(runId);
|
|
1131
|
-
if (!run) throw new
|
|
1327
|
+
if (!run) throw new NotFoundError(`Run '${runId}' not found`);
|
|
1132
1328
|
const text = typeof message === 'string' ? message.trim() : '';
|
|
1133
1329
|
if (!text || text.length > 4000) throw new ValidationError("'message' must be 1 to 4000 characters");
|
|
1134
1330
|
if (this.deliveries.has(runId)) {
|
|
@@ -1138,7 +1334,7 @@ export class Orchestrator {
|
|
|
1138
1334
|
throw new ValidationError(`Only a blocked or running run can be nudged (this one is '${run.state}')`);
|
|
1139
1335
|
}
|
|
1140
1336
|
const ticket = this.ticketRepo.get(run.ticket_id);
|
|
1141
|
-
if (!ticket) throw new
|
|
1337
|
+
if (!ticket) throw new NotFoundError(`Ticket '${run.ticket_id}' not found`);
|
|
1142
1338
|
if (ticket.mode === 'hub') return this.nudgeTeam(run, ticket, text);
|
|
1143
1339
|
const terminal = await this.notifyAgent(runId, ticket, text);
|
|
1144
1340
|
this.agentEvent(run, 'nudge', { terminal, message: text, from_state: run.state });
|
|
@@ -1173,103 +1369,220 @@ export class Orchestrator {
|
|
|
1173
1369
|
}
|
|
1174
1370
|
|
|
1175
1371
|
/**
|
|
1176
|
-
*
|
|
1372
|
+
* P2: Build the orchestrator / leader row for a run, used in getRunTeamStatus.
|
|
1373
|
+
* Guarantees that any run (hub or single, running or waiting or queued,
|
|
1374
|
+
* modern or legacy bare agent) returns an orchestrator row.
|
|
1375
|
+
*/
|
|
1376
|
+
private async buildOrchestratorRow(
|
|
1377
|
+
run: Run,
|
|
1378
|
+
ticket: Ticket | null,
|
|
1379
|
+
terminalInfo?: HcTerminalDetails | null
|
|
1380
|
+
): Promise<TeamStatusRow> {
|
|
1381
|
+
const isHub = ticket?.mode === 'hub';
|
|
1382
|
+
const agentKind = ticket?.agent || 'pi';
|
|
1383
|
+
|
|
1384
|
+
let t = terminalInfo ?? null;
|
|
1385
|
+
if (!t && run.hc_terminal) {
|
|
1386
|
+
try {
|
|
1387
|
+
t = await this.hcClient.getTerminal(run.hc_terminal);
|
|
1388
|
+
} catch {}
|
|
1389
|
+
}
|
|
1390
|
+
if (!t && run.hc_machine) {
|
|
1391
|
+
try {
|
|
1392
|
+
const terminals = await this.hcClient.getMachineTerminals(run.hc_machine);
|
|
1393
|
+
t =
|
|
1394
|
+
terminals.find(
|
|
1395
|
+
(x) =>
|
|
1396
|
+
x.name === 'hub leader' ||
|
|
1397
|
+
x.name === 'orquestador' ||
|
|
1398
|
+
x.address?.endsWith('/t1')
|
|
1399
|
+
) ||
|
|
1400
|
+
terminals[0] ||
|
|
1401
|
+
null;
|
|
1402
|
+
} catch {}
|
|
1403
|
+
}
|
|
1404
|
+
|
|
1405
|
+
const isGenericAgent = (name?: string) => !name || name === 'agent' || /^t\d+$/.test(name);
|
|
1406
|
+
|
|
1407
|
+
let listedAgent: string | undefined;
|
|
1408
|
+
if (isGenericAgent(t?.agent) && (run.hc_machine || run.hc_terminal || t?.address)) {
|
|
1409
|
+
try {
|
|
1410
|
+
const listed = await this.hcClient.listTerminals(run.hc_machine || undefined);
|
|
1411
|
+
const match = listed.find(
|
|
1412
|
+
(x) => x.address === (t?.address || run.hc_terminal) || x.address?.endsWith('/t1')
|
|
1413
|
+
);
|
|
1414
|
+
if (match?.agent && !isGenericAgent(match.agent)) {
|
|
1415
|
+
listedAgent = match.agent;
|
|
1416
|
+
}
|
|
1417
|
+
} catch {}
|
|
1418
|
+
}
|
|
1419
|
+
|
|
1420
|
+
if (t && listedAgent && isGenericAgent(t.agent)) {
|
|
1421
|
+
t.agent = listedAgent;
|
|
1422
|
+
}
|
|
1423
|
+
|
|
1424
|
+
const detectedAgent =
|
|
1425
|
+
t?.agent && !isGenericAgent(t.agent)
|
|
1426
|
+
? t.agent
|
|
1427
|
+
: listedAgent && !isGenericAgent(listedAgent)
|
|
1428
|
+
? listedAgent
|
|
1429
|
+
: ticket?.agent || 'pi';
|
|
1430
|
+
const agentName = isHub ? 'hub leader' : detectedAgent;
|
|
1431
|
+
const pane =
|
|
1432
|
+
t?.address ||
|
|
1433
|
+
run.hc_terminal ||
|
|
1434
|
+
(run.hc_machine ? `${run.hc_machine}/t1` : undefined);
|
|
1435
|
+
|
|
1436
|
+
let state = 'trabajando';
|
|
1437
|
+
let status = 'working';
|
|
1438
|
+
let question: string | undefined = undefined;
|
|
1439
|
+
|
|
1440
|
+
if (run.state === 'queued' || run.state === 'ready') {
|
|
1441
|
+
state = 'arrancando';
|
|
1442
|
+
status = 'arrancando';
|
|
1443
|
+
} else if (run.state === 'waiting') {
|
|
1444
|
+
state = 'bloqueado';
|
|
1445
|
+
status = 'en espera';
|
|
1446
|
+
question = run.failure_reason || (agentName ? `Esperando respuesta: ${agentName}` : undefined);
|
|
1447
|
+
} else if (t) {
|
|
1448
|
+
const isWaiting =
|
|
1449
|
+
t.status === 'blocked' ||
|
|
1450
|
+
((t.status === 'idle' || t.status === 'done') && (t.turn ?? 0) > 0);
|
|
1451
|
+
|
|
1452
|
+
if (isWaiting) {
|
|
1453
|
+
state = 'bloqueado';
|
|
1454
|
+
status = 'en espera';
|
|
1455
|
+
question = run.failure_reason || (agentName ? `Esperando respuesta: ${agentName}` : undefined);
|
|
1456
|
+
} else if (t.status === 'working') {
|
|
1457
|
+
state = 'trabajando';
|
|
1458
|
+
status = 'working';
|
|
1459
|
+
} else if (t.status === 'idle') {
|
|
1460
|
+
state = 'idle';
|
|
1461
|
+
status = 'idle';
|
|
1462
|
+
} else if (t.status === 'live') {
|
|
1463
|
+
state = 'live';
|
|
1464
|
+
status = 'live';
|
|
1465
|
+
} else if (t.status) {
|
|
1466
|
+
state = t.status;
|
|
1467
|
+
status = t.status;
|
|
1468
|
+
} else if (t.state === 'live') {
|
|
1469
|
+
// Live terminal without agent status hook (e.g. p6 with bond tui, or bare pi)
|
|
1470
|
+
state = 'live';
|
|
1471
|
+
status = 'live';
|
|
1472
|
+
} else {
|
|
1473
|
+
state = 'sin estado';
|
|
1474
|
+
status = 'sin estado';
|
|
1475
|
+
}
|
|
1476
|
+
} else {
|
|
1477
|
+
if (run.state === 'running') {
|
|
1478
|
+
state = 'arrancando';
|
|
1479
|
+
status = 'arrancando';
|
|
1480
|
+
} else if (run.state === 'finished') {
|
|
1481
|
+
state = 'lista';
|
|
1482
|
+
status = 'finished';
|
|
1483
|
+
} else if (run.state === 'failed') {
|
|
1484
|
+
state = 'bloqueado';
|
|
1485
|
+
status = 'failed';
|
|
1486
|
+
} else {
|
|
1487
|
+
state = 'sin estado';
|
|
1488
|
+
status = 'sin estado';
|
|
1489
|
+
}
|
|
1490
|
+
}
|
|
1491
|
+
|
|
1492
|
+
return {
|
|
1493
|
+
branch: ticket?.target_branch || '',
|
|
1494
|
+
path: isHub ? '/workspace/hub' : '/workspace/repo',
|
|
1495
|
+
repo: 'orquestador',
|
|
1496
|
+
state,
|
|
1497
|
+
ahead: 0,
|
|
1498
|
+
files: [],
|
|
1499
|
+
dirty: 0,
|
|
1500
|
+
integrated: false,
|
|
1501
|
+
agent: {
|
|
1502
|
+
name: agentName,
|
|
1503
|
+
kind: agentKind,
|
|
1504
|
+
status,
|
|
1505
|
+
question,
|
|
1506
|
+
pane,
|
|
1507
|
+
terminal: pane,
|
|
1508
|
+
},
|
|
1509
|
+
};
|
|
1510
|
+
}
|
|
1511
|
+
|
|
1512
|
+
/**
|
|
1513
|
+
* P7 (criterion 8 & Ampliación) & P2: get the team status for a run.
|
|
1177
1514
|
* For hub runs, includes the hub orchestrator agent (pi in hub root) at the top,
|
|
1178
1515
|
* labelled as «hub leader» (orquestador), merged with repo agents from `bond team status --json`.
|
|
1516
|
+
* For single runs, returns the orchestrator agent row.
|
|
1179
1517
|
*/
|
|
1180
1518
|
async getRunTeamStatus(runId: string): Promise<TeamStatusRow[]> {
|
|
1181
1519
|
const run = this.runRepo.get(runId);
|
|
1182
1520
|
if (!run) throw new ValidationError(`Run '${runId}' not found`);
|
|
1183
|
-
if (!run.container_name) return [];
|
|
1184
1521
|
|
|
1185
1522
|
const ticket = this.ticketRepo.get(run.ticket_id);
|
|
1186
1523
|
const isHub = ticket?.mode === 'hub';
|
|
1187
1524
|
|
|
1525
|
+
if (!run.container_name) {
|
|
1526
|
+
return [await this.buildOrchestratorRow(run, ticket)];
|
|
1527
|
+
}
|
|
1528
|
+
|
|
1188
1529
|
// P9: HC engine - get status directly from hc, NO docker exec
|
|
1189
|
-
if (
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1530
|
+
if (ticket?.team_engine !== 'herdr') {
|
|
1531
|
+
if (isHub) {
|
|
1532
|
+
try {
|
|
1533
|
+
const machine = run.hc_machine || machineNameForRun(run.id);
|
|
1534
|
+
const terminals = await this.hcClient.getMachineTerminals(machine);
|
|
1193
1535
|
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1536
|
+
const isLeader = (t: { name?: string; cwd?: string; address?: string }) => {
|
|
1537
|
+
if (t.name === 'hub leader' || t.name === 'hub-leader' || t.name === 'leader' || t.name === 'orquestador') {
|
|
1538
|
+
return true;
|
|
1539
|
+
}
|
|
1540
|
+
const cleanCwd = t.cwd?.replace(/\/+$/, '');
|
|
1541
|
+
if (cleanCwd === '/workspace/hub') return true;
|
|
1542
|
+
if (t.address?.endsWith('/t1')) return true;
|
|
1543
|
+
return false;
|
|
1544
|
+
};
|
|
1203
1545
|
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
let leaderStatus = 'working';
|
|
1209
|
-
if (leader.status === 'blocked') {
|
|
1210
|
-
leaderState = 'bloqueado';
|
|
1211
|
-
leaderStatus = 'blocked';
|
|
1212
|
-
} else if ((leader.status === 'idle' || leader.status === 'done') && (leader.turn ?? 0) > 0) {
|
|
1213
|
-
leaderState = 'bloqueado';
|
|
1214
|
-
leaderStatus = 'idle-waiting';
|
|
1215
|
-
} else if (leader.status === 'working') {
|
|
1216
|
-
leaderState = 'trabajando';
|
|
1217
|
-
leaderStatus = 'working';
|
|
1218
|
-
} else {
|
|
1219
|
-
leaderState = 'trabajando';
|
|
1220
|
-
leaderStatus = leader.status || 'working';
|
|
1546
|
+
const rows: TeamStatusRow[] = [];
|
|
1547
|
+
const leader = terminals.find(isLeader);
|
|
1548
|
+
if (leader) {
|
|
1549
|
+
rows.push(await this.buildOrchestratorRow(run, ticket, leader));
|
|
1221
1550
|
}
|
|
1222
1551
|
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
else if (t.status === 'working') state = 'trabajando';
|
|
1251
|
-
return {
|
|
1252
|
-
branch,
|
|
1253
|
-
path: t.cwd || '',
|
|
1254
|
-
repo: repoName,
|
|
1255
|
-
state,
|
|
1256
|
-
ahead: 0,
|
|
1257
|
-
files: [],
|
|
1258
|
-
dirty: 0,
|
|
1259
|
-
integrated: false,
|
|
1260
|
-
agent: {
|
|
1261
|
-
name: t.name || repoName,
|
|
1262
|
-
kind: t.agent || ticket?.agent || 'pi',
|
|
1263
|
-
status: t.status || 'unknown',
|
|
1264
|
-
pane: t.address,
|
|
1265
|
-
terminal: t.address,
|
|
1266
|
-
},
|
|
1267
|
-
};
|
|
1268
|
-
});
|
|
1552
|
+
const repoRows: TeamStatusRow[] = terminals
|
|
1553
|
+
.filter((t) => !isLeader(t))
|
|
1554
|
+
.map((t) => {
|
|
1555
|
+
const repoName = t.labels?.['bond.repo']?.replace(/^repos\//, '') || t.name || 'agente';
|
|
1556
|
+
const branch = t.labels?.['bond.branch'] || ticket?.target_branch || '';
|
|
1557
|
+
let state = 'trabajando';
|
|
1558
|
+
if (t.status === 'blocked') state = 'bloqueado';
|
|
1559
|
+
else if ((t.status === 'idle' || t.status === 'done') && (t.turn ?? 0) > 0) state = 'lista';
|
|
1560
|
+
else if (t.status === 'working') state = 'trabajando';
|
|
1561
|
+
return {
|
|
1562
|
+
branch,
|
|
1563
|
+
path: t.cwd || '',
|
|
1564
|
+
repo: repoName,
|
|
1565
|
+
state,
|
|
1566
|
+
ahead: 0,
|
|
1567
|
+
files: [],
|
|
1568
|
+
dirty: 0,
|
|
1569
|
+
integrated: false,
|
|
1570
|
+
agent: {
|
|
1571
|
+
name: t.name || repoName,
|
|
1572
|
+
kind: t.agent || ticket?.agent || 'pi',
|
|
1573
|
+
status: t.status || 'unknown',
|
|
1574
|
+
pane: t.address,
|
|
1575
|
+
terminal: t.address,
|
|
1576
|
+
},
|
|
1577
|
+
};
|
|
1578
|
+
});
|
|
1269
1579
|
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1580
|
+
return [...rows, ...repoRows];
|
|
1581
|
+
} catch {
|
|
1582
|
+
return [await this.buildOrchestratorRow(run, ticket)];
|
|
1583
|
+
}
|
|
1584
|
+
} else {
|
|
1585
|
+
return [await this.buildOrchestratorRow(run, ticket)];
|
|
1273
1586
|
}
|
|
1274
1587
|
}
|
|
1275
1588
|
|
|
@@ -1358,7 +1671,7 @@ export class Orchestrator {
|
|
|
1358
1671
|
leaderStatus = 'blocked';
|
|
1359
1672
|
} else if ((leaderAgent.agent_status === 'idle' || leaderAgent.agent_status === 'done') && seq > 0) {
|
|
1360
1673
|
leaderState = 'bloqueado';
|
|
1361
|
-
leaderStatus = '
|
|
1674
|
+
leaderStatus = 'en espera';
|
|
1362
1675
|
} else if (leaderAgent.agent_status === 'working') {
|
|
1363
1676
|
leaderState = 'trabajando';
|
|
1364
1677
|
leaderStatus = 'working';
|
|
@@ -1395,11 +1708,13 @@ export class Orchestrator {
|
|
|
1395
1708
|
r.agent?.name !== 'hub leader'
|
|
1396
1709
|
),
|
|
1397
1710
|
];
|
|
1711
|
+
} else if (rows.length === 0) {
|
|
1712
|
+
rows = [await this.buildOrchestratorRow(run, ticket)];
|
|
1398
1713
|
}
|
|
1399
1714
|
|
|
1400
1715
|
return rows;
|
|
1401
1716
|
} catch {
|
|
1402
|
-
return [];
|
|
1717
|
+
return [await this.buildOrchestratorRow(run, ticket)];
|
|
1403
1718
|
}
|
|
1404
1719
|
}
|
|
1405
1720
|
|
|
@@ -1415,9 +1730,9 @@ export class Orchestrator {
|
|
|
1415
1730
|
token?: string
|
|
1416
1731
|
): Promise<'pushed' | 'nothing_to_deliver'> {
|
|
1417
1732
|
const run = this.runRepo.get(runId);
|
|
1418
|
-
if (!run) throw new
|
|
1733
|
+
if (!run) throw new NotFoundError(`Run '${runId}' not found`);
|
|
1419
1734
|
const ticket = this.ticketRepo.get(run.ticket_id);
|
|
1420
|
-
if (!ticket) throw new
|
|
1735
|
+
if (!ticket) throw new NotFoundError(`Ticket '${run.ticket_id}' not found`);
|
|
1421
1736
|
assertPushTarget(ticket, repoUrl, branch);
|
|
1422
1737
|
if (!/^[0-9a-f]{40}$/.test(expectedSha)) throw new Error('Invalid expected head sha');
|
|
1423
1738
|
if (!run.container_name) throw new Error('The run has no container');
|
|
@@ -1505,11 +1820,30 @@ export class Orchestrator {
|
|
|
1505
1820
|
|
|
1506
1821
|
try {
|
|
1507
1822
|
// 1. Verification in each repo still to deliver (criterion 3 of P4, per repo).
|
|
1823
|
+
// MEDIUM-2: capture working tree before running verification commands
|
|
1824
|
+
const expectedTrees: Record<string, string> = {};
|
|
1508
1825
|
const verification: string[] = [];
|
|
1509
1826
|
const secs = Math.max(1, Math.floor(this.config.verifyTimeoutMs / 1000));
|
|
1510
1827
|
for (const t of targets.filter((x) => !x.hub && !done(x.key))) {
|
|
1511
1828
|
const wt = await session.worktreeOf(t.dir, branch);
|
|
1512
1829
|
if (!wt) continue;
|
|
1830
|
+
if (ticket.verify_commands.length > 0) {
|
|
1831
|
+
const treeRes = await this.dockerClient.exec(
|
|
1832
|
+
run.container_name,
|
|
1833
|
+
['sh', '-c', TREE_SCRIPT, 'runner-tree', wt],
|
|
1834
|
+
'runner',
|
|
1835
|
+
30_000
|
|
1836
|
+
);
|
|
1837
|
+
let tree = '';
|
|
1838
|
+
if (treeRes.exitCode === 0) {
|
|
1839
|
+
tree = /tree=([0-9a-f]{40})\b/.exec(treeRes.stdout)?.[1] || '';
|
|
1840
|
+
if (tree) expectedTrees[t.key] = tree;
|
|
1841
|
+
}
|
|
1842
|
+
// M-1: Fail closed if tree capture fails with non-empty verify_commands
|
|
1843
|
+
if (!tree) {
|
|
1844
|
+
return await this.verificationFailed(runId, ticket, `${t.key}: working tree capture failed before verification (exit ${treeRes.exitCode})`, treeRes);
|
|
1845
|
+
}
|
|
1846
|
+
}
|
|
1513
1847
|
for (const cmd of ticket.verify_commands) {
|
|
1514
1848
|
let res: { stdout: string; stderr: string; exitCode: number };
|
|
1515
1849
|
try {
|
|
@@ -1524,6 +1858,25 @@ export class Orchestrator {
|
|
|
1524
1858
|
}
|
|
1525
1859
|
if (!stillVerifying()) return current();
|
|
1526
1860
|
if (res.exitCode !== 0) return await this.verificationFailed(runId, ticket, `${t.key}: ${cmd}`, res);
|
|
1861
|
+
// M-3: Verify intermediate tree after each verification command to close flip-flops
|
|
1862
|
+
if (expectedTrees[t.key]) {
|
|
1863
|
+
const intermediateTreeRes = await this.dockerClient.exec(
|
|
1864
|
+
run.container_name,
|
|
1865
|
+
['sh', '-c', TREE_SCRIPT, 'runner-tree', wt],
|
|
1866
|
+
'runner',
|
|
1867
|
+
30_000
|
|
1868
|
+
);
|
|
1869
|
+
const intermediateTree = intermediateTreeRes.exitCode === 0
|
|
1870
|
+
? /tree=([0-9a-f]{40})\b/.exec(intermediateTreeRes.stdout)?.[1] || ''
|
|
1871
|
+
: '';
|
|
1872
|
+
if (intermediateTree !== expectedTrees[t.key]) {
|
|
1873
|
+
return await this.verificationFailed(runId, ticket, `${t.key}: intermediate working tree check after '${cmd}'`, {
|
|
1874
|
+
stdout: intermediateTreeRes.stdout,
|
|
1875
|
+
stderr: `working tree changed during verification (${intermediateTree || 'capture failed'} != ${expectedTrees[t.key]})`,
|
|
1876
|
+
exitCode: COMMIT_EXIT.treeChanged,
|
|
1877
|
+
});
|
|
1878
|
+
}
|
|
1879
|
+
}
|
|
1527
1880
|
verification.push(`${t.key}: \`${cmd}\`: OK`);
|
|
1528
1881
|
}
|
|
1529
1882
|
}
|
|
@@ -1555,7 +1908,7 @@ export class Orchestrator {
|
|
|
1555
1908
|
`${ticket.title}\n\nbond-app run ${runId} (ticket ${ticket.id})`,
|
|
1556
1909
|
login || 'bond-app',
|
|
1557
1910
|
login ? `${login}@users.noreply.github.com` : 'bond-app@localhost',
|
|
1558
|
-
wt, bundle,
|
|
1911
|
+
wt, bundle, expectedTrees[t.key] || '',
|
|
1559
1912
|
],
|
|
1560
1913
|
'runner',
|
|
1561
1914
|
120_000
|
|
@@ -1570,7 +1923,17 @@ export class Orchestrator {
|
|
|
1570
1923
|
sha = await session.bundleBranch(t.dir, branch, bundle);
|
|
1571
1924
|
}
|
|
1572
1925
|
if (!stillVerifying()) return current();
|
|
1573
|
-
const
|
|
1926
|
+
const shouldRetryPush = (err: unknown) => {
|
|
1927
|
+
const msg = String((err as Error).message || err);
|
|
1928
|
+
return !msg.includes('nothing to deliver') && !msg.includes('.github/workflows') && !msg.includes('does not match the committed head');
|
|
1929
|
+
};
|
|
1930
|
+
const pushed = await this.retryDeliveryStep(
|
|
1931
|
+
`push_${t.key}`,
|
|
1932
|
+
run,
|
|
1933
|
+
() => this.pushBundle(run, t.url, branch, bundle, sha, t.base, token),
|
|
1934
|
+
this.config.deliveryRetryDelaysMs,
|
|
1935
|
+
shouldRetryPush
|
|
1936
|
+
);
|
|
1574
1937
|
st.sha = sha;
|
|
1575
1938
|
if (pushed === 'nothing_to_deliver') {
|
|
1576
1939
|
st.status = 'no_changes';
|
|
@@ -1583,12 +1946,17 @@ export class Orchestrator {
|
|
|
1583
1946
|
}
|
|
1584
1947
|
if (!stillVerifying()) return current();
|
|
1585
1948
|
const others = targets.filter((o) => o !== t).map(nameOf);
|
|
1586
|
-
const pr = await this.
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1949
|
+
const pr = await this.retryDeliveryStep(
|
|
1950
|
+
`pr_${t.key}`,
|
|
1951
|
+
run,
|
|
1952
|
+
() => this.github.openPullRequest(token, t.url, {
|
|
1953
|
+
head: branch,
|
|
1954
|
+
base: t.base,
|
|
1955
|
+
title: ticket.title,
|
|
1956
|
+
body: pullRequestBody(ticket, run, verification, { base: t.base, others }),
|
|
1957
|
+
}),
|
|
1958
|
+
this.config.deliveryRetryDelaysMs
|
|
1959
|
+
);
|
|
1592
1960
|
st.status = 'pr_opened';
|
|
1593
1961
|
st.pr_url = pr.url;
|
|
1594
1962
|
st.pr_number = pr.number;
|
|
@@ -1666,7 +2034,7 @@ export class Orchestrator {
|
|
|
1666
2034
|
|
|
1667
2035
|
private hubSessionOf(run: Run): HubSession {
|
|
1668
2036
|
if (!run.container_name) throw new HubMountError('The run has no container');
|
|
1669
|
-
return new HubSession(this.dockerClient, run.container_name);
|
|
2037
|
+
return new HubSession(this.dockerClient, run.container_name, this.hcClient, run.hc_machine || machineNameForRun(run.id));
|
|
1670
2038
|
}
|
|
1671
2039
|
|
|
1672
2040
|
private tokenFor(runId: string): string {
|
|
@@ -1683,9 +2051,9 @@ export class Orchestrator {
|
|
|
1683
2051
|
*/
|
|
1684
2052
|
async analyzeHub(runId: string): Promise<HubAnalysis> {
|
|
1685
2053
|
const run = this.runRepo.get(runId);
|
|
1686
|
-
if (!run) throw new
|
|
2054
|
+
if (!run) throw new NotFoundError(`Run '${runId}' not found`);
|
|
1687
2055
|
const ticket = this.ticketRepo.get(run.ticket_id);
|
|
1688
|
-
if (!ticket) throw new
|
|
2056
|
+
if (!ticket) throw new NotFoundError(`Ticket '${run.ticket_id}' not found`);
|
|
1689
2057
|
const session = this.hubSessionOf(run);
|
|
1690
2058
|
const warnings: string[] = [];
|
|
1691
2059
|
|
|
@@ -1746,7 +2114,9 @@ export class Orchestrator {
|
|
|
1746
2114
|
let res: { stdout: string; stderr: string; exitCode: number };
|
|
1747
2115
|
try {
|
|
1748
2116
|
if (argv[0] === 'pi') await this.injectCredentials(run.container_name!, ['pi'], home);
|
|
1749
|
-
|
|
2117
|
+
const note = this.analysisNotes.get(runId);
|
|
2118
|
+
this.analysisNotes.delete(runId);
|
|
2119
|
+
res = await session.runAgent(argv, analysisPrompt(ticket, hub, note), this.config.analysisTimeoutMs, home);
|
|
1750
2120
|
} finally {
|
|
1751
2121
|
await session.removeDir(home);
|
|
1752
2122
|
}
|
|
@@ -1770,20 +2140,24 @@ export class Orchestrator {
|
|
|
1770
2140
|
warnings.push('Sin agente de hub: solo cuentan las comprobaciones fijas');
|
|
1771
2141
|
}
|
|
1772
2142
|
|
|
2143
|
+
if (!ticket.hub_url) {
|
|
2144
|
+
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');
|
|
2145
|
+
}
|
|
2146
|
+
|
|
1773
2147
|
return buildAnalysis({ hub, created: !ticket.hub_url, gaps, warnings, agentSummary });
|
|
1774
2148
|
}
|
|
1775
2149
|
|
|
1776
|
-
/** The hub agent's command: the override, or
|
|
2150
|
+
/** The hub agent's command: the override, or pi in print mode, read-only. */
|
|
1777
2151
|
private analysisArgv(ticket: Ticket): string[] | null {
|
|
1778
2152
|
const cmd = this.config.analysisCommand;
|
|
1779
2153
|
if (cmd === 'off') return null;
|
|
1780
2154
|
if (cmd) return [...cmd];
|
|
1781
|
-
|
|
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.
|
|
2155
|
+
// Hub agent runs read-only pi in print mode regardless of the ticket's agent (P3 criterion 5)
|
|
1784
2156
|
const argv = ['pi', '-p', '--no-session', '--no-approve', '--tools', 'read,grep,find,ls'];
|
|
1785
|
-
// Review L-4:
|
|
1786
|
-
|
|
2157
|
+
// Review L-4 / M-4: pass model only when ticket.agent is pi; default_model applies if ticket has no model (D-M1)
|
|
2158
|
+
const defaultModel = ticket.agent === 'pi' ? this.settingsRepo?.getSetupSelection?.()?.default_model : null;
|
|
2159
|
+
const model = ticket.agent === 'pi' ? (ticket.model || defaultModel) : null;
|
|
2160
|
+
if (model && /^[A-Za-z0-9_./:@-]{1,120}$/.test(model)) argv.push('--model', model);
|
|
1787
2161
|
return argv;
|
|
1788
2162
|
}
|
|
1789
2163
|
|
|
@@ -1830,11 +2204,12 @@ export class Orchestrator {
|
|
|
1830
2204
|
} catch {
|
|
1831
2205
|
live = false;
|
|
1832
2206
|
}
|
|
1833
|
-
reused = live && (await session.teamOpen(ticket.target_branch, analysis.repos.length, ticket.team_engine || 'hc'));
|
|
2207
|
+
reused = live && (await session.teamOpen(ticket.target_branch, analysis.repos.length, ticket.team_engine || 'hc', this.hcClient, run.hc_machine || machineNameForRun(run.id)));
|
|
1834
2208
|
}
|
|
1835
2209
|
if (!reused) {
|
|
1836
2210
|
const terminal = await session.launchTeam(this.hcClient, run.hc_machine!, ticket, analysis.repos, {
|
|
1837
2211
|
onTerminal: (address) => this.runRepo.update(runId, { hc_terminal: address }),
|
|
2212
|
+
defaultModel: this.settingsRepo?.getSetupSelection?.()?.default_model,
|
|
1838
2213
|
});
|
|
1839
2214
|
this.runRepo.update(runId, { hc_terminal: terminal });
|
|
1840
2215
|
} else {
|
|
@@ -1861,7 +2236,7 @@ export class Orchestrator {
|
|
|
1861
2236
|
*/
|
|
1862
2237
|
async approveHubFixes(runId: string): Promise<{ run: Run; applied: string[]; failed: string[] }> {
|
|
1863
2238
|
const run = this.runRepo.get(runId);
|
|
1864
|
-
if (!run) throw new
|
|
2239
|
+
if (!run) throw new NotFoundError(`Run '${runId}' not found`);
|
|
1865
2240
|
if (run.state !== 'blocked' || run.failure_reason !== 'hub_incomplete' || !run.hub_analysis) {
|
|
1866
2241
|
throw new ValidationError('Solo se aprueban arreglos de un run bloqueado por un hub incompleto');
|
|
1867
2242
|
}
|
|
@@ -2014,8 +2389,16 @@ export class Orchestrator {
|
|
|
2014
2389
|
(t) => t.state === 'live' && t.labels?.['bond.branch'] === ticket.target_branch && t.address
|
|
2015
2390
|
);
|
|
2016
2391
|
if (branchTerminals.length > 0) {
|
|
2392
|
+
const errors: string[] = [];
|
|
2017
2393
|
for (const term of branchTerminals) {
|
|
2018
|
-
|
|
2394
|
+
try {
|
|
2395
|
+
await this.hcClient.sendText(term.address!, text);
|
|
2396
|
+
} catch (err) {
|
|
2397
|
+
errors.push(`${term.address}: ${(err as Error).message || String(err)}`);
|
|
2398
|
+
}
|
|
2399
|
+
}
|
|
2400
|
+
if (errors.length > 0) {
|
|
2401
|
+
throw new ValidationError(`Fallo al enviar mensaje a terminales: ${errors.join(', ')}`);
|
|
2019
2402
|
}
|
|
2020
2403
|
return;
|
|
2021
2404
|
}
|
|
@@ -2023,10 +2406,15 @@ export class Orchestrator {
|
|
|
2023
2406
|
(t) => t.state === 'live' && (t.name === 'hub-leader' || t.name === 'hub leader' || t.address?.endsWith('/t1')) && t.address
|
|
2024
2407
|
);
|
|
2025
2408
|
if (leader) {
|
|
2026
|
-
|
|
2027
|
-
|
|
2409
|
+
try {
|
|
2410
|
+
await this.hcClient.sendText(leader.address!, text);
|
|
2411
|
+
return;
|
|
2412
|
+
} catch (err) {
|
|
2413
|
+
throw new ValidationError(`Fallo al enviar mensaje al líder ${leader.address}: ${(err as Error).message || String(err)}`);
|
|
2414
|
+
}
|
|
2028
2415
|
}
|
|
2029
|
-
} catch {
|
|
2416
|
+
} catch (err) {
|
|
2417
|
+
if (err instanceof ValidationError) throw err;
|
|
2030
2418
|
// Fall back to bond team prompt with BOND_TEAM_ENGINE=hc below
|
|
2031
2419
|
}
|
|
2032
2420
|
}
|
|
@@ -2060,6 +2448,8 @@ export class Orchestrator {
|
|
|
2060
2448
|
const hub = await session.readHubToml();
|
|
2061
2449
|
const missing = new Set<string>();
|
|
2062
2450
|
for (const r of hub.repos) {
|
|
2451
|
+
// P5 debt L-1: validate repo names in unblockHub and prevent _hub_ collision
|
|
2452
|
+
if (!NAME_RE.test(r.name) || r.name === '_hub_') continue;
|
|
2063
2453
|
if (!r.url || !validateGitHubUrl(r.url)) continue;
|
|
2064
2454
|
const present = await session.runner(['test', '-e', `${HUB_DIR}/${r.path}/.git`]);
|
|
2065
2455
|
if (present.exitCode !== 0) {
|
|
@@ -2076,7 +2466,7 @@ export class Orchestrator {
|
|
|
2076
2466
|
if (!ticket.hub_url) {
|
|
2077
2467
|
const adds: HubFix[] = ticket.repos
|
|
2078
2468
|
.map((r) => ({ name: repoNameFromUrl(r.url), url: r.url, base: r.base_branch }))
|
|
2079
|
-
.filter((r) => !hub.repos.some((h) => h.name === r.name))
|
|
2469
|
+
.filter((r) => NAME_RE.test(r.name) && r.name !== '_hub_' && !hub.repos.some((h) => h.name === r.name))
|
|
2080
2470
|
.map((r) => ({ action: 'hub_add' as const, name: r.name, url: r.url, base_branch: r.base }));
|
|
2081
2471
|
for (const fix of adds) await session.removeDir(`/workspace/repos/${fix.name}`);
|
|
2082
2472
|
if (adds.length > 0) await session.applyFixes(adds, ticket.target_branch, token);
|
|
@@ -2098,14 +2488,14 @@ export class Orchestrator {
|
|
|
2098
2488
|
createRun(ticketId: string): Run {
|
|
2099
2489
|
const ticket = this.ticketRepo.get(ticketId);
|
|
2100
2490
|
if (!ticket) {
|
|
2101
|
-
throw new
|
|
2491
|
+
throw new NotFoundError(`Ticket '${ticketId}' not found`);
|
|
2102
2492
|
}
|
|
2103
2493
|
|
|
2104
2494
|
// M10: Refuse second active run per ticket
|
|
2105
2495
|
const activeRuns = this.runRepo.listActive();
|
|
2106
2496
|
const existingActive = activeRuns.find((r) => r.ticket_id === ticketId);
|
|
2107
2497
|
if (existingActive) {
|
|
2108
|
-
throw new
|
|
2498
|
+
throw new ValidationError(`Cannot create a new run: ticket '${ticketId}' already has an active run '${existingActive.id}'`);
|
|
2109
2499
|
}
|
|
2110
2500
|
|
|
2111
2501
|
const run = this.runRepo.create(ticketId);
|
|
@@ -2114,10 +2504,14 @@ export class Orchestrator {
|
|
|
2114
2504
|
}
|
|
2115
2505
|
|
|
2116
2506
|
/**
|
|
2117
|
-
* Start executing a run.
|
|
2507
|
+
* Start executing a run. Filters options so test-only options cannot be passed (P3 criterion 4).
|
|
2118
2508
|
*/
|
|
2119
2509
|
async startRun(runId: string, options: StartRunOptions = {}): Promise<Run> {
|
|
2120
|
-
|
|
2510
|
+
const filtered: StartRunOptions = {
|
|
2511
|
+
githubToken: typeof options?.githubToken === 'string' ? options.githubToken : undefined,
|
|
2512
|
+
allowExistingRemoteBranch: Boolean(options?.allowExistingRemoteBranch),
|
|
2513
|
+
};
|
|
2514
|
+
return this.internalStartRun(runId, filtered);
|
|
2121
2515
|
}
|
|
2122
2516
|
|
|
2123
2517
|
/**
|
|
@@ -2175,11 +2569,11 @@ export class Orchestrator {
|
|
|
2175
2569
|
private async internalStartRun(runId: string, options: TestStartRunOptions = {}): Promise<Run> {
|
|
2176
2570
|
const run = this.runRepo.get(runId);
|
|
2177
2571
|
if (!run) {
|
|
2178
|
-
throw new
|
|
2572
|
+
throw new NotFoundError(`Run '${runId}' not found`);
|
|
2179
2573
|
}
|
|
2180
2574
|
let ticket = this.ticketRepo.get(run.ticket_id);
|
|
2181
2575
|
if (!ticket) {
|
|
2182
|
-
throw new
|
|
2576
|
+
throw new NotFoundError(`Ticket '${run.ticket_id}' not found`);
|
|
2183
2577
|
}
|
|
2184
2578
|
|
|
2185
2579
|
// L1: Validate input BEFORE creating any resources (network, container, hc machine).
|
|
@@ -2396,7 +2790,7 @@ fi
|
|
|
2396
2790
|
15000
|
|
2397
2791
|
);
|
|
2398
2792
|
if (revParseRes.exitCode === 0) {
|
|
2399
|
-
throw new
|
|
2793
|
+
throw new ValidationError(`Remote branch '${targetBranch}' already exists on origin (N4)`);
|
|
2400
2794
|
} else if (revParseRes.exitCode > 1) {
|
|
2401
2795
|
throw new Error(`Failed to check remote branch: ${revParseRes.stderr}`);
|
|
2402
2796
|
}
|
|
@@ -2456,8 +2850,14 @@ fi
|
|
|
2456
2850
|
return this.runRepo.get(run.id)!;
|
|
2457
2851
|
}
|
|
2458
2852
|
|
|
2853
|
+
if (!options.skipClone) {
|
|
2854
|
+
await this.bondifyRepo(containerInfo.containerName, ticket, run.id);
|
|
2855
|
+
}
|
|
2856
|
+
|
|
2857
|
+
assertQueued();
|
|
2858
|
+
|
|
2459
2859
|
const agentCwd = options.skipClone ? '/workspace' : '/workspace/repo';
|
|
2460
|
-
const hcTerminal = await this.hcClient.startTerminal(hcMachine, this.
|
|
2860
|
+
const hcTerminal = await this.hcClient.startTerminal(hcMachine, await this.resolveAgentCommand(containerInfo.containerName, ticket), agentCwd);
|
|
2461
2861
|
this.runRepo.update(run.id, { hc_terminal: hcTerminal });
|
|
2462
2862
|
await this.hcClient.assertTerminalAlive(hcTerminal);
|
|
2463
2863
|
|
|
@@ -2490,52 +2890,63 @@ fi
|
|
|
2490
2890
|
startError = err;
|
|
2491
2891
|
throw err;
|
|
2492
2892
|
} finally {
|
|
2493
|
-
|
|
2494
|
-
|
|
2495
|
-
|
|
2496
|
-
|
|
2497
|
-
|
|
2498
|
-
|
|
2499
|
-
|
|
2500
|
-
|
|
2501
|
-
|
|
2502
|
-
|
|
2503
|
-
|
|
2504
|
-
|
|
2505
|
-
|
|
2506
|
-
|
|
2507
|
-
|
|
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) });
|
|
2893
|
+
try {
|
|
2894
|
+
if (startError) {
|
|
2895
|
+
this.runTokens.delete(runId);
|
|
2896
|
+
this.mountFailures.delete(runId);
|
|
2897
|
+
this.analysisNotes.delete(runId);
|
|
2898
|
+
// M-D: Teardown resources unconditionally in finally
|
|
2899
|
+
try {
|
|
2900
|
+
await this.teardownRunResources(runId, containerName);
|
|
2901
|
+
} catch {
|
|
2902
|
+
// teardown failure sets cleanup_pending in DB
|
|
2903
|
+
}
|
|
2904
|
+
|
|
2905
|
+
// L2: Wait for in-flight termination so we do not race with concurrent cancelRun
|
|
2906
|
+
while (this.inFlightTerminations.has(runId)) {
|
|
2907
|
+
await new Promise((r) => setTimeout(r, 20));
|
|
2517
2908
|
}
|
|
2518
|
-
|
|
2519
|
-
|
|
2520
|
-
|
|
2521
|
-
|
|
2522
|
-
|
|
2523
|
-
|
|
2524
|
-
|
|
2909
|
+
|
|
2910
|
+
// L2: Mark run failed if not already terminal, preserving any concurrent cancellation reason
|
|
2911
|
+
const latest = this.runRepo.get(runId);
|
|
2912
|
+
if (latest && latest.state !== 'failed' && latest.state !== 'pr_ready') {
|
|
2913
|
+
const oldState = latest.state;
|
|
2914
|
+
const failureReason =
|
|
2915
|
+
this.cancellationRequested.has(runId)
|
|
2916
|
+
? 'cancelled'
|
|
2917
|
+
: startError instanceof ValidationError
|
|
2918
|
+
? 'validation_error'
|
|
2919
|
+
: startError instanceof HubMountError
|
|
2920
|
+
? 'hub_mount_failed'
|
|
2921
|
+
: 'container_error';
|
|
2922
|
+
if (startError instanceof HubMountError) {
|
|
2923
|
+
this.agentEvent(latest, 'hub.mount_failed', { error: startError.message.slice(0, 300) });
|
|
2924
|
+
}
|
|
2925
|
+
const { updated } = this.runRepo.updateStateConditionally(
|
|
2926
|
+
runId,
|
|
2927
|
+
oldState,
|
|
2928
|
+
'failed',
|
|
2929
|
+
{
|
|
2930
|
+
failure_reason: failureReason,
|
|
2931
|
+
finished_at: new Date().toISOString(),
|
|
2932
|
+
}
|
|
2933
|
+
);
|
|
2934
|
+
if (updated) {
|
|
2935
|
+
this.ticketRepo.updateStatus(ticket.id, 'failed');
|
|
2936
|
+
this.eventBus.publish(runId, ticket.id, 'run.state_changed', {
|
|
2937
|
+
run_id: runId,
|
|
2938
|
+
ticket_id: ticket.id,
|
|
2939
|
+
old_state: oldState,
|
|
2940
|
+
new_state: 'failed',
|
|
2941
|
+
reason: failureReason,
|
|
2942
|
+
timestamp: Date.now(),
|
|
2943
|
+
});
|
|
2525
2944
|
}
|
|
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
2945
|
}
|
|
2538
2946
|
}
|
|
2947
|
+
} finally {
|
|
2948
|
+
this.startingRuns.delete(runId);
|
|
2949
|
+
this.cancellationRequested.delete(runId);
|
|
2539
2950
|
}
|
|
2540
2951
|
}
|
|
2541
2952
|
}
|
|
@@ -2554,13 +2965,169 @@ fi
|
|
|
2554
2965
|
}
|
|
2555
2966
|
const story = [ticket.story ?? '', ticket.prompt ?? ''].filter((s) => s.trim()).join('\n\n');
|
|
2556
2967
|
const prompt = (promptOverride ?? story).trim();
|
|
2557
|
-
// P4: the ticket's model for pi (`--model provider/id`),
|
|
2558
|
-
|
|
2559
|
-
|
|
2968
|
+
// P4 & D-M1: the ticket's model for pi (`--model provider/id`), or default_model if ticket has none.
|
|
2969
|
+
const defaultModel = ticket.agent === 'pi' ? this.settingsRepo?.getSetupSelection?.()?.default_model : null;
|
|
2970
|
+
const model = ticket.agent === 'pi' ? (ticket.model || defaultModel) : null;
|
|
2971
|
+
if (ticket.agent === 'pi' && model) {
|
|
2972
|
+
return prompt ? ['pi', '--model', model, prompt] : ['pi', '--model', model];
|
|
2560
2973
|
}
|
|
2561
2974
|
return prompt ? [ticket.agent, prompt] : [ticket.agent];
|
|
2562
2975
|
}
|
|
2563
2976
|
|
|
2977
|
+
/**
|
|
2978
|
+
* P4 (D-U): Auto-bondify repository if it lacks .bond/bond.toml.
|
|
2979
|
+
* If config.runnerLauncher === 'bond' and ticket.bondify !== false:
|
|
2980
|
+
* Probes `command -v bond >/dev/null 2>&1 && [ ! -f /workspace/repo/.bond/bond.toml ]`.
|
|
2981
|
+
* If true, runs in /workspace/repo `bond init --yes --agents <ticket.agent>`, then commits
|
|
2982
|
+
* the MINIMAL bondification à la bond-hub: only `.bond/bond.toml` (and `AGENTS.md` when bond
|
|
2983
|
+
* init created or modified it). The runtime output of bond init (`.agents/`, `.pi/`, ...)
|
|
2984
|
+
* stays on disk for the agent but is appended to `.git/info/exclude` so neither this commit
|
|
2985
|
+
* nor the agent's own `git add -A` ever carries it into the PR.
|
|
2986
|
+
* Emits agentEvent on completion or failure.
|
|
2987
|
+
*
|
|
2988
|
+
* Pi non-interactive trust: /workspace is already trusted in /home/runner/.pi/agent/trust.json
|
|
2989
|
+
* (baked into the runner image in runner/Dockerfile via runner/pi-trust.json). Because pi and
|
|
2990
|
+
* bond match the nearest ancestor directory when checking trust, any path inside /workspace/repo
|
|
2991
|
+
* inherits project trust automatically without user prompts or confirmation dialogs.
|
|
2992
|
+
*
|
|
2993
|
+
* If .bond/bond.toml already exists, does nothing.
|
|
2994
|
+
* If ticket.bondify === false, does not probe at all.
|
|
2995
|
+
* If bond init or commit fails, logs and records an event, but continues without throwing.
|
|
2996
|
+
*/
|
|
2997
|
+
async bondifyRepo(
|
|
2998
|
+
containerName: string | null | undefined,
|
|
2999
|
+
ticket: Ticket,
|
|
3000
|
+
runId: string
|
|
3001
|
+
): Promise<boolean> {
|
|
3002
|
+
if (this.config.runnerLauncher !== 'bond' || ticket.bondify === false || !containerName) {
|
|
3003
|
+
return false;
|
|
3004
|
+
}
|
|
3005
|
+
|
|
3006
|
+
try {
|
|
3007
|
+
const probe = await this.dockerClient.exec(
|
|
3008
|
+
containerName,
|
|
3009
|
+
['sh', '-c', 'command -v bond >/dev/null 2>&1 && [ ! -f /workspace/repo/.bond/bond.toml ]'],
|
|
3010
|
+
'runner',
|
|
3011
|
+
15000
|
|
3012
|
+
);
|
|
3013
|
+
if (probe.exitCode !== 0) {
|
|
3014
|
+
return false;
|
|
3015
|
+
}
|
|
3016
|
+
|
|
3017
|
+
const initRes = await this.dockerClient.exec(
|
|
3018
|
+
containerName,
|
|
3019
|
+
['sh', '-c', `cd /workspace/repo && bond init --yes --agents ${ticket.agent}`],
|
|
3020
|
+
'runner',
|
|
3021
|
+
30000
|
|
3022
|
+
);
|
|
3023
|
+
if (initRes.exitCode !== 0) {
|
|
3024
|
+
if (this.eventBus) {
|
|
3025
|
+
const run = this.runRepo?.get?.(runId);
|
|
3026
|
+
if (run) {
|
|
3027
|
+
this.agentEvent(run, 'bond.init_failed', { exitCode: initRes.exitCode, stderr: initRes.stderr });
|
|
3028
|
+
} else {
|
|
3029
|
+
this.eventBus.publish(runId, ticket.id, 'agent.event', {
|
|
3030
|
+
run_id: runId,
|
|
3031
|
+
ticket_id: ticket.id,
|
|
3032
|
+
event: 'bond.init_failed',
|
|
3033
|
+
exitCode: initRes.exitCode,
|
|
3034
|
+
stderr: initRes.stderr,
|
|
3035
|
+
});
|
|
3036
|
+
}
|
|
3037
|
+
}
|
|
3038
|
+
return false;
|
|
3039
|
+
}
|
|
3040
|
+
|
|
3041
|
+
const commitRes = await this.dockerClient.exec(
|
|
3042
|
+
containerName,
|
|
3043
|
+
[
|
|
3044
|
+
'sh',
|
|
3045
|
+
'-c',
|
|
3046
|
+
'cd /workspace/repo && printf "%s\\n" /.agents/ /.pi/ /.claude/ /.codex/ >> .git/info/exclude'
|
|
3047
|
+
+ ' && git add .bond/bond.toml'
|
|
3048
|
+
+ ' && { git add AGENTS.md 2>/dev/null || true; }'
|
|
3049
|
+
+ ' && { git diff --cached --quiet || git -c user.name=bond-app -c user.email=bond-app@localhost commit -q -m "chore: bond init"; }',
|
|
3050
|
+
],
|
|
3051
|
+
'runner',
|
|
3052
|
+
15000
|
|
3053
|
+
);
|
|
3054
|
+
if (commitRes.exitCode !== 0) {
|
|
3055
|
+
if (this.eventBus) {
|
|
3056
|
+
const run = this.runRepo?.get?.(runId);
|
|
3057
|
+
if (run) {
|
|
3058
|
+
this.agentEvent(run, 'bond.commit_failed', { exitCode: commitRes.exitCode, stderr: commitRes.stderr });
|
|
3059
|
+
} else {
|
|
3060
|
+
this.eventBus.publish(runId, ticket.id, 'agent.event', {
|
|
3061
|
+
run_id: runId,
|
|
3062
|
+
ticket_id: ticket.id,
|
|
3063
|
+
event: 'bond.commit_failed',
|
|
3064
|
+
exitCode: commitRes.exitCode,
|
|
3065
|
+
stderr: commitRes.stderr,
|
|
3066
|
+
});
|
|
3067
|
+
}
|
|
3068
|
+
}
|
|
3069
|
+
return false;
|
|
3070
|
+
}
|
|
3071
|
+
|
|
3072
|
+
if (this.eventBus) {
|
|
3073
|
+
const run = this.runRepo?.get?.(runId);
|
|
3074
|
+
if (run) {
|
|
3075
|
+
this.agentEvent(run, 'bond.init_done', { agent: ticket.agent, commit: 'chore: bond init' });
|
|
3076
|
+
} else {
|
|
3077
|
+
this.eventBus.publish(runId, ticket.id, 'agent.event', {
|
|
3078
|
+
run_id: runId,
|
|
3079
|
+
ticket_id: ticket.id,
|
|
3080
|
+
event: 'bond.init_done',
|
|
3081
|
+
agent: ticket.agent,
|
|
3082
|
+
commit: 'chore: bond init',
|
|
3083
|
+
});
|
|
3084
|
+
}
|
|
3085
|
+
}
|
|
3086
|
+
return true;
|
|
3087
|
+
} catch {
|
|
3088
|
+
return false;
|
|
3089
|
+
}
|
|
3090
|
+
}
|
|
3091
|
+
|
|
3092
|
+
/**
|
|
3093
|
+
* D-G (image plan): the launch command is `bond tui --agent <agente>` - bond is the
|
|
3094
|
+
* harness (skills, AGENTS.md, sync, decisions, the rich agent bar); the ticket prompt
|
|
3095
|
+
* travels after `--` so it reaches the agent as its first message (runner/SPIKE-BOND.md).
|
|
3096
|
+
* Falls back to the bare launcher (agentCommandFor) when runner_launcher is "pi", an
|
|
3097
|
+
* explicit BOND_APP_AGENT_COMMAND wins, the image has no bond with `tui`, or the clone
|
|
3098
|
+
* is not a bond repo - there bond would stop to offer `bond init`.
|
|
3099
|
+
*/
|
|
3100
|
+
async resolveAgentCommand(
|
|
3101
|
+
containerName: string | null | undefined,
|
|
3102
|
+
ticket: Ticket,
|
|
3103
|
+
promptOverride?: string
|
|
3104
|
+
): Promise<string[]> {
|
|
3105
|
+
if (this.config.runnerLauncher !== 'bond' || this.config.agentCommand || !containerName) {
|
|
3106
|
+
return this.agentCommandFor(ticket, promptOverride);
|
|
3107
|
+
}
|
|
3108
|
+
try {
|
|
3109
|
+
const probe = await this.dockerClient.exec(containerName, [
|
|
3110
|
+
'sh', '-c',
|
|
3111
|
+
'command -v bond >/dev/null 2>&1 && bond tui --help >/dev/null 2>&1 && [ -f "/workspace/repo/.bond/bond.toml" ]',
|
|
3112
|
+
]);
|
|
3113
|
+
if (probe.exitCode !== 0) return this.agentCommandFor(ticket, promptOverride);
|
|
3114
|
+
} catch {
|
|
3115
|
+
return this.agentCommandFor(ticket, promptOverride);
|
|
3116
|
+
}
|
|
3117
|
+
if (!isValidAgent(ticket.agent)) {
|
|
3118
|
+
throw new ValidationError(`Unsupported agent '${ticket.agent}'`);
|
|
3119
|
+
}
|
|
3120
|
+
const story = [ticket.story ?? '', ticket.prompt ?? ''].filter((s) => s.trim()).join('\n\n');
|
|
3121
|
+
const prompt = (promptOverride ?? story).trim();
|
|
3122
|
+
const argv = ['bond', 'tui', '--agent', ticket.agent, '--'];
|
|
3123
|
+
// P4 (D-D) & D-M1: el modelo solo aplica a pi; default_model si el ticket no trae modelo.
|
|
3124
|
+
const defaultModel = ticket.agent === 'pi' ? this.settingsRepo?.getSetupSelection?.()?.default_model : null;
|
|
3125
|
+
const model = ticket.agent === 'pi' ? (ticket.model || defaultModel) : null;
|
|
3126
|
+
if (ticket.agent === 'pi' && model) argv.push('--model', model);
|
|
3127
|
+
if (prompt) argv.push(prompt);
|
|
3128
|
+
return argv;
|
|
3129
|
+
}
|
|
3130
|
+
|
|
2564
3131
|
/**
|
|
2565
3132
|
* Teardown the run's hc machine, container and network (N1, M3, M4, P3).
|
|
2566
3133
|
* The hc machine is forgotten first; the container and network are removed even if
|
|
@@ -2615,7 +3182,7 @@ fi
|
|
|
2615
3182
|
async cancelRun(runId: string, reason: FailureReason = 'cancelled'): Promise<{ durationMs: number; run: Run }> {
|
|
2616
3183
|
const run = this.runRepo.get(runId);
|
|
2617
3184
|
if (!run) {
|
|
2618
|
-
throw new
|
|
3185
|
+
throw new NotFoundError(`Run '${runId}' not found`);
|
|
2619
3186
|
}
|
|
2620
3187
|
|
|
2621
3188
|
const t0 = Date.now();
|
|
@@ -2626,11 +3193,18 @@ fi
|
|
|
2626
3193
|
return { durationMs: Date.now() - t0, run: this.runRepo.get(runId)! };
|
|
2627
3194
|
}
|
|
2628
3195
|
|
|
2629
|
-
|
|
2630
|
-
|
|
2631
|
-
|
|
2632
|
-
|
|
2633
|
-
|
|
3196
|
+
this.cancellationRequested.add(runId);
|
|
3197
|
+
try {
|
|
3198
|
+
const updated = await this.terminateRun(runId, 'failed', reason);
|
|
3199
|
+
return {
|
|
3200
|
+
durationMs: Date.now() - t0,
|
|
3201
|
+
run: updated,
|
|
3202
|
+
};
|
|
3203
|
+
} finally {
|
|
3204
|
+
if (!this.startingRuns.has(runId)) {
|
|
3205
|
+
this.cancellationRequested.delete(runId);
|
|
3206
|
+
}
|
|
3207
|
+
}
|
|
2634
3208
|
}
|
|
2635
3209
|
|
|
2636
3210
|
/**
|
|
@@ -2643,7 +3217,7 @@ fi
|
|
|
2643
3217
|
async deleteTicket(ticketId: string, options: { force?: boolean } = {}): Promise<{ success: boolean }> {
|
|
2644
3218
|
const ticket = this.ticketRepo.get(ticketId);
|
|
2645
3219
|
if (!ticket) {
|
|
2646
|
-
throw new
|
|
3220
|
+
throw new NotFoundError(`Ticket '${ticketId}' not found`);
|
|
2647
3221
|
}
|
|
2648
3222
|
|
|
2649
3223
|
const runs = this.runRepo.list({ ticketId });
|
|
@@ -2754,7 +3328,7 @@ fi
|
|
|
2754
3328
|
requires_force: boolean;
|
|
2755
3329
|
}> {
|
|
2756
3330
|
const ticket = this.ticketRepo.get(ticketId);
|
|
2757
|
-
if (!ticket) throw new
|
|
3331
|
+
if (!ticket) throw new NotFoundError(`Ticket '${ticketId}' not found`);
|
|
2758
3332
|
|
|
2759
3333
|
const runs = this.runRepo.list({ ticketId });
|
|
2760
3334
|
const latestRun = runs[0] ?? null;
|
|
@@ -2853,7 +3427,7 @@ fi
|
|
|
2853
3427
|
try {
|
|
2854
3428
|
const run = this.runRepo.get(runId);
|
|
2855
3429
|
if (!run) {
|
|
2856
|
-
throw new
|
|
3430
|
+
throw new NotFoundError(`Run '${runId}' not found`);
|
|
2857
3431
|
}
|
|
2858
3432
|
|
|
2859
3433
|
if (run.state === 'failed' || run.state === 'pr_ready' || run.state === 'finished') {
|
|
@@ -2873,9 +3447,24 @@ fi
|
|
|
2873
3447
|
|
|
2874
3448
|
// Re-read run state after async teardown
|
|
2875
3449
|
const latest = this.runRepo.get(runId);
|
|
2876
|
-
if (!latest || latest.state === '
|
|
3450
|
+
if (!latest || latest.state === 'pr_ready' || latest.state === 'finished') {
|
|
2877
3451
|
return latest || run;
|
|
2878
3452
|
}
|
|
3453
|
+
if (latest.state === 'failed') {
|
|
3454
|
+
if (reason && latest.failure_reason !== reason) {
|
|
3455
|
+
this.runRepo.update(runId, { failure_reason: reason });
|
|
3456
|
+
this.eventBus.publish(runId, latest.ticket_id, 'run.state_changed', {
|
|
3457
|
+
run_id: runId,
|
|
3458
|
+
ticket_id: latest.ticket_id,
|
|
3459
|
+
old_state: 'failed',
|
|
3460
|
+
new_state: 'failed',
|
|
3461
|
+
reason: reason,
|
|
3462
|
+
timestamp: Date.now(),
|
|
3463
|
+
});
|
|
3464
|
+
return this.runRepo.get(runId)!;
|
|
3465
|
+
}
|
|
3466
|
+
return latest;
|
|
3467
|
+
}
|
|
2879
3468
|
|
|
2880
3469
|
const oldState = latest.state;
|
|
2881
3470
|
const updates: Partial<Run> = {
|
|
@@ -2907,38 +3496,93 @@ fi
|
|
|
2907
3496
|
return this.runRepo.get(runId)!;
|
|
2908
3497
|
} finally {
|
|
2909
3498
|
this.inFlightTerminations.delete(runId);
|
|
3499
|
+
if (!this.startingRuns.has(runId)) {
|
|
3500
|
+
this.cancellationRequested.delete(runId);
|
|
3501
|
+
}
|
|
2910
3502
|
}
|
|
2911
3503
|
}
|
|
2912
3504
|
|
|
2913
3505
|
/**
|
|
2914
3506
|
* P2 criterion 7 (D7): rebuild the runner image with the new pinned versions of
|
|
2915
|
-
* bond, hc and the agents.
|
|
2916
|
-
*
|
|
3507
|
+
* bond, hc and the agents. Image plan P2: the body may also pick the agent list and
|
|
3508
|
+
* optional staged config/credentials; the data dir root for their validation is
|
|
3509
|
+
* injected here, never taken from the request.
|
|
3510
|
+
* Credentials are never touched by a plain rebuild: they never live in the image
|
|
3511
|
+
* unless explicitly staged (D-A) and nothing secret goes on the docker command line.
|
|
2917
3512
|
*/
|
|
2918
|
-
async rebuildRunnerImage(
|
|
3513
|
+
async rebuildRunnerImage(
|
|
3514
|
+
versions: RunnerVersions = {},
|
|
3515
|
+
extras: {
|
|
3516
|
+
agents?: string[];
|
|
3517
|
+
skip_az?: boolean;
|
|
3518
|
+
skip_gh?: boolean;
|
|
3519
|
+
config_dir?: string;
|
|
3520
|
+
credentials_file?: string;
|
|
3521
|
+
} = {}
|
|
3522
|
+
): Promise<{ image: string; rebuilt_at: string; credentials_touched: boolean }> {
|
|
2919
3523
|
if (this.rebuildInFlight) {
|
|
2920
3524
|
throw new RebuildInProgressError('A rebuild is already in progress');
|
|
2921
3525
|
}
|
|
2922
3526
|
this.rebuildInFlight = true;
|
|
2923
3527
|
try {
|
|
2924
|
-
await this.rebuildImpl(this.config.runnerImage,
|
|
3528
|
+
await this.rebuildImpl(this.config.runnerImage, {
|
|
3529
|
+
...versions,
|
|
3530
|
+
...extras,
|
|
3531
|
+
data_dir: this.config.dataDir,
|
|
3532
|
+
});
|
|
2925
3533
|
return {
|
|
2926
3534
|
image: this.config.runnerImage,
|
|
2927
3535
|
rebuilt_at: new Date().toISOString(),
|
|
2928
|
-
credentials_touched:
|
|
3536
|
+
credentials_touched: extras.credentials_file !== undefined,
|
|
2929
3537
|
};
|
|
2930
3538
|
} finally {
|
|
2931
3539
|
this.rebuildInFlight = false;
|
|
2932
3540
|
}
|
|
2933
3541
|
}
|
|
2934
3542
|
|
|
3543
|
+
/**
|
|
3544
|
+
* W-P1 (wizard): the aggregated setup state — selection, per-agent credentials, the gh
|
|
3545
|
+
* session and the runner image. Recomputed on every call (a stored credential shows up
|
|
3546
|
+
* without a restart); a docker that is not there or fails reads as image absent.
|
|
3547
|
+
*/
|
|
3548
|
+
async getSetupState(): Promise<SetupState> {
|
|
3549
|
+
let image: RunnerImageInfo;
|
|
3550
|
+
try {
|
|
3551
|
+
image = await this.dockerClient.inspectRunnerImage(this.config.runnerImage);
|
|
3552
|
+
} catch {
|
|
3553
|
+
image = { present: false };
|
|
3554
|
+
}
|
|
3555
|
+
const selection = this.settingsRepo.getSetupSelection();
|
|
3556
|
+
return buildSetupState({
|
|
3557
|
+
setup_done: selection.setup_done,
|
|
3558
|
+
agents_selected: selection.agents_selected,
|
|
3559
|
+
credentials: this.settingsRepo.listSummaries(),
|
|
3560
|
+
github: this.settingsRepo.getGitHubSummary(),
|
|
3561
|
+
image,
|
|
3562
|
+
suggestions_model: selection.suggestions_model,
|
|
3563
|
+
default_model: selection.default_model,
|
|
3564
|
+
models: selection.models,
|
|
3565
|
+
});
|
|
3566
|
+
}
|
|
3567
|
+
|
|
3568
|
+
/** W-P1: persists the wizard's selection; only the given fields change (validated by the API). */
|
|
3569
|
+
saveSetup(selection: {
|
|
3570
|
+
agents_selected?: string[];
|
|
3571
|
+
setup_done?: boolean;
|
|
3572
|
+
suggestions_model?: string | null;
|
|
3573
|
+
default_model?: string | null;
|
|
3574
|
+
models?: string[];
|
|
3575
|
+
}): void {
|
|
3576
|
+
this.settingsRepo.saveSetupSelection(selection);
|
|
3577
|
+
}
|
|
3578
|
+
|
|
2935
3579
|
/**
|
|
2936
3580
|
* State transitions. Terminal transitions delegate directly to terminateRun (H4, N2).
|
|
2937
3581
|
*/
|
|
2938
3582
|
async transitionRun(runId: string, newState: RunState, reason?: string | null): Promise<Run> {
|
|
2939
3583
|
const run = this.runRepo.get(runId);
|
|
2940
3584
|
if (!run) {
|
|
2941
|
-
throw new
|
|
3585
|
+
throw new NotFoundError(`Run '${runId}' not found`);
|
|
2942
3586
|
}
|
|
2943
3587
|
|
|
2944
3588
|
if (newState === 'failed' || newState === 'pr_ready') {
|
|
@@ -2949,7 +3593,7 @@ fi
|
|
|
2949
3593
|
|
|
2950
3594
|
const oldState = run.state;
|
|
2951
3595
|
const updates: Partial<Run> = {
|
|
2952
|
-
failure_reason: reason || undefined,
|
|
3596
|
+
failure_reason: reason !== undefined ? (reason || null) : (oldState === 'blocked' && newState !== 'blocked' ? null : undefined),
|
|
2953
3597
|
};
|
|
2954
3598
|
if (newState === 'running' && !run.started_at) {
|
|
2955
3599
|
updates.started_at = new Date().toISOString();
|