@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.
@@ -71,9 +71,9 @@ export class Watchdog {
71
71
  return true;
72
72
  }
73
73
 
74
- // 2. Queued timeout check (M-D): ensures stranded queued runs time out
74
+ // 2. Queued timeout check (M-D, P3 criterion 4): timeout measured strictly from created_at
75
75
  if (run.state === 'queued') {
76
- const queuedAt = new Date(run.updated_at || run.created_at).getTime();
76
+ const queuedAt = new Date(run.created_at).getTime();
77
77
  const queuedElapsedMs = Date.now() - queuedAt;
78
78
  const maxQueuedMs =
79
79
  ticket.timeout_minutes > 0
@@ -90,7 +90,7 @@ export class RunRepository {
90
90
  hc_machine = ?, hc_terminal = ?, cost_usd = ?, cleanup_pending = ?,
91
91
  verify_failures = ?, pr_url = ?, pr_number = ?, hub_analysis = ?, repo_states = ?,
92
92
  active_ms = ?, last_active_at = ?,
93
- started_at = ?, finished_at = ?, updated_at = ?
93
+ started_at = ?, finished_at = ?, updated_at = ?, created_at = ?
94
94
  WHERE id = ?
95
95
  `);
96
96
 
@@ -113,6 +113,7 @@ export class RunRepository {
113
113
  merged.started_at || null,
114
114
  merged.finished_at || null,
115
115
  merged.updated_at,
116
+ merged.created_at,
116
117
  id
117
118
  );
118
119
 
@@ -135,10 +136,16 @@ export class RunRepository {
135
136
  }
136
137
 
137
138
  const activeTime = applyActiveTimeTransition(existing, newState, updates);
139
+ // LOW-5: the reason for blocked is cleared when leaving that state
140
+ const failureReason = expectedOldState === 'blocked' && newState !== 'blocked'
141
+ ? (updates.failure_reason !== undefined ? updates.failure_reason : null)
142
+ : (updates.failure_reason !== undefined ? updates.failure_reason : existing.failure_reason);
143
+
138
144
  const merged = {
139
145
  ...existing,
140
146
  ...updates,
141
147
  state: newState,
148
+ failure_reason: failureReason,
142
149
  active_ms: activeTime.active_ms,
143
150
  last_active_at: activeTime.last_active_at,
144
151
  updated_at: updates.updated_at || new Date().toISOString(),
@@ -85,6 +85,19 @@ export class DockerClient {
85
85
  }
86
86
  }
87
87
 
88
+ async inspectNetwork(networkName: string): Promise<Record<string, unknown> | null> {
89
+ try {
90
+ const { stdout } = await execFileAsync('docker', ['network', 'inspect', networkName]);
91
+ const parsed = JSON.parse(stdout);
92
+ if (Array.isArray(parsed) && parsed.length > 0 && typeof parsed[0] === 'object' && parsed[0] !== null) {
93
+ return parsed[0] as Record<string, unknown>;
94
+ }
95
+ return null;
96
+ } catch {
97
+ return null;
98
+ }
99
+ }
100
+
88
101
  async listManagedNetworks(instanceId?: string): Promise<DockerNetworkSummary[]> {
89
102
  const args = [
90
103
  'network',
@@ -82,8 +82,13 @@ export class GitHubClient {
82
82
  }
83
83
  if (created.status === 422) {
84
84
  const q = `?head=${encodeURIComponent(`${owner}:${opts.head}`)}&base=${encodeURIComponent(opts.base)}&state=open`;
85
- const existing = await this.call(token, 'GET', `/repos/${owner}/${repo}/pulls${q}`);
86
- const list = (existing.data as Array<{ number: number; html_url: string }>) ?? [];
85
+ let existing = await this.call(token, 'GET', `/repos/${owner}/${repo}/pulls${q}`);
86
+ let list = (existing.data as Array<{ number: number; html_url: string }>) ?? [];
87
+ if (!Array.isArray(list) || list.length === 0) {
88
+ const q2 = `?head=${encodeURIComponent(opts.head)}&base=${encodeURIComponent(opts.base)}&state=open`;
89
+ existing = await this.call(token, 'GET', `/repos/${owner}/${repo}/pulls${q2}`);
90
+ list = (existing.data as Array<{ number: number; html_url: string }>) ?? [];
91
+ }
87
92
  if (existing.status === 200 && Array.isArray(list) && list.length > 0) {
88
93
  return { number: list[0].number, url: list[0].html_url, created: false };
89
94
  }
@@ -206,9 +206,42 @@ export class HcClient {
206
206
  /**
207
207
  * P9: List live terminals across machines, or only terminals on a specific machine.
208
208
  */
209
- async listTerminals(machine?: string): Promise<Array<{ address: string; name?: string; cwd?: string; state?: string; turn?: number }>> {
210
- const res = (await this.call(['ls', '--json'])) as { terminals?: Array<{ address: string; name?: string; cwd?: string; state?: string; turn?: number }> };
211
- const all = res.terminals ?? [];
209
+ async listTerminals(machine?: string): Promise<Array<{
210
+ address: string;
211
+ name?: string;
212
+ cwd?: string;
213
+ state?: string;
214
+ status?: unknown;
215
+ exit_code?: number | null;
216
+ turn?: number;
217
+ labels?: Record<string, string>;
218
+ agent?: string;
219
+ }>> {
220
+ const res = (await this.call(['ls', '--json'])) as {
221
+ terminals?: Array<{
222
+ address: string;
223
+ name?: string;
224
+ cwd?: string;
225
+ state?: string;
226
+ status?: unknown;
227
+ exit_code?: number | null;
228
+ turn?: number;
229
+ labels?: Record<string, string>;
230
+ agent?: string;
231
+ foreground?: { name?: string };
232
+ }>;
233
+ };
234
+ const all = (res.terminals ?? []).map((t) => ({
235
+ address: t.address,
236
+ name: t.name,
237
+ cwd: t.cwd,
238
+ state: t.state,
239
+ status: t.status,
240
+ exit_code: t.exit_code,
241
+ turn: t.turn,
242
+ labels: t.labels,
243
+ agent: t.agent || t.foreground?.name,
244
+ }));
212
245
  if (!machine) return all;
213
246
  const prefix = `${machine}/`;
214
247
  return all.filter((t) => t.address.startsWith(prefix) || t.address === machine);
@@ -217,11 +250,28 @@ export class HcClient {
217
250
  /**
218
251
  * P9: Query all terminals of a machine with full details (labels, status, turn)
219
252
  * directly from hc, with NO docker exec.
253
+ * P1 criterion 3: obtains state from `hc ls --json` without N+1 `hc get` per terminal,
254
+ * falling back to `getTerminal` only if the data is missing from ls.
220
255
  */
221
256
  async getMachineTerminals(machine: string): Promise<HcTerminalDetails[]> {
222
257
  const listed = await this.listTerminals(machine);
223
258
  const details = await Promise.all(
224
259
  listed.map(async (t) => {
260
+ const hasStatus = t.status !== undefined;
261
+ const hasLabels = t.labels !== undefined && typeof t.labels === 'object' && t.labels !== null;
262
+ if (hasStatus && hasLabels) {
263
+ return {
264
+ address: t.address,
265
+ name: t.name,
266
+ cwd: t.cwd,
267
+ state: t.state ?? null,
268
+ status: agentStatusOf(t.status),
269
+ exit_code: t.exit_code ?? null,
270
+ turn: typeof t.turn === 'number' ? t.turn : 0,
271
+ labels: t.labels,
272
+ agent: t.agent || t.name,
273
+ };
274
+ }
225
275
  try {
226
276
  return await this.getTerminal(t.address);
227
277
  } catch {
@@ -230,10 +280,11 @@ export class HcClient {
230
280
  name: t.name,
231
281
  cwd: t.cwd,
232
282
  state: t.state ?? null,
233
- status: null,
234
- exit_code: null,
235
- turn: t.turn ?? 0,
236
- labels: {},
283
+ status: t.status !== undefined ? agentStatusOf(t.status) : null,
284
+ exit_code: t.exit_code ?? null,
285
+ turn: typeof t.turn === 'number' ? t.turn : 0,
286
+ labels: t.labels ?? {},
287
+ agent: t.agent || t.name,
237
288
  };
238
289
  }
239
290
  })
package/src/server/app.ts CHANGED
@@ -1,7 +1,17 @@
1
1
  import http, { IncomingMessage, ServerResponse, Server } from 'node:http';
2
2
  import { URL } from 'node:url';
3
3
  import crypto from 'node:crypto';
4
- import { Orchestrator, ValidationError, RebuildInProgressError, GitHubCredentialMissingError, UnmergedBranchError } from '../core/orchestrator.ts';
4
+ import {
5
+ Orchestrator,
6
+ ValidationError,
7
+ RebuildInProgressError,
8
+ GitHubCredentialMissingError,
9
+ UnmergedBranchError,
10
+ NotFoundError,
11
+ ConflictError,
12
+ JsonParseError,
13
+ PayloadTooLargeError,
14
+ } from '../core/orchestrator.ts';
5
15
  import { InvalidVersionError, type RunnerVersions } from '../runner/image-builder.ts';
6
16
  import { InvalidStateTransitionError } from '../core/state-machine.ts';
7
17
  import { isValidAgent, validateGitHubLogin, validateGitHubToken, type CreateTicketInput, type RunState } from '../types.ts';
@@ -62,8 +72,8 @@ export function createServer(orchestrator: Orchestrator): Server {
62
72
  req.on('data', (chunk) => {
63
73
  bytes += chunk.length;
64
74
  if (bytes > maxBytes) {
65
- req.destroy();
66
- reject(new Error('Payload too large'));
75
+ req.pause();
76
+ reject(new PayloadTooLargeError('Payload too large'));
67
77
  return;
68
78
  }
69
79
  body += chunk.toString();
@@ -76,12 +86,12 @@ export function createServer(orchestrator: Orchestrator): Server {
76
86
  try {
77
87
  const parsed = JSON.parse(body);
78
88
  if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
79
- reject(new Error('JSON body must be an object'));
89
+ reject(new JsonParseError('JSON body must be an object'));
80
90
  return;
81
91
  }
82
92
  resolve(parsed);
83
93
  } catch {
84
- reject(new Error('Invalid JSON'));
94
+ reject(new JsonParseError('Invalid JSON'));
85
95
  }
86
96
  });
87
97
  req.on('error', reject);
@@ -149,8 +159,11 @@ export function createServer(orchestrator: Orchestrator): Server {
149
159
  const preview = await orchestrator.getDeletePreview(ticketId);
150
160
  sendJson(200, preview);
151
161
  } catch (err: unknown) {
152
- const msg = (err as Error).message;
153
- sendJson(msg.includes('not found') ? 404 : 500, { error: msg });
162
+ if (err instanceof NotFoundError) {
163
+ sendJson(404, { error: (err as Error).message });
164
+ } else {
165
+ sendJson(500, { error: (err as Error).message });
166
+ }
154
167
  }
155
168
  return;
156
169
  }
@@ -174,8 +187,7 @@ export function createServer(orchestrator: Orchestrator): Server {
174
187
  const pinned = ['repo_url', 'target_branch', 'base_branch', 'repos', 'hub_url', 'hub_base', 'repo_agents'].filter((k) => body[k] !== undefined);
175
188
  const active = orchestrator.runRepo.listActive().find((r) => r.ticket_id === ticketId);
176
189
  if (pinned.length > 0 && active) {
177
- sendJson(409, { error: `Cannot change ${pinned.join(', ')} while run '${active.id}' is active` });
178
- return;
190
+ throw new ConflictError(`Cannot change ${pinned.join(', ')} while run '${active.id}' is active`);
179
191
  }
180
192
  try {
181
193
  const updated = orchestrator.ticketRepo.update(ticketId, body);
@@ -203,9 +215,10 @@ export function createServer(orchestrator: Orchestrator): Server {
203
215
  branch: err.branch,
204
216
  base: err.base,
205
217
  });
218
+ } else if (err instanceof NotFoundError) {
219
+ sendJson(404, { error: (err as Error).message });
206
220
  } else {
207
- const msg = (err as Error).message;
208
- sendJson(msg.includes('not found') ? 404 : 500, { error: msg });
221
+ sendJson(500, { error: (err as Error).message });
209
222
  }
210
223
  }
211
224
  return;
@@ -232,11 +245,12 @@ export function createServer(orchestrator: Orchestrator): Server {
232
245
  const run = orchestrator.createRun(ticketId);
233
246
  sendJson(201, run);
234
247
  } catch (err: unknown) {
235
- const msg = (err as Error).message;
236
- if (msg.includes('not found')) {
237
- sendJson(404, { error: msg });
248
+ if (err instanceof NotFoundError) {
249
+ sendJson(404, { error: (err as Error).message });
250
+ } else if (err instanceof ValidationError) {
251
+ sendJson(400, { error: (err as Error).message });
238
252
  } else {
239
- sendJson(400, { error: msg });
253
+ sendJson(500, { error: (err as Error).message });
240
254
  }
241
255
  }
242
256
  return;
@@ -263,12 +277,11 @@ export function createServer(orchestrator: Orchestrator): Server {
263
277
  sendJson(400, { error: message, code: err.code });
264
278
  } else if (
265
279
  err instanceof ValidationError ||
266
- message.includes('not found') ||
267
- message.includes('Missing') ||
268
- message.includes('Invalid') ||
269
- message.includes('already exists')
280
+ err instanceof InvalidStateTransitionError
270
281
  ) {
271
282
  sendJson(400, { error: message });
283
+ } else if (err instanceof NotFoundError) {
284
+ sendJson(404, { error: message });
272
285
  } else {
273
286
  // L1: Return 500 for infrastructure errors
274
287
  sendJson(500, { error: message });
@@ -413,6 +426,14 @@ export function createServer(orchestrator: Orchestrator): Server {
413
426
  sendJson(400, { error: "'state' is required" });
414
427
  return;
415
428
  }
429
+ // D1: /transition only allows cancel and transitions that do not skip verification or PR
430
+ const DISALLOWED_STATES = new Set<RunState>(['finished', 'pr_ready', 'verifying']);
431
+ if (DISALLOWED_STATES.has(newState)) {
432
+ sendJson(400, {
433
+ error: `Transition to '${newState}' is not allowed: /transition only allows cancel and transitions that do not skip verification or PR (D1)`,
434
+ });
435
+ return;
436
+ }
416
437
  const run = await orchestrator.transitionRun(runId, newState, reason);
417
438
  sendJson(200, run);
418
439
  return;
@@ -469,9 +490,10 @@ export function createServer(orchestrator: Orchestrator): Server {
469
490
  branch: err.branch,
470
491
  base: err.base,
471
492
  });
493
+ } else if (err instanceof NotFoundError) {
494
+ sendJson(404, { error: (err as Error).message });
472
495
  } else {
473
- const msg = (err as Error).message;
474
- sendJson(msg.includes('not found') ? 404 : 500, { error: msg });
496
+ sendJson(500, { error: (err as Error).message });
475
497
  }
476
498
  }
477
499
  return;
@@ -563,12 +585,12 @@ export function createServer(orchestrator: Orchestrator): Server {
563
585
  // Not found
564
586
  sendJson(404, { error: 'Not found' });
565
587
  } catch (err: unknown) {
566
- if (err instanceof RebuildInProgressError) {
567
- sendJson(409, { error: err.message });
588
+ if (err instanceof RebuildInProgressError || err instanceof ConflictError) {
589
+ sendJson(409, { error: (err as Error).message });
568
590
  return;
569
591
  }
570
- if (err instanceof InvalidVersionError) {
571
- sendJson(400, { error: err.message });
592
+ if (err instanceof InvalidVersionError || err instanceof JsonParseError || err instanceof ValidationError) {
593
+ sendJson(400, { error: (err as Error).message });
572
594
  return;
573
595
  }
574
596
  if (err instanceof InvalidStateTransitionError) {
@@ -579,15 +601,16 @@ export function createServer(orchestrator: Orchestrator): Server {
579
601
  });
580
602
  return;
581
603
  }
582
- const e = err as Error;
583
- if (e.message === 'Invalid JSON' || e.message === 'JSON body must be an object') {
584
- sendJson(400, { error: e.message });
604
+ if (err instanceof PayloadTooLargeError) {
605
+ sendJson(413, { error: (err as Error).message });
606
+ req.destroy();
585
607
  return;
586
608
  }
587
- if (e.message === 'Payload too large') {
588
- sendJson(413, { error: e.message });
609
+ if (err instanceof NotFoundError) {
610
+ sendJson(404, { error: (err as Error).message });
589
611
  return;
590
612
  }
613
+ const e = err as Error;
591
614
  sendJson(500, { error: e.message || 'Internal server error' });
592
615
  }
593
616
  });