@jmanuelcorral/bond-app 0.2.2 → 0.3.1

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/src/cli.ts CHANGED
@@ -18,6 +18,7 @@ import type { ServerHooks } from './server/app.ts';
18
18
  import { MIN_HC_VERSION, MIN_HERDR_APP_VERSION } from './runner/hc-client.ts';
19
19
  import { install, parseInstallArgs, removeLauncher } from '../scripts/app-install.ts';
20
20
  import { runDoctor, type DoctorDeps, type DoctorReport } from './core/doctor.ts';
21
+ import { collectDiagnosis, ISSUE_REPO } from './core/diagnose.ts';
21
22
  import {
22
23
  maybeHandleFirstRun,
23
24
  runSetup,
@@ -549,6 +550,103 @@ export async function handleStatus(args: string[]): Promise<number> {
549
550
  return res.running ? 0 : 1;
550
551
  }
551
552
 
553
+ /**
554
+ * `bond-app diagnose [--out <file.zip>] [--issue [--yes]]`: the logs, doctor, versions, the
555
+ * service and the last runs in a zip without secrets (works with the orchestrator down).
556
+ * `--issue` shows what it will send and, once confirmed, opens an issue in jmanuelcorral/bond-app
557
+ * with gh; the zip is attached by the person (GitHub's API cannot attach files).
558
+ */
559
+ export async function handleDiagnose(args: string[]): Promise<number> {
560
+ let dataDir = defaultDataDir();
561
+ let home = defaultHerdrAppHome();
562
+ let port = parseInt(process.env.BOND_APP_PORT || '3000', 10);
563
+ let host = process.env.BOND_APP_HOST || '127.0.0.1';
564
+ let out: string | null = null;
565
+ let issue = false;
566
+ let yes = false;
567
+ for (let i = 0; i < args.length; i++) {
568
+ const arg = args[i];
569
+ const value = () => {
570
+ const v = args[++i];
571
+ if (!v || v.startsWith('--')) throw new Error(`${arg} requires a value`);
572
+ return v;
573
+ };
574
+ if (arg === '--data-dir') dataDir = path.resolve(value());
575
+ else if (arg === '--home') home = path.resolve(value());
576
+ else if (arg === '--port') port = parseInt(value(), 10);
577
+ else if (arg === '--host') host = value();
578
+ else if (arg === '--out') out = path.resolve(value());
579
+ else if (arg === '--issue') issue = true;
580
+ else if (arg === '--yes' || arg === '-y') yes = true;
581
+ else if (arg === '-h' || arg === '--help') {
582
+ console.log(`Usage: bond-app diagnose [--out <file.zip>] [--issue [--yes]] [--data-dir <dir>] [--home <dir>]
583
+
584
+ Zips the orchestrator and herdr-app logs, bond-app doctor, versions (bond, hc, herdr-app,
585
+ docker), the user service and the last runs, with tokens and credentials replaced by ***.
586
+ --issue shows the summary it will send and opens an issue in ${ISSUE_REPO} with gh; then
587
+ drag the zip into the issue.`);
588
+ return 0;
589
+ } else throw new Error(`unknown option '${arg}' for diagnose`);
590
+ }
591
+
592
+ console.log('Recogiendo el diagnóstico (doctor, versiones, logs)…');
593
+ const report = await runDoctor({ port, host, dataDir, home });
594
+ let service: { status: string; unitPath: string | null } | undefined;
595
+ try {
596
+ const st = await getServiceStatus({ dataDir });
597
+ service = { status: JSON.stringify(st, null, 2), unitPath: st.unitPath };
598
+ } catch {}
599
+ const d = await collectDiagnosis({ dataDir, herdrAppHome: home, doctorJson: JSON.stringify(report, null, 2), service, version: VERSION });
600
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
601
+ const zipPath = out ?? path.join(dataDir, 'diagnostics', `bond-app-diagnose-${stamp}.zip`);
602
+ fs.mkdirSync(path.dirname(zipPath), { recursive: true, mode: 0o700 });
603
+ fs.writeFileSync(zipPath, d.zip, { mode: 0o600 });
604
+ console.log(`\nZip: ${zipPath}`);
605
+ console.log(`Contiene: ${d.files.join(', ')}`);
606
+ console.log('Tokens y credenciales sustituidos por ***. Revísalo antes de compartirlo si quieres.');
607
+ if (!issue) return 0;
608
+
609
+ const auth = await new Promise<boolean>((resolve) => {
610
+ const child = spawn('gh', ['auth', 'status'], { stdio: 'ignore', shell: process.platform === 'win32' });
611
+ child.on('error', () => resolve(false));
612
+ child.on('exit', (code) => resolve(code === 0));
613
+ });
614
+ if (!auth) {
615
+ console.error(`\nPara abrir la issue hace falta gh con sesión (gh auth login). Mientras, abre una a mano en https://github.com/${ISSUE_REPO}/issues/new y adjunta el zip.`);
616
+ return 1;
617
+ }
618
+ const firstFail = report.checks.find((c) => c.status === 'fail') ?? report.checks.find((c) => c.status === 'warn');
619
+ const title = `Diagnóstico: ${firstFail ? `${firstFail.name} — ${firstFail.detail}`.slice(0, 90) : 'informe'} (bond-app ${VERSION}, ${report.platform})`;
620
+ console.log(`\n--- Se abrirá esta issue en ${ISSUE_REPO} ---\nTítulo: ${title}\n\n${d.summary}\n--- fin ---\n`);
621
+ if (!yes) {
622
+ process.stdout.write('¿La abro? [s/N] ');
623
+ const answer = await new Promise<string>((resolve) => {
624
+ process.stdin.resume();
625
+ process.stdin.once('data', (b) => { process.stdin.pause(); resolve(String(b).trim().toLowerCase()); });
626
+ });
627
+ if (!['s', 'si', 'sí', 'y', 'yes'].includes(answer)) {
628
+ console.log('No se ha abierto nada. El zip queda en', zipPath);
629
+ return 0;
630
+ }
631
+ }
632
+ const bodyFile = path.join(path.dirname(zipPath), `issue-${stamp}.md`);
633
+ fs.writeFileSync(bodyFile, d.summary, { mode: 0o600 });
634
+ const url = await new Promise<string | null>((resolve) => {
635
+ let outText = '';
636
+ const child = spawn('gh', ['issue', 'create', '-R', ISSUE_REPO, '--title', title, '--body-file', bodyFile], { stdio: ['ignore', 'pipe', 'inherit'], shell: process.platform === 'win32' });
637
+ child.stdout.on('data', (b) => { outText += String(b); });
638
+ child.on('error', () => resolve(null));
639
+ child.on('exit', (code) => resolve(code === 0 ? (/https:\/\/\S+/.exec(outText)?.[0] ?? outText.trim()) : null));
640
+ });
641
+ if (!url) {
642
+ console.error('gh no pudo abrir la issue. El zip queda en', zipPath);
643
+ return 1;
644
+ }
645
+ console.log(`\nIssue abierta: ${url}`);
646
+ console.log(`Ahora arrastra el zip a un comentario de la issue (GitHub no deja adjuntarlo por API):\n ${zipPath}`);
647
+ return 0;
648
+ }
649
+
552
650
  export async function handleDoctor(args: string[], deps?: DoctorDeps): Promise<number> {
553
651
  let port = parseInt(process.env.BOND_APP_PORT || '3000', 10);
554
652
  let host = process.env.BOND_APP_HOST || '127.0.0.1';
@@ -859,6 +957,7 @@ Commands:
859
957
  open Open herdr-app and switch to the bond layout
860
958
  status Check the status of the orchestrator and herdr-app integration
861
959
  doctor Diagnose requirements, binaries, mods, data dir, orchestrator and image
960
+ diagnose Zip logs and diagnostics (no secrets) to report a problem; --issue opens a GitHub issue
862
961
 
863
962
  Options:
864
963
  -v, --version Show version number
@@ -1057,6 +1156,8 @@ export async function runCli(argv: string[], setupDeps?: SetupDeps): Promise<num
1057
1156
  return await handleStatus(rest);
1058
1157
  case 'doctor':
1059
1158
  return await handleDoctor(rest);
1159
+ case 'diagnose':
1160
+ return await handleDiagnose(rest);
1060
1161
  default:
1061
1162
  console.error(`bond-app: unknown command '${cmd}'\n`);
1062
1163
  printHelp();
package/src/config.ts CHANGED
@@ -37,6 +37,12 @@ export interface AppConfig {
37
37
  runnerLauncher: 'bond' | 'pi';
38
38
  /** P4 criterion 3: verification failures in a row before the run goes to `blocked`. */
39
39
  maxVerifyFailures: number;
40
+ /** Issue #3 P3: how often the stuck-agent check runs (full context, exhausted budget); 0 = off. */
41
+ stuckCheckIntervalMs: number;
42
+ /** A pi agent with a full context (or a failed compaction) is relaunched with a handoff on its own; BOND_APP_AUTO_RELAUNCH=0 turns it off. */
43
+ autoRelaunchContext: boolean;
44
+ /** Ask npm at start and once a day whether bond-app or bond have a newer version; BOND_APP_UPDATE_CHECK=0 turns it off. */
45
+ updateCheck: boolean;
40
46
  /** P4: time limit of each verify command. */
41
47
  verifyTimeoutMs: number;
42
48
  /**
@@ -154,6 +160,9 @@ export function loadConfig(overrides: Partial<AppConfig> = {}): AppConfig {
154
160
  agentCommand: parseAgentCommand(process.env.BOND_APP_AGENT_COMMAND),
155
161
  runnerLauncher: process.env.RUNNER_LAUNCHER === 'pi' ? 'pi' : 'bond',
156
162
  maxVerifyFailures: Math.max(1, parseInt(process.env.BOND_APP_MAX_VERIFY_FAILURES || '3', 10) || 3),
163
+ stuckCheckIntervalMs: Math.max(0, parseInt(process.env.BOND_APP_STUCK_CHECK_MS || '60000', 10) || 0),
164
+ autoRelaunchContext: process.env.BOND_APP_AUTO_RELAUNCH !== '0',
165
+ updateCheck: process.env.BOND_APP_UPDATE_CHECK !== '0',
157
166
  verifyTimeoutMs: 10 * 60 * 1000,
158
167
  analysisCommand: parseAnalysisCommand(process.env.BOND_APP_ANALYSIS_COMMAND),
159
168
  analysisTimeoutMs: 5 * 60 * 1000,
@@ -0,0 +1,38 @@
1
+ /**
2
+ * LOOP P0 (issue #2): the options that let each agent kind work unattended in a run's
3
+ * container, which is its sandbox (runs are `runner`, never root). One table for every launch:
4
+ * single-repo runs (bare and `bond tui`), the hub leader gru, and «Relanzar con resumen». Before
5
+ * this, the hub's gru got none, and a claude, codex, copilot or agy leader stopped at its first
6
+ * permission prompt.
7
+ */
8
+ import type { SupportedAgent } from '../types.ts';
9
+
10
+ export interface UnattendedFlags {
11
+ /** Options right after the program name. */
12
+ before: string[];
13
+ /** The option that introduces the first message (agy and copilot: `-i`), or null. */
14
+ promptFlag: string | null;
15
+ }
16
+
17
+ const FLAGS: Record<SupportedAgent, UnattendedFlags> = {
18
+ pi: { before: [], promptFlag: null },
19
+ claude: { before: ['--dangerously-skip-permissions'], promptFlag: null },
20
+ // --dangerously-bypass-hook-trust: bond's agent-state hook would stop it at «Hooks need review».
21
+ codex: { before: ['--dangerously-bypass-approvals-and-sandbox', '--dangerously-bypass-hook-trust'], promptFlag: null },
22
+ agy: { before: ['--dangerously-skip-permissions'], promptFlag: '-i' },
23
+ copilot: { before: ['--yolo'], promptFlag: '-i' },
24
+ };
25
+
26
+ export function unattendedFlags(kind: SupportedAgent): UnattendedFlags {
27
+ return FLAGS[kind];
28
+ }
29
+
30
+ /**
31
+ * The argv tail for a first message: `[-i] <prompt…>` for agy and copilot, the prompt alone
32
+ * otherwise, and nothing without a prompt (a bare `-i` makes agy exit 2).
33
+ */
34
+ export function promptArgs(kind: SupportedAgent, prompt: string[]): string[] {
35
+ if (!prompt.length) return [];
36
+ const flag = FLAGS[kind].promptFlag;
37
+ return flag ? [flag, ...prompt] : [...prompt];
38
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * LOOP P0 (issue #2): one definition of «this agent waits for someone» and «this is the run's
3
+ * leader», shared by the waiting check, the team status and the nudge. These predicates were
4
+ * written out again in each of them, for hc terminals and for herdr agents.
5
+ */
6
+
7
+ /** Terminal or agent names that mean the run's leader. */
8
+ const LEADER_NAMES = new Set(['gru', 'hub leader', 'hub-leader', 'leader', 'orquestador']);
9
+
10
+ const atHubRoot = (cwd?: string) => cwd?.replace(/\/+$/, '') === '/workspace/hub';
11
+
12
+ /** An hc terminal (hc engine): waiting when blocked, or idle/done after at least one turn. */
13
+ export function isTerminalWaiting(t: { status?: string | null; turn?: number }): boolean {
14
+ if (t.status === 'blocked' || t.status === 'waiting') return true;
15
+ return (t.status === 'idle' || t.status === 'done') && (t.turn ?? 0) > 0;
16
+ }
17
+
18
+ /** A herdr agent (herdr engine): waiting when blocked, asking a question, or idle/done after one completion. */
19
+ export function isHerdrAgentWaiting(a: { agent_status?: string; completion_seq?: number | string; question?: unknown }): boolean {
20
+ if (a.agent_status === 'blocked' || a.agent_status === 'waiting') return true;
21
+ if (a.question) return true;
22
+ const seq = typeof a.completion_seq === 'number' ? a.completion_seq : Number(a.completion_seq || 0);
23
+ return (a.agent_status === 'idle' || a.agent_status === 'done') && seq > 0;
24
+ }
25
+
26
+ /** The leader among hc terminals: by name, at the hub root, or the run's first terminal. */
27
+ export function isLeaderTerminal(t: { name?: string; cwd?: string; address?: string }): boolean {
28
+ if (t.name && LEADER_NAMES.has(t.name)) return true;
29
+ if (atHubRoot(t.cwd)) return true;
30
+ return Boolean(t.address?.endsWith('/t1'));
31
+ }
32
+
33
+ /** The leader among herdr agents: by name, at the hub root, or the first pane under a generic name. */
34
+ export function isLeaderHerdrAgent(a: { name?: string; cwd?: string; pane_id?: string }): boolean {
35
+ if (a.name && LEADER_NAMES.has(a.name)) return true;
36
+ if (atHubRoot(a.cwd)) return true;
37
+ return a.pane_id === 'w1:p1' && (!a.name || a.name === 'pi' || a.name === 'agent' || a.name === 'gru');
38
+ }
@@ -5,7 +5,7 @@ import path from 'node:path';
5
5
  import crypto from 'node:crypto';
6
6
  import http from 'node:http';
7
7
  import type { AgyLoginSessionState, AgyLoginStatus } from '../types.ts';
8
- import { credentialAccount } from '../db/settings-repo.ts';
8
+ import { azureSubscriptions, credentialAccount, type AzureLoginDoc } from '../db/settings-repo.ts';
9
9
  import { restrictPathSync } from './permissions.ts';
10
10
 
11
11
  const execFileAsync = promisify(execFile);
@@ -134,13 +134,13 @@ export interface LoginContext {
134
134
  }
135
135
 
136
136
  export interface AgentLoginSpec {
137
- agent: 'agy' | 'claude' | 'codex' | 'copilot';
137
+ agent: 'agy' | 'claude' | 'codex' | 'copilot' | 'azure';
138
138
  /** What runs in the login container's tmux session. */
139
139
  command: string;
140
140
  /** Before the URL shows: answer the CLI's menus (agy picks «Google OAuth»); throws to fail. */
141
141
  onPane(pane: string, send: (keys: string, literal?: boolean) => Promise<void>, first: boolean): Promise<void>;
142
142
  /** After the code: the result once ready ({content, email}), null while waiting; throws on failure. */
143
- collect(pane: string, readTokenFile: () => Promise<string | null>): Promise<{ content: string; email?: string } | null>;
143
+ collect(pane: string, readTokenFile: () => Promise<string | null>, readFile?: (path: string) => Promise<string | null>): Promise<{ content: string; email?: string } | null>;
144
144
  /** Ms between typing the code and Enter (claude's TUI takes a paste, then the key). */
145
145
  enterDelayMs?: number;
146
146
  /** The file `collect`'s readTokenFile reads in the container (default: agy's token). */
@@ -310,6 +310,54 @@ export const COPILOT_LOGIN_SPEC: AgentLoginSpec = {
310
310
  },
311
311
  };
312
312
 
313
+ /**
314
+ * Issue #4 (P1, D1): the person's Azure session with `az login --use-device-code`. The person
315
+ * opens microsoft.com/devicelogin and types the code; az then writes ~/.azure (the profile
316
+ * with the subscriptions, and the MSAL token cache). Both files are the result (D3), with the
317
+ * default subscription. login_experience_v2 off: az never asks which subscription.
318
+ */
319
+ export const AZURE_PROFILE_PATH = '/home/runner/.azure/azureProfile.json';
320
+ export const AZURE_MSAL_PATH = '/home/runner/.azure/msal_token_cache.json';
321
+
322
+ export const AZURE_LOGIN_SPEC: AgentLoginSpec = {
323
+ agent: 'azure',
324
+ command: 'az login --use-device-code --output none',
325
+ tokenPath: AZURE_PROFILE_PATH,
326
+ device: true,
327
+ async prepare(ctx) {
328
+ await ctx.exec(['az', 'config', 'set', 'core.login_experience_v2=off', 'core.collect_telemetry=false', 'core.only_show_errors=true']);
329
+ },
330
+ async onPane(pane) {
331
+ if (/az: (command )?not found|executable file not found/i.test(pane)) {
332
+ throw new Error('az (Azure CLI) no está en la imagen del runner: reconstrúyela en Ajustes → Imagen');
333
+ }
334
+ },
335
+ extract(pane) {
336
+ const text = pane.replace(ANSI, '').replace(/\s+/g, ' ');
337
+ const m = /(https:\/\/(?:microsoft\.com\/devicelogin|login\.microsoft(?:online)?\.com\/[\w/.-]*device[\w/.-]*))\S*\s+and enter the code ([A-Z0-9]{6,12})/i.exec(text);
338
+ return m ? { url: m[1], user_code: m[2] } : null;
339
+ },
340
+ async collect(pane, readProfile, readFile) {
341
+ const text = pane.replace(ANSI, '');
342
+ if (/No subscriptions found/i.test(text)) {
343
+ throw new Error('La cuenta no tiene suscripciones de Azure en ese tenant: bond-app necesita al menos una');
344
+ }
345
+ if (/AADSTS\d+|code (has )?expired|authorization_declined|access_denied/i.test(text)) {
346
+ throw new Error('Azure no autorizó el login (código caducado o denegado): vuelve a empezar');
347
+ }
348
+ // The files are the proof: az exits once signed in and its tmux pane goes with it.
349
+ const profile = (await readProfile())?.replace(/^\uFEFF/, '') ?? null;
350
+ if (!profile || !readFile) return null;
351
+ const subs = azureSubscriptions(profile);
352
+ if (subs.length === 0) return null;
353
+ const msal = await readFile(AZURE_MSAL_PATH);
354
+ if (!msal || !/"RefreshToken"/.test(msal)) return null;
355
+ const chosen = subs.find((x) => x.default) ?? subs[0];
356
+ const doc: AzureLoginDoc = { version: 1, profile, msal, subscription_id: chosen.id };
357
+ return { content: JSON.stringify(doc), email: chosen.user || 'Azure' };
358
+ },
359
+ };
360
+
313
361
  export interface AgyLoginManagerOptions {
314
362
  driver?: AgyLoginDriver;
315
363
  runnerImage: string;
@@ -596,7 +644,11 @@ export class AgyLoginManager {
596
644
  const pane = this.spec.agent === 'agy' ? '' : await this.driver.captureTmuxPane(sessionName);
597
645
  let result: { content: string; email?: string } | null;
598
646
  try {
599
- result = await this.spec.collect(pane, () => this.driver.readContainerTokenFile(containerName, this.spec.tokenPath));
647
+ result = await this.spec.collect(
648
+ pane,
649
+ () => this.driver.readContainerTokenFile(containerName, this.spec.tokenPath),
650
+ (file) => this.driver.readContainerTokenFile(containerName, file),
651
+ );
600
652
  } catch (err: unknown) {
601
653
  await this.handleError((err as Error).message);
602
654
  return;
@@ -0,0 +1,279 @@
1
+ /**
2
+ * `bond-app diagnose`: everything needed to understand why bond-app misbehaves on a machine,
3
+ * in one zip, without secrets. Works with the orchestrator down (it reads files and runs the
4
+ * same checks as doctor). `--issue` opens a GitHub issue with the summary (gh) and leaves the
5
+ * zip for the person to attach: GitHub's API cannot attach files to an issue.
6
+ *
7
+ * Everything that goes in passes through redactSecrets: the API token, the stored credentials
8
+ * (the values the DB keeps) and the usual token shapes become `***`.
9
+ */
10
+ import fs from 'node:fs';
11
+ import os from 'node:os';
12
+ import path from 'node:path';
13
+ import zlib from 'node:zlib';
14
+ import { execFile } from 'node:child_process';
15
+ import { promisify } from 'node:util';
16
+ import { DatabaseSync } from 'node:sqlite';
17
+ import { redactSecrets } from './handoff.ts';
18
+
19
+ const execFileAsync = promisify(execFile);
20
+
21
+ export const ISSUE_REPO = 'jmanuelcorral/bond-app';
22
+ /** How much of each log goes in (its end). */
23
+ export const LOG_TAIL_BYTES = 1024 * 1024;
24
+
25
+ // --- zip (store + deflate, no dependency) ------------------------------------------------
26
+
27
+ const CRC_TABLE = (() => {
28
+ const t = new Uint32Array(256);
29
+ for (let n = 0; n < 256; n++) {
30
+ let c = n;
31
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
32
+ t[n] = c >>> 0;
33
+ }
34
+ return t;
35
+ })();
36
+
37
+ export function crc32(buf: Buffer): number {
38
+ let c = 0xffffffff;
39
+ for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8);
40
+ return (c ^ 0xffffffff) >>> 0;
41
+ }
42
+
43
+ /** A zip of text files (deflated), readable by any unzip. */
44
+ export function zipFiles(files: Array<{ name: string; content: string | Buffer }>, date = new Date()): Buffer {
45
+ const dosTime = ((date.getHours() << 11) | (date.getMinutes() << 5) | Math.floor(date.getSeconds() / 2)) & 0xffff;
46
+ const dosDate = (((date.getFullYear() - 1980) << 9) | ((date.getMonth() + 1) << 5) | date.getDate()) & 0xffff;
47
+ const locals: Buffer[] = [];
48
+ const centrals: Buffer[] = [];
49
+ let offset = 0;
50
+ for (const f of files) {
51
+ const name = Buffer.from(f.name, 'utf8');
52
+ const data = Buffer.isBuffer(f.content) ? f.content : Buffer.from(f.content, 'utf8');
53
+ const packed = zlib.deflateRawSync(data);
54
+ const crc = crc32(data);
55
+ const local = Buffer.alloc(30);
56
+ local.writeUInt32LE(0x04034b50, 0);
57
+ local.writeUInt16LE(20, 4);
58
+ local.writeUInt16LE(0x0800, 6); // UTF-8 names
59
+ local.writeUInt16LE(8, 8); // deflate
60
+ local.writeUInt16LE(dosTime, 10);
61
+ local.writeUInt16LE(dosDate, 12);
62
+ local.writeUInt32LE(crc, 14);
63
+ local.writeUInt32LE(packed.length, 18);
64
+ local.writeUInt32LE(data.length, 22);
65
+ local.writeUInt16LE(name.length, 26);
66
+ local.writeUInt16LE(0, 28);
67
+ locals.push(local, name, packed);
68
+ const central = Buffer.alloc(46);
69
+ central.writeUInt32LE(0x02014b50, 0);
70
+ central.writeUInt16LE(20, 4);
71
+ central.writeUInt16LE(20, 6);
72
+ central.writeUInt16LE(0x0800, 8);
73
+ central.writeUInt16LE(8, 10);
74
+ central.writeUInt16LE(dosTime, 12);
75
+ central.writeUInt16LE(dosDate, 14);
76
+ central.writeUInt32LE(crc, 16);
77
+ central.writeUInt32LE(packed.length, 20);
78
+ central.writeUInt32LE(data.length, 24);
79
+ central.writeUInt16LE(name.length, 28);
80
+ central.writeUInt32LE(offset, 42);
81
+ centrals.push(central, name);
82
+ offset += local.length + name.length + packed.length;
83
+ }
84
+ const centralSize = centrals.reduce((n, b) => n + b.length, 0);
85
+ const end = Buffer.alloc(22);
86
+ end.writeUInt32LE(0x06054b50, 0);
87
+ end.writeUInt16LE(files.length, 8);
88
+ end.writeUInt16LE(files.length, 10);
89
+ end.writeUInt32LE(centralSize, 12);
90
+ end.writeUInt32LE(offset, 16);
91
+ return Buffer.concat([...locals, ...centrals, end]);
92
+ }
93
+
94
+ // --- what goes in ------------------------------------------------------------------------
95
+
96
+ /** The end of a file (logs grow): at most `max` bytes, from a line start. */
97
+ export function tailFile(file: string, max = LOG_TAIL_BYTES): string | null {
98
+ try {
99
+ const size = fs.statSync(file).size;
100
+ const fd = fs.openSync(file, 'r');
101
+ try {
102
+ const len = Math.min(size, max);
103
+ const buf = Buffer.alloc(len);
104
+ fs.readSync(fd, buf, 0, len, size - len);
105
+ let text = buf.toString('utf8');
106
+ if (size > max) text = `[… ${size - max} bytes anteriores omitidos]\n${text.slice(text.indexOf('\n') + 1)}`;
107
+ return text;
108
+ } finally {
109
+ fs.closeSync(fd);
110
+ }
111
+ } catch {
112
+ return null;
113
+ }
114
+ }
115
+
116
+ /** Every value worth hiding that bond-app keeps: the API token and the stored credentials. */
117
+ export function knownSecrets(dataDir: string): string[] {
118
+ const out: string[] = [];
119
+ try {
120
+ out.push(fs.readFileSync(path.join(dataDir, 'token'), 'utf8').trim());
121
+ } catch {}
122
+ const db = path.join(dataDir, 'bond-app.sqlite');
123
+ if (!fs.existsSync(db)) return out;
124
+ try {
125
+ const conn = new DatabaseSync(db, { readOnly: true });
126
+ try {
127
+ // Every string inside, also inside JSON kept as a string (az's MSAL cache in the Azure login).
128
+ const strings = (v: unknown, acc: string[], depth = 0) => {
129
+ if (depth > 6) return;
130
+ if (typeof v === 'string') {
131
+ acc.push(v);
132
+ if (/^\s*[[{]/.test(v)) {
133
+ try {
134
+ strings(JSON.parse(v), acc, depth + 1);
135
+ } catch {}
136
+ }
137
+ } else if (v && typeof v === 'object') for (const x of Object.values(v)) strings(x, acc, depth + 1);
138
+ };
139
+ for (const table of ['agent_credentials', 'github_credential', 'azure_devops_credential', 'jira_credential']) {
140
+ let rows: Array<Record<string, unknown>> = [];
141
+ try {
142
+ rows = conn.prepare(`SELECT * FROM ${table}`).all() as Array<Record<string, unknown>>;
143
+ } catch {
144
+ continue;
145
+ }
146
+ for (const row of rows) {
147
+ for (const [k, v] of Object.entries(row)) {
148
+ if (typeof v !== 'string' || ['agent', 'provider', 'updated_at', 'created_at', 'login', 'site', 'email', 'org_url'].includes(k)) continue;
149
+ strings(v, out);
150
+ }
151
+ }
152
+ }
153
+ } finally {
154
+ conn.close();
155
+ }
156
+ } catch {}
157
+ // Only what looks like a secret (long, no spaces): not every word of a JSON config.
158
+ return [...new Set(out.map((s) => s.trim()).filter((s) => s.length >= 12 && !/\s/.test(s) && !/^https?:\/\//.test(s)))];
159
+ }
160
+
161
+ async function cmd(bin: string, args: string[]): Promise<string> {
162
+ try {
163
+ const { stdout, stderr } = await execFileAsync(bin, args, { timeout: 15_000, shell: process.platform === 'win32' });
164
+ return `${stdout}${stderr}`.trim();
165
+ } catch (err) {
166
+ const e = err as { stdout?: string; stderr?: string; message?: string };
167
+ return `(falló: ${(e.stderr || e.stdout || e.message || String(err)).trim().slice(0, 500)})`;
168
+ }
169
+ }
170
+
171
+ /** The last runs, without titles or stories (they may be private): state and why. */
172
+ export function runsSummary(dataDir: string): string {
173
+ const db = path.join(dataDir, 'bond-app.sqlite');
174
+ if (!fs.existsSync(db)) return 'sin base de datos';
175
+ try {
176
+ const conn = new DatabaseSync(db, { readOnly: true });
177
+ try {
178
+ const runs = conn.prepare(
179
+ `SELECT r.id, r.state, r.failure_reason, r.loop_state, r.created_at, r.updated_at, t.agent, t.hub_url IS NOT NULL AS hub
180
+ FROM runs r LEFT JOIN tickets t ON t.id = r.ticket_id ORDER BY r.created_at DESC LIMIT 20`
181
+ ).all();
182
+ const events = conn.prepare(
183
+ `SELECT run_id, type, created_at, substr(payload, 1, 400) AS payload FROM events ORDER BY rowid DESC LIMIT 200`
184
+ ).all();
185
+ return JSON.stringify({ runs, events }, null, 2);
186
+ } finally {
187
+ conn.close();
188
+ }
189
+ } catch (err) {
190
+ return `no se pudo leer: ${(err as Error).message}`;
191
+ }
192
+ }
193
+
194
+ export interface DiagnoseOptions {
195
+ dataDir: string;
196
+ herdrAppHome: string;
197
+ /** doctor's report as JSON (the caller runs it: it needs the same options as doctor). */
198
+ doctorJson: string;
199
+ /** The service's status and its unit/plist path. */
200
+ service?: { status: string; unitPath: string | null };
201
+ version: string;
202
+ }
203
+
204
+ export interface Diagnosis {
205
+ zip: Buffer;
206
+ files: string[];
207
+ /** The text for the issue: versions, doctor's failures and the end of the orchestrator log. */
208
+ summary: string;
209
+ }
210
+
211
+ export async function collectDiagnosis(o: DiagnoseOptions): Promise<Diagnosis> {
212
+ const secrets = knownSecrets(o.dataDir);
213
+ const clean = (s: string) => redactSecrets(s, secrets);
214
+ const files: Array<{ name: string; content: string }> = [];
215
+ const add = (name: string, content: string | null) => {
216
+ if (content !== null && content !== undefined) files.push({ name, content: clean(content) });
217
+ };
218
+
219
+ const info = [
220
+ `bond-app ${o.version}`,
221
+ `fecha ${new Date().toISOString()}`,
222
+ `sistema ${os.platform()} ${os.release()} ${os.arch()} (${os.type()})`,
223
+ `node ${process.version}`,
224
+ `bond ${await cmd('bond', ['--version'])}`,
225
+ `hc ${await cmd('hc', ['--version'])}`,
226
+ `herdr-app ${await cmd('herdr-app', ['--version'])}`,
227
+ '',
228
+ '## docker version',
229
+ await cmd('docker', ['version']),
230
+ '',
231
+ '## docker context ls',
232
+ await cmd('docker', ['context', 'ls']),
233
+ '',
234
+ '## Entorno',
235
+ `PATH=${process.env.PATH ?? ''}`,
236
+ ...Object.entries(process.env)
237
+ .filter(([k]) => /^(BOND_APP_|RUNNER_IMAGE$|DOCKER_HOST$|DOCKER_CONTEXT$|HERDR_APP_HOME$|XDG_)/.test(k) && !/TOKEN|SECRET|PASS|KEY/i.test(k))
238
+ .map(([k, v]) => `${k}=${v}`),
239
+ ].join('\n');
240
+ add('info.txt', info);
241
+ add('doctor.json', o.doctorJson);
242
+ add('orchestrator.log', tailFile(path.join(o.dataDir, 'orchestrator.log')));
243
+ add('app.log', tailFile(path.join(o.dataDir, 'app.log')));
244
+ for (const f of ['/tmp/herdr-app.log', path.join(o.herdrAppHome, 'herdr-app.log')]) add(`herdr-app/${path.basename(f)}`, tailFile(f, 512 * 1024));
245
+ if (o.service) {
246
+ add('service/status.txt', o.service.status);
247
+ if (o.service.unitPath) add(`service/${path.basename(o.service.unitPath)}`, tailFile(o.service.unitPath, 64 * 1024));
248
+ }
249
+ add('runs.json', runsSummary(o.dataDir));
250
+ const installed = path.join(o.herdrAppHome, 'installed.json');
251
+ add('herdr-app/installed.json', tailFile(installed, 64 * 1024));
252
+
253
+ let failing: string[] = [];
254
+ try {
255
+ const d = JSON.parse(o.doctorJson) as { checks?: Array<{ status: string; name: string; detail: string; fix?: string }> };
256
+ failing = (d.checks ?? []).filter((c) => c.status !== 'ok').map((c) => `- ${c.status === 'fail' ? '✗' : '!'} **${c.name}**: ${c.detail}${c.fix ? ` (arreglo: ${c.fix})` : ''}`);
257
+ } catch {}
258
+ const logTail = (tailFile(path.join(o.dataDir, 'orchestrator.log'), 8 * 1024) ?? 'sin log').split('\n').slice(-40).join('\n');
259
+ const summary = clean([
260
+ '## Entorno',
261
+ '',
262
+ '```',
263
+ info.split('\n## Entorno')[0].trim(),
264
+ '```',
265
+ '',
266
+ '## bond-app doctor',
267
+ '',
268
+ failing.length ? failing.join('\n') : 'Todo en orden.',
269
+ '',
270
+ '## Final del log del orquestador',
271
+ '',
272
+ '```',
273
+ logTail,
274
+ '```',
275
+ '',
276
+ 'El zip con los logs completos (sin secretos) va adjunto.',
277
+ ].join('\n'));
278
+ return { zip: zipFiles(files), files: files.map((f) => f.name), summary };
279
+ }