@jmanuelcorral/bond-app 0.1.1 → 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.
@@ -7,6 +7,7 @@
7
7
  * origin refs) and a symlinked repo by pointing the container's .bond/hub.local.toml at
8
8
  * its clone; then `bond hub sync --yes` and `bond hub check --json` do the rest.
9
9
  */
10
+ import path from 'node:path';
10
11
  import type { DockerClient } from '../runner/docker-client.ts';
11
12
  import type { HcClient } from '../runner/hc-client.ts';
12
13
  import {
@@ -58,12 +59,16 @@ export interface MountResult {
58
59
  export class HubSession {
59
60
  private docker: DockerClient;
60
61
  private ctr: string;
62
+ private hcClient?: HcClient;
63
+ private hcMachine?: string;
61
64
  /** Called after each repo is mounted (the orchestrator refreshes the run; review H3). */
62
65
  onProgress: () => void = () => {};
63
66
 
64
- constructor(docker: DockerClient, containerName: string) {
67
+ constructor(docker: DockerClient, containerName: string, hcClient?: HcClient, hcMachine?: string) {
65
68
  this.docker = docker;
66
69
  this.ctr = containerName;
70
+ this.hcClient = hcClient;
71
+ this.hcMachine = hcMachine;
67
72
  }
68
73
 
69
74
  /** A command as `runner`, with its HOME (bond and git read their config from there). */
@@ -259,7 +264,7 @@ export class HubSession {
259
264
  * every agent a repo's bond.toml lists, but a run only starts the team's agents (checked
260
265
  * apart, in the image): those failures are warnings.
261
266
  */
262
- async check(teamAgent: (repo: string) => string = () => ''): Promise<{ failures: string[]; warnings: string[] }> {
267
+ async check(teamAgent: (repo: string) => string = () => 'pi'): Promise<{ failures: string[]; warnings: string[] }> {
263
268
  const res = await this.runner(['sh', '-c', `cd ${HUB_DIR} && bond hub check --json </dev/null`], 120_000);
264
269
  const failures: string[] = [];
265
270
  const warnings: string[] = [];
@@ -431,11 +436,54 @@ export class HubSession {
431
436
  return sha;
432
437
  }
433
438
 
439
+ /**
440
+ * P1 criterion 6 & A-1: Check whether a real `bond team` command is currently executing
441
+ * in the container by scanning `/proc/<pid>/cmdline` and checking argv elements, so
442
+ * fallback does not compete with the leader and restoreDefaultAgent does not race.
443
+ *
444
+ * Note (A-1): We scan argv elements (some argv[i] whose basename is 'bond' followed by
445
+ * argv[i+1] === 'team', or basename 'bond-team'), never matching on free substrings
446
+ * of the command line, because the leader process (exec pi "$(cat orchestrator-prompt.txt)")
447
+ * carries the prompt in its argv which literally contains "bond team '<branch>'".
448
+ *
449
+ * Fail-open design (M-2): If docker.exec fails or times out (e.g. docker daemon under load
450
+ * or container unreachable), this returns `false` rather than blocking launches, allowing
451
+ * recovery to proceed.
452
+ */
453
+ async isTeamCommandRunning(): Promise<boolean> {
454
+ try {
455
+ const res = await this.runner(['node', '-e', CHECK_TEAM_RUNNING_SCRIPT], 5_000);
456
+ return res.exitCode === 0 && Boolean(res.stdout.trim());
457
+ } catch {
458
+ // Fail-open (M-2): On docker execution error, assume not running to prevent hanging launches
459
+ return false;
460
+ }
461
+ }
462
+
434
463
  /**
435
464
  * Review L-2: whether the run's team is already open (every repo has its worktree on the
436
465
  * branch with an agent), e.g. after an orchestrator restart during the launch.
466
+ * P1 criterion 1: with hc engine, decides reuse directly from hcClient with zero dockerClient.exec
467
+ * calls, keeping the current docker exec behavior for herdr engine.
437
468
  */
438
- async teamOpen(branch: string, repoCount: number, engine = 'herdr'): Promise<boolean> {
469
+ async teamOpen(branch: string, repoCount: number, engine = 'herdr', hcClient?: HcClient, machine?: string): Promise<boolean> {
470
+ const client = hcClient || this.hcClient;
471
+ const targetMachine = machine || this.hcMachine;
472
+ if (engine === 'hc' && client && targetMachine) {
473
+ try {
474
+ const terminals = await client.getMachineTerminals(targetMachine);
475
+ const liveRepoTerminals = terminals.filter(
476
+ (t) => t.state === 'live' && t.labels?.['bond.branch'] === branch && t.name !== 'hub-leader' && !t.address?.endsWith('/t1')
477
+ );
478
+ if (repoCount > 0 && liveRepoTerminals.length >= repoCount) {
479
+ return true;
480
+ }
481
+ return false;
482
+ } catch {
483
+ // Fall back to docker exec if hcClient query fails
484
+ }
485
+ }
486
+
439
487
  const engineEnv = engine === 'hc' ? 'BOND_TEAM_ENGINE=hc ' : '';
440
488
  const res = await this.runner(['sh', '-c', `cd ${HUB_DIR} && ${engineEnv}bond team status --json </dev/null`], 60_000);
441
489
  if (res.exitCode !== 0) return false;
@@ -596,9 +644,30 @@ export class HubSession {
596
644
  await new Promise((r) => setTimeout(r, pollMs));
597
645
  }
598
646
  if (!opened) {
599
- if (!(await this.teamOpen(branch, repos.length))) {
600
- const fallbackCmd = `cd ${HUB_DIR} && BOND_TEAM_NO_TABLE=1 HERDR_ENV=1 HERDR_PANE_ID=${shq(pane)} bond team ${shq(branch)} --repos ${repoList} --no-table --yes </dev/null`;
601
- await this.runner(['sh', '-c', fallbackCmd], 60_000);
647
+ // P1 criterion 6 (M-3 de P7): if leader is currently executing bond team, wait for it
648
+ if (await this.isTeamCommandRunning()) {
649
+ const teamEnd = Date.now() + Math.min(waitMs, 60_000);
650
+ while (Date.now() < teamEnd && (await this.isTeamCommandRunning())) {
651
+ if (await this.teamOpen(branch, repos.length)) {
652
+ opened = true;
653
+ break;
654
+ }
655
+ await new Promise((r) => setTimeout(r, pollMs));
656
+ }
657
+ }
658
+ if (!opened && !(await this.teamOpen(branch, repos.length))) {
659
+ if (!(await this.isTeamCommandRunning())) {
660
+ const fallbackCmd = `cd ${HUB_DIR} && BOND_TEAM_NO_TABLE=1 HERDR_ENV=1 HERDR_PANE_ID=${shq(pane)} bond team ${shq(branch)} --repos ${repoList} --no-table --yes </dev/null`;
661
+ await this.runner(['sh', '-c', fallbackCmd], 60_000);
662
+ }
663
+ }
664
+ }
665
+
666
+ // P1 criterion 6: wait for any running bond team to complete before restoring default agents
667
+ if (await this.isTeamCommandRunning()) {
668
+ const restEnd = Date.now() + 30_000;
669
+ while (Date.now() < restEnd && (await this.isTeamCommandRunning())) {
670
+ await new Promise((r) => setTimeout(r, pollMs));
602
671
  }
603
672
  }
604
673
 
@@ -669,7 +738,7 @@ export class HubSession {
669
738
  const teamDeadline = Date.now() + waitMs;
670
739
  let opened = false;
671
740
  while (Date.now() < teamDeadline) {
672
- if (await this.teamOpen(branch, repos.length, 'hc')) {
741
+ if (await this.teamOpen(branch, repos.length, 'hc', hc, machine)) {
673
742
  opened = true;
674
743
  break;
675
744
  }
@@ -688,9 +757,30 @@ export class HubSession {
688
757
  await new Promise((r) => setTimeout(r, pollMs));
689
758
  }
690
759
  if (!opened) {
691
- if (!(await this.teamOpen(branch, repos.length, 'hc'))) {
692
- const fallbackCmd = `cd ${HUB_DIR} && BOND_TEAM_NO_TABLE=1 BOND_TEAM_ENGINE=hc BOND_TEAM_LABELS='herdr.space=s1,herdr.tab=t1' bond team ${shq(branch)} --repos ${repoList} --engine hc --no-table --yes </dev/null`;
693
- await this.runner(['sh', '-c', fallbackCmd], 60_000);
760
+ // P1 criterion 6 (M-3 de P7): if leader is currently executing bond team, wait for it
761
+ if (await this.isTeamCommandRunning()) {
762
+ const teamEnd = Date.now() + Math.min(waitMs, 60_000);
763
+ while (Date.now() < teamEnd && (await this.isTeamCommandRunning())) {
764
+ if (await this.teamOpen(branch, repos.length, 'hc', hc, machine)) {
765
+ opened = true;
766
+ break;
767
+ }
768
+ await new Promise((r) => setTimeout(r, pollMs));
769
+ }
770
+ }
771
+ if (!opened && !(await this.teamOpen(branch, repos.length, 'hc', hc, machine))) {
772
+ if (!(await this.isTeamCommandRunning())) {
773
+ const fallbackCmd = `cd ${HUB_DIR} && BOND_TEAM_NO_TABLE=1 BOND_TEAM_ENGINE=hc BOND_TEAM_LABELS='herdr.space=s1,herdr.tab=t1' bond team ${shq(branch)} --repos ${repoList} --engine hc --no-table --yes </dev/null`;
774
+ await this.runner(['sh', '-c', fallbackCmd], 60_000);
775
+ }
776
+ }
777
+ }
778
+
779
+ // P1 criterion 6: wait for any running bond team to complete before restoring default agents
780
+ if (await this.isTeamCommandRunning()) {
781
+ const restEnd = Date.now() + 30_000;
782
+ while (Date.now() < restEnd && (await this.isTeamCommandRunning())) {
783
+ await new Promise((r) => setTimeout(r, pollMs));
694
784
  }
695
785
  }
696
786
 
@@ -728,4 +818,49 @@ export async function proposeUrls(
728
818
  return out;
729
819
  }
730
820
 
821
+ export const CHECK_TEAM_RUNNING_SCRIPT = `
822
+ const fs = require('fs');
823
+ const path = require('path');
824
+ try {
825
+ const pids = fs.readdirSync('/proc').filter((p) => /^\\d+$/.test(p));
826
+ for (const pid of pids) {
827
+ if (Number(pid) === process.pid) continue;
828
+ try {
829
+ const raw = fs.readFileSync('/proc/' + pid + '/cmdline');
830
+ if (!raw || raw.length === 0) continue;
831
+ const parts = raw.toString('utf8').split('\\0').filter(Boolean);
832
+ for (let i = 0; i < parts.length; i++) {
833
+ const base = path.basename(parts[i]).replace(/\\.[cm]?js$/, '');
834
+ if (base === 'bond-team') {
835
+ process.stdout.write('running\\n');
836
+ process.exit(0);
837
+ }
838
+ if (base === 'bond' && parts[i + 1] === 'team') {
839
+ process.stdout.write('running\\n');
840
+ process.exit(0);
841
+ }
842
+ }
843
+ } catch {}
844
+ }
845
+ } catch {}
846
+ process.exit(1);
847
+ `.trim().replace(/\n\s*/g, ' ');
848
+
849
+ /**
850
+ * P1 criterion 6 & A-1: Evaluates whether a process's argv elements represent
851
+ * a real `bond team` invocation, rather than substring matching the whole command line.
852
+ */
853
+ export function isBondTeamArgv(argv: string[]): boolean {
854
+ for (let i = 0; i < argv.length; i++) {
855
+ const base = path.basename(argv[i]).replace(/\.[cm]?js$/, '');
856
+ if (base === 'bond-team') {
857
+ return true;
858
+ }
859
+ if (base === 'bond' && argv[i + 1] === 'team') {
860
+ return true;
861
+ }
862
+ }
863
+ return false;
864
+ }
865
+
731
866
  export type { HubProbe };
package/src/core/hub.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  * answer, and the text edits «Aprobar arreglos» makes. The orchestrator does the I/O.
5
5
  */
6
6
  import { validateBranchName, validateGitHubUrl, isValidAgent } from '../types.ts';
7
- export { NAME_RE as REPO_NAME_RE };
7
+ export { NAME_RE, NAME_RE as REPO_NAME_RE };
8
8
  import type { HubAnalysis, HubAnalysisRepo, HubGap, Ticket } from '../types.ts';
9
9
 
10
10
  /** Where the hub and the clones of its symlinked repos live in the container. */
@@ -79,7 +79,7 @@ export function parseHubToml(text: string): HubToml {
79
79
  const m = /^repos\.(?:"([^"]+)"|([A-Za-z0-9_.-]+))$/.exec(table[1].trim());
80
80
  if (m) {
81
81
  currentName = m[1] ?? m[2];
82
- if (!NAME_RE.test(currentName)) throw new HubTomlError(`hub.toml: invalid repo name '${currentName}'`);
82
+ if (!NAME_RE.test(currentName) || currentName === '_hub_') throw new HubTomlError(`hub.toml: invalid repo name '${currentName}'`);
83
83
  current = {};
84
84
  } else {
85
85
  current = null;
@@ -246,35 +246,70 @@ export interface AgentAnswer {
246
246
  summary: string;
247
247
  }
248
248
 
249
- /** The last JSON object line of the agent's output, validated; null if there is none. */
249
+ function validateParsedAnswer(parsed: unknown): AgentAnswer | null {
250
+ if (!parsed || typeof parsed !== 'object') return null;
251
+ const p = parsed as { ready?: unknown; missing?: unknown; summary?: unknown };
252
+ if (typeof p.ready !== 'boolean') return null;
253
+ const missing = Array.isArray(p.missing)
254
+ ? p.missing
255
+ .filter((m): m is Record<string, unknown> => Boolean(m) && typeof m === 'object')
256
+ .map((m) => ({
257
+ name: String(m.name ?? '').slice(0, 64),
258
+ url: typeof m.url === 'string' && m.url ? m.url.trim() : null,
259
+ why: String(m.why ?? '').slice(0, 300),
260
+ }))
261
+ .filter((m) => m.name || m.url)
262
+ .slice(0, 10)
263
+ : [];
264
+ return { ready: p.ready && missing.length === 0, missing, summary: String(p.summary ?? '').slice(0, 500) };
265
+ }
266
+
267
+ /** The last JSON object of the agent's output, validated (single-line or block); null if there is none. */
250
268
  export function parseAgentAnswer(output: string): AgentAnswer | null {
251
269
  const lines = output.split(/\r?\n/).map((l) => l.trim()).filter(Boolean).reverse();
252
270
  for (const line of lines) {
253
271
  const start = line.indexOf('{');
254
272
  const end = line.lastIndexOf('}');
255
273
  if (start < 0 || end <= start) continue;
256
- let parsed: unknown;
257
274
  try {
258
- parsed = JSON.parse(line.slice(start, end + 1));
275
+ const parsed = JSON.parse(line.slice(start, end + 1));
276
+ const res = validateParsedAnswer(parsed);
277
+ if (res) return res;
259
278
  } catch {
260
279
  continue;
261
280
  }
262
- if (!parsed || typeof parsed !== 'object') continue;
263
- const p = parsed as { ready?: unknown; missing?: unknown; summary?: unknown };
264
- if (typeof p.ready !== 'boolean') continue;
265
- const missing = Array.isArray(p.missing)
266
- ? p.missing
267
- .filter((m): m is Record<string, unknown> => Boolean(m) && typeof m === 'object')
268
- .map((m) => ({
269
- name: String(m.name ?? '').slice(0, 64),
270
- url: typeof m.url === 'string' && m.url ? m.url.trim() : null,
271
- why: String(m.why ?? '').slice(0, 300),
272
- }))
273
- .filter((m) => m.name || m.url)
274
- .slice(0, 10)
275
- : [];
276
- return { ready: p.ready && missing.length === 0, missing, summary: String(p.summary ?? '').slice(0, 500) };
277
281
  }
282
+
283
+ // Fallback: extract markdown code blocks ```json ... ``` or ``` ... ```
284
+ const blockRegex = /```(?:json)?\s*([\s\S]*?)\s*```/g;
285
+ let match: RegExpExecArray | null;
286
+ const blocks: string[] = [];
287
+ while ((match = blockRegex.exec(output)) !== null) {
288
+ blocks.push(match[1].trim());
289
+ }
290
+ for (const block of blocks.reverse()) {
291
+ try {
292
+ const parsed = JSON.parse(block);
293
+ const res = validateParsedAnswer(parsed);
294
+ if (res) return res;
295
+ } catch {
296
+ continue;
297
+ }
298
+ }
299
+
300
+ // Fallback: outermost balanced or slice JSON object
301
+ const firstBrace = output.indexOf('{');
302
+ const lastBrace = output.lastIndexOf('}');
303
+ if (firstBrace >= 0 && lastBrace > firstBrace) {
304
+ try {
305
+ const parsed = JSON.parse(output.slice(firstBrace, lastBrace + 1));
306
+ const res = validateParsedAnswer(parsed);
307
+ if (res) return res;
308
+ } catch {
309
+ // ignore
310
+ }
311
+ }
312
+
278
313
  return null;
279
314
  }
280
315