@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.
@@ -13,6 +13,7 @@ import { checkHttpHealth } from '../cli.ts';
13
13
  import { getServiceStatus, type ServiceDeps } from './service.ts';
14
14
  import { defaultDataDir, defaultHerdrAppHome } from './paths.ts';
15
15
  import { checkIcaclsOutput, currentWindowsUsername } from './permissions.ts';
16
+ import type { AzureLoginSummary } from '../types.ts';
16
17
 
17
18
  const execFileAsync = promisify(execFile);
18
19
  const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
@@ -57,6 +58,8 @@ export interface DoctorDeps {
57
58
  runCommand?: (cmd: string, args: string[], timeoutMs?: number) => Promise<CommandOutput>;
58
59
  checkHealth?: (host: string, port: number, timeoutMs?: number) => Promise<{ ok: boolean; statusCode?: number; data?: unknown }>;
59
60
  fetchSetupState?: (host: string, port: number, token: string, timeoutMs?: number) => Promise<SetupStateSummary | null>;
61
+ /** Issue #4: the Azure session as the orchestrator sees it (GET /api/v1/settings/azure-login). */
62
+ fetchAzureLogin?: (host: string, port: number, token: string, timeoutMs?: number) => Promise<AzureLoginSummary | null>;
60
63
  checkApp?: (home: string) => AppIntegrationCheckResult;
61
64
  getFreeSpaceBytes?: (targetPath: string) => number | null;
62
65
  nodeVersion?: string;
@@ -126,18 +129,27 @@ async function defaultRunCommand(cmd: string, args: string[], timeoutMs = 10_000
126
129
  }
127
130
  }
128
131
 
129
- function defaultFetchSetupState(
132
+ function defaultFetchSetupState(host: string, port: number, token: string, timeoutMs = 1500): Promise<SetupStateSummary | null> {
133
+ return fetchApiJson<SetupStateSummary>(host, port, token, '/api/v1/setup', timeoutMs);
134
+ }
135
+
136
+ function defaultFetchAzureLogin(host: string, port: number, token: string, timeoutMs = 1500): Promise<AzureLoginSummary | null> {
137
+ return fetchApiJson<AzureLoginSummary>(host, port, token, '/api/v1/settings/azure-login', timeoutMs);
138
+ }
139
+
140
+ function fetchApiJson<T>(
130
141
  host: string,
131
142
  port: number,
132
143
  token: string,
144
+ apiPath: string,
133
145
  timeoutMs = 1500
134
- ): Promise<SetupStateSummary | null> {
146
+ ): Promise<T | null> {
135
147
  return new Promise((resolve) => {
136
148
  const req = http.get(
137
149
  {
138
150
  host,
139
151
  port,
140
- path: '/api/v1/setup',
152
+ path: apiPath,
141
153
  headers: {
142
154
  Host: `${host}:${port}`,
143
155
  Authorization: `Bearer ${token}`,
@@ -153,7 +165,7 @@ function defaultFetchSetupState(
153
165
  res.on('end', () => {
154
166
  if (res.statusCode === 200) {
155
167
  try {
156
- resolve(JSON.parse(body) as SetupStateSummary);
168
+ resolve(JSON.parse(body) as T);
157
169
  } catch {
158
170
  resolve(null);
159
171
  }
@@ -206,6 +218,7 @@ export async function runDoctor(options: DoctorOptions = {}): Promise<DoctorRepo
206
218
  const runCommand = deps.runCommand ?? defaultRunCommand;
207
219
  const checkHealth = deps.checkHealth ?? checkHttpHealth;
208
220
  const fetchSetupState = deps.fetchSetupState ?? defaultFetchSetupState;
221
+ const fetchAzureLogin = deps.fetchAzureLogin ?? defaultFetchAzureLogin;
209
222
  const checkApp = deps.checkApp ?? checkAppInstalled;
210
223
  const getFreeSpaceBytes = deps.getFreeSpaceBytes ?? defaultGetFreeSpaceBytes;
211
224
  const platform = normalizePlatform(deps.platform ?? process.platform);
@@ -633,15 +646,15 @@ export async function runDoctor(options: DoctorOptions = {}): Promise<DoctorRepo
633
646
 
634
647
  // 10. Runner image
635
648
  let liveSetup: SetupStateSummary | null = null;
636
- if (!explicitImage && healthOk) {
637
- let apiToken = process.env.BOND_APP_AUTH_TOKEN || '';
638
- if (!apiToken && fs.existsSync(tokenPath)) {
639
- try {
640
- apiToken = fs.readFileSync(tokenPath, 'utf8').trim();
641
- } catch {
642
- apiToken = '';
643
- }
649
+ let apiToken = process.env.BOND_APP_AUTH_TOKEN || '';
650
+ if (!apiToken && healthOk && fs.existsSync(tokenPath)) {
651
+ try {
652
+ apiToken = fs.readFileSync(tokenPath, 'utf8').trim();
653
+ } catch {
654
+ apiToken = '';
644
655
  }
656
+ }
657
+ if (!explicitImage && healthOk) {
645
658
  if (apiToken) {
646
659
  try {
647
660
  liveSetup = await fetchSetupState(host, port, apiToken, 1500);
@@ -742,6 +755,17 @@ export async function runDoctor(options: DoctorOptions = {}): Promise<DoctorRepo
742
755
  }
743
756
  }
744
757
 
758
+ // Issue #4: the Azure session for the runs (optional: only tickets with «Login de Azure» use it).
759
+ if (healthOk && apiToken) {
760
+ let az: AzureLoginSummary | null = null;
761
+ try {
762
+ az = await fetchAzureLogin(host, port, apiToken, 1500);
763
+ } catch {
764
+ az = null;
765
+ }
766
+ if (az) checks.push(azureLoginCheck(az));
767
+ }
768
+
745
769
  const summary = {
746
770
  ok: checks.filter((c) => c.status === 'ok').length,
747
771
  warn: checks.filter((c) => c.status === 'warn').length,
@@ -755,3 +779,25 @@ export async function runDoctor(options: DoctorOptions = {}): Promise<DoctorRepo
755
779
  summary,
756
780
  };
757
781
  }
782
+
783
+ /** Issue #4: the Azure session line of doctor: who, which subscription, and until when. */
784
+ export function azureLoginCheck(az: AzureLoginSummary, now = Date.now()): DoctorCheck {
785
+ const fix = 'Inicia sesión en Ajustes → Azure → «Iniciar sesión en Azure»';
786
+ if (!az.configured) {
787
+ return { id: 'azure-login', name: 'Azure login', status: 'ok', essential: false, detail: 'sin sesión (opcional: solo la usan los tickets con «Login de Azure»)', meta: { configured: false } };
788
+ }
789
+ const sub = az.subscription ? `${az.subscription.name} (${az.subscription.id})` : 'sin suscripción';
790
+ const ends = az.expires_at ? Date.parse(az.expires_at) : NaN;
791
+ const days = Number.isFinite(ends) ? Math.floor((ends - now) / 86_400_000) : null;
792
+ const expired = az.expired || (days !== null && days < 0);
793
+ const soon = !expired && days !== null && days < 14;
794
+ return {
795
+ id: 'azure-login',
796
+ name: 'Azure login',
797
+ status: expired || soon || !az.subscription ? 'warn' : 'ok',
798
+ essential: false,
799
+ detail: `${az.user || 'cuenta desconocida'} · ${sub} · ${expired ? 'caducada' : days === null ? 'caducidad desconocida' : `caduca en ~${days} días`}`,
800
+ fix: expired || soon || !az.subscription ? fix : undefined,
801
+ meta: { configured: true, user: az.user, subscription: az.subscription ?? null, expires_at: az.expires_at ?? null },
802
+ };
803
+ }
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Issue #3 («Relanzar con resumen») P1: the handoff a relaunched agent starts from.
3
+ *
4
+ * Everything comes from outside the stuck agent: its session files (`bond summary`, and pi's
5
+ * last compaction summary), git, and the decisions recorded in the run. Nothing is asked of the
6
+ * agent, and nothing is written into its window. A Claude that hit its usage limit, or a pi with
7
+ * a full context, can still be replaced. No LLM, and no secrets: the text is redacted before it
8
+ * is written or shown.
9
+ */
10
+
11
+ /** Sections the gather script prints, in order, each after an `@@<name>` line. */
12
+ export const GATHER_SECTIONS = ['summary', 'branch', 'base', 'log', 'status', 'diffstat', 'compaction', 'decisions'] as const;
13
+ export type GatherSection = (typeof GATHER_SECTIONS)[number];
14
+
15
+ /**
16
+ * Runs in the container as runner: `sh -c <script> bond-handoff <cwd> <kind> <base>`. Every
17
+ * part is best effort (an older bond without `summary`, a cwd that is not a repo…) and capped,
18
+ * so the handoff never grows without bound.
19
+ */
20
+ export const HANDOFF_GATHER_SCRIPT = [
21
+ 'cd "$1" 2>/dev/null || exit 3',
22
+ 'k="$2"; base="$3"',
23
+ 'echo "@@summary"',
24
+ 'if command -v bond >/dev/null 2>&1 && bond summary --help >/dev/null 2>&1; then bond summary "$k" -n 8 </dev/null 2>/dev/null | head -c 12000; fi',
25
+ 'echo; echo "@@branch"; git rev-parse --abbrev-ref HEAD 2>/dev/null',
26
+ 'b=$(git config bondapp.base 2>/dev/null || true); [ -n "$b" ] || b="$base"',
27
+ 'ref=""; for r in "origin/$b" "$b"; do if [ -n "$b" ] && git rev-parse --verify -q "$r" >/dev/null 2>&1; then ref="$r"; break; fi; done',
28
+ 'echo "@@base"; echo "$ref"',
29
+ 'echo "@@log"; [ -n "$ref" ] && git log --oneline "$ref"..HEAD 2>/dev/null | head -40',
30
+ 'echo "@@status"; git status --short 2>/dev/null | head -60',
31
+ 'echo "@@diffstat"; git diff --stat HEAD 2>/dev/null | tail -40',
32
+ 'echo "@@compaction"',
33
+ // pi keeps its sessions in ~/.pi/agent/sessions/--<cwd with / as ->--/; the last compaction
34
+ // entry of the newest one is the summary pi itself made (when compaction still worked).
35
+ `[ "$k" = pi ] && node -e 'const fs=require("fs"),p=require("path");const d=p.join(process.env.HOME||"/home/runner",".pi/agent/sessions","--"+process.argv[1].replace(/^\\//,"").replace(/\\//g,"-")+"--");let f;try{f=fs.readdirSync(d).filter(x=>x.endsWith(".jsonl")).map(x=>p.join(d,x)).sort((a,b)=>fs.statSync(b).mtimeMs-fs.statSync(a).mtimeMs)[0]}catch{}if(f){let s="";for(const l of fs.readFileSync(f,"utf8").split("\\n")){try{const e=JSON.parse(l);if(e.type==="compaction"&&typeof e.summary==="string")s=e.summary}catch{}}process.stdout.write(s.slice(0,8000))}' "$1" 2>/dev/null`,
36
+ 'echo; echo "@@decisions"; if command -v bond >/dev/null 2>&1; then bond decisions --json </dev/null 2>/dev/null | head -c 40000; fi',
37
+ 'exit 0',
38
+ ].join('\n');
39
+
40
+ /** The gather output split by section (missing sections are ''). */
41
+ export function parseGather(output: string): Record<GatherSection, string> {
42
+ const out = Object.fromEntries(GATHER_SECTIONS.map((s) => [s, ''])) as Record<GatherSection, string>;
43
+ let current: GatherSection | null = null;
44
+ const buf: string[] = [];
45
+ const flush = () => {
46
+ // Only blank lines and the end are trimmed: `git status --short` lines start with a space.
47
+ if (current) out[current] = buf.join('\n').replace(/^(\s*\n)+/, '').trimEnd();
48
+ buf.length = 0;
49
+ };
50
+ for (const line of output.split('\n')) {
51
+ const m = /^@@([a-z]+)$/.exec(line.trim());
52
+ if (m && (GATHER_SECTIONS as readonly string[]).includes(m[1])) {
53
+ flush();
54
+ current = m[1] as GatherSection;
55
+ } else if (current) buf.push(line);
56
+ }
57
+ flush();
58
+ return out;
59
+ }
60
+
61
+ export interface HandoffDecision {
62
+ id: string;
63
+ title: string;
64
+ status: string;
65
+ }
66
+
67
+ /** The run's decisions taken by `agentName` (`decided_by` ends in `/<name>`) since `since`. */
68
+ export function decisionsBy(decisionsJson: string, agentName: string, since: string | null): HandoffDecision[] {
69
+ let parsed: unknown;
70
+ try {
71
+ parsed = JSON.parse(decisionsJson);
72
+ } catch {
73
+ return [];
74
+ }
75
+ const list = Array.isArray(parsed) ? parsed : Array.isArray((parsed as { decisions?: unknown })?.decisions) ? (parsed as { decisions: unknown[] }).decisions : [];
76
+ const day = since ? since.slice(0, 10) : '';
77
+ const out: HandoffDecision[] = [];
78
+ for (const d of list as Array<Record<string, unknown>>) {
79
+ const by = String(d.decided_by ?? '');
80
+ const date = String(d.date ?? '');
81
+ if (!by.endsWith(`/${agentName}`)) continue;
82
+ if (day && date && date < day) continue;
83
+ out.push({ id: String(d.id ?? ''), title: String(d.title ?? ''), status: String(d.status ?? '') });
84
+ }
85
+ return out.slice(0, 30);
86
+ }
87
+
88
+ /** Token shapes that must never reach a handoff, whatever printed them. */
89
+ const TOKEN_PATTERNS: RegExp[] = [
90
+ /\bgh[pousr]_[A-Za-z0-9]{20,}\b/g,
91
+ /\bgithub_pat_[A-Za-z0-9_]{20,}\b/g,
92
+ /\bglpat-[A-Za-z0-9_-]{20,}\b/g,
93
+ /\bsk-[A-Za-z0-9_-]{16,}\b/g,
94
+ /\bxox[abposr]-[A-Za-z0-9-]{10,}\b/g,
95
+ /\bAKIA[0-9A-Z]{16}\b/g,
96
+ /\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{16,}/g,
97
+ /(https?:\/\/)[^\s/@:]+:[^\s/@]+@/g,
98
+ ];
99
+
100
+ /** Replaces the run's known secrets and common token shapes with `***`. */
101
+ export function redactSecrets(text: string, secrets: Array<string | null | undefined>): string {
102
+ let out = text;
103
+ for (const s of secrets) {
104
+ if (s && s.length >= 8) out = out.split(s).join('***');
105
+ }
106
+ for (const re of TOKEN_PATTERNS) {
107
+ out = out.replace(re, (m, p1) => (typeof p1 === 'string' && p1.startsWith('http') ? `${p1}***@` : '***'));
108
+ }
109
+ return out;
110
+ }
111
+
112
+ export interface HandoffInput {
113
+ ticketTitle: string;
114
+ task: string;
115
+ agentName: string;
116
+ fromKind: string;
117
+ toKind: string;
118
+ reason: string;
119
+ cwd: string;
120
+ /** The hub leader, when the relaunched agent is a team member. */
121
+ leader?: string | null;
122
+ gather: Record<GatherSection, string>;
123
+ decisions: HandoffDecision[];
124
+ }
125
+
126
+ /** Headings of embedded text two levels down, so they nest under the handoff's own `##`. */
127
+ const demote = (s: string) => s.replace(/^(#{1,4})(?=\s)/gm, '##$1');
128
+
129
+ const fence = (s: string) => '```\n' + s.replace(/```/g, '``​`') + '\n```';
130
+
131
+ /** The handoff as Markdown (sections with nothing in them are left out). */
132
+ export function buildHandoff(input: HandoffInput): string {
133
+ const g = input.gather;
134
+ const parts: string[] = [];
135
+ parts.push(`# Traspaso: retomas el trabajo de ${input.agentName}`);
136
+ parts.push(
137
+ [
138
+ `Otro agente (${input.fromKind}) trabajaba en este run como **${input.agentName}** y se ha relanzado con ${input.toKind}.`,
139
+ `Motivo: ${input.reason}.`,
140
+ `Carpeta: \`${input.cwd}\`.`,
141
+ input.leader ? `Eres un miembro del equipo; el líder del hub es **${input.leader}**: pregúntale a él.` : null,
142
+ 'Su último paso pudo quedar a medias (el corte pudo llegar en mitad de una herramienta): revisa el estado de git de abajo antes de seguir, y no repitas lo que ya está commiteado.',
143
+ ]
144
+ .filter(Boolean)
145
+ .join('\n'),
146
+ );
147
+ parts.push(`## La tarea del ticket\n\n**${input.ticketTitle}**\n\n${input.task.trim().slice(0, 6000)}`);
148
+ if (g.compaction) parts.push(`## Último resumen de su sesión (compactación de pi)\n\n${demote(g.compaction)}`);
149
+ if (g.summary) parts.push(`## Lo último de su sesión (bond summary)\n\n${demote(g.summary)}`);
150
+ const git: string[] = [];
151
+ if (g.branch) git.push(`Rama: \`${g.branch}\`${g.base ? ` (base \`${g.base}\`)` : ''}`);
152
+ if (g.log) git.push(`Commits sobre la base:\n${fence(g.log)}`);
153
+ git.push(g.status ? `Cambios sin commitear:\n${fence(g.status)}` : 'Sin cambios sin commitear.');
154
+ if (g.diffstat) git.push(`Diff sin commitear (resumen):\n${fence(g.diffstat)}`);
155
+ parts.push(`## Estado de git\n\n${git.join('\n\n')}`);
156
+ if (input.decisions.length) {
157
+ parts.push(`## Decisiones que registró en el run\n\n${input.decisions.map((d) => `- \`${d.id}\` (${d.status}): ${d.title}`).join('\n')}`);
158
+ }
159
+ parts.push('## Qué hacer ahora\n\nLee lo anterior, comprueba el estado real del repo y continúa la tarea desde donde se quedó. Si algo no cuadra, pregunta.');
160
+ return `${parts.join('\n\n')}\n`;
161
+ }
@@ -26,6 +26,7 @@ import {
26
26
  } from './hub.ts';
27
27
  import { isValidAgent, validateBranchName, type HubAnalysisRepo, type HubFix, type Ticket } from '../types.ts';
28
28
  import { validateRepoUrl } from './repo-host.ts';
29
+ import { unattendedFlags } from './agent-flags.ts';
29
30
 
30
31
  export type TokenForRepo = string | ((url: string) => string | null | undefined);
31
32
 
@@ -665,7 +666,7 @@ export class HubSession {
665
666
  if (!MODEL_RE.test(effectiveModel)) throw new HubMountError(`Invalid model '${effectiveModel}'`);
666
667
  modelArg = `--model ${shq(effectiveModel)} `;
667
668
  }
668
- const runCmd = `cd ${HUB_DIR} && export BOND_TEAM_NO_TABLE=1 && exec ${agentCmd} ${modelArg}"$(cat ${promptPath})"`;
669
+ const runCmd = `cd ${HUB_DIR} && export BOND_TEAM_NO_TABLE=1 && exec ${leaderInvocation(agentCmd, modelArg, promptPath)}`;
669
670
  const runRes = await this.runner(['herdr', 'pane', 'run', pane, runCmd], 15_000);
670
671
  if (runRes.exitCode !== 0) throw new HubMountError(`herdr pane run failed: ${firstLine(runRes.stderr || runRes.stdout)}`);
671
672
 
@@ -802,13 +803,24 @@ export class HubSession {
802
803
  }
803
804
  // Its own tab (no herdr.tab label: t1 is the bond-init shell's), named gru like the
804
805
  // main agent of a single-repo run, and signing its decisions as <kind>/gru (bond 1.16.8).
805
- const leaderShellCmd = `cd ${HUB_DIR} && export BOND_TEAM_ENGINE=hc BOND_TEAM_NO_TABLE=1 BOND_AGENT=${shq(`${agentCmd}/gru`)} && exec ${agentCmd} ${modelArg}"$(cat ${promptPath})"`;
806
+ const leaderShellCmd = `cd ${HUB_DIR} && export BOND_TEAM_ENGINE=hc BOND_TEAM_NO_TABLE=1 BOND_AGENT=${shq(`${agentCmd}/gru`)} && exec ${leaderInvocation(agentCmd, modelArg, promptPath)}`;
806
807
  const terminal = await hc.startTerminal(machine, ['sh', '-c', leaderShellCmd], HUB_DIR, 'gru');
807
808
  opts.onTerminal?.(terminal);
808
809
  return terminal;
809
810
  }
810
811
  }
811
812
 
813
+ /**
814
+ * LOOP P0: the hub leader's command line, unattended like every other launch (agent-flags.ts):
815
+ * `<agent> <its options> [--model m] [-i] "$(cat <prompt file>)"`.
816
+ */
817
+ export function leaderInvocation(agentCmd: string, modelArg: string, promptPath: string): string {
818
+ const flags = isValidAgent(agentCmd) ? unattendedFlags(agentCmd) : { before: [], promptFlag: null };
819
+ const before = flags.before.map((f) => `${f} `).join('');
820
+ const promptFlag = flags.promptFlag ? `${flags.promptFlag} ` : '';
821
+ return `${agentCmd} ${before}${modelArg}${promptFlag}"$(cat ${promptPath})"`;
822
+ }
823
+
812
824
  /** The hub name for a created hub: the ticket id, safe for paths. */
813
825
  export function hubNameFor(ticket: Ticket): string {
814
826
  return `hub-${ticket.id}`.replace(/[^A-Za-z0-9_.-]/g, '-').slice(0, 64);
package/src/core/hub.ts CHANGED
@@ -268,7 +268,7 @@ export function analysisPrompt(ticket: Ticket, hub: HubToml, instructions?: stri
268
268
  'Di qué repos nombra o necesita la historia y no están en el hub. No inventes repos: solo los que la historia o los docs nombran.',
269
269
  'Pon "ready": false sin repos que falten solo si sin otra cosa del hub la historia NO se puede hacer (di cuál en "summary"). Que falten un plan, docs o secciones de AGENTS.md por rellenar no impide empezar: eso es "ready": true.',
270
270
  'Termina con UNA línea que sea solo un objeto JSON, sin nada más en esa línea:',
271
- '{"ready": true|false, "missing": [{"name": "<repo>", "url": "https://github.com/<owner>/<repo>.git o null", "why": "<motivo corto>"}], "summary": "<una frase>"}',
271
+ '{"ready": true|false, "missing": [{"name": "<repo>", "url": "<url git del repo: https://github.com/<owner>/<repo>.git o https://dev.azure.com/<org>/<proyecto>/_git/<repo>> o null", "why": "<motivo corto>"}], "summary": "<una frase>"}',
272
272
  ].join('\n');
273
273
  }
274
274
 
@@ -364,7 +364,7 @@ export function agentGaps(answer: AgentAnswer, hub: HubToml, startId: number): H
364
364
  const urls = new Set(hub.repos.map((r) => (r.url ?? '').toLowerCase().replace(/\.git$/, '')));
365
365
  let n = startId;
366
366
  for (const m of answer.missing) {
367
- let url = m.url && validateGitHubUrl(m.url) ? m.url : null;
367
+ let url = m.url && validateRepoUrl(m.url) ? m.url : null;
368
368
  let name = m.name;
369
369
  if (url) {
370
370
  try {
@@ -381,7 +381,7 @@ export function agentGaps(answer: AgentAnswer, hub: HubToml, startId: number): H
381
381
  repo: name,
382
382
  message: url
383
383
  ? `La historia necesita '${name}' y no está en el hub (${m.why || 'sin motivo'}). Propuesta: bond hub add ${url}`
384
- : `La historia necesita '${name}' y no está en el hub (${m.why || 'sin motivo'}); falta su url de GitHub`,
384
+ : `La historia necesita '${name}' y no está en el hub (${m.why || 'sin motivo'}); falta su url`,
385
385
  fix: url ? { action: 'hub_add', name, url, base_branch: 'main' } : null,
386
386
  });
387
387
  }
@@ -0,0 +1,241 @@
1
+ /**
2
+ * LOOP P3 (issue #2): the loop engine's pure parts. bond-app owns the loop's clock: it counts
3
+ * iterations, applies the limits and can pause or stop it. gru (skill loop-lead, in bond) owns
4
+ * the judgement. They talk through the run's `bond-app` command (the same FIFO channel as
5
+ * `bond-app pr`):
6
+ *
7
+ * - a member asks gru: `bond-app ask "<q>"`, which reaches gru's terminal as
8
+ * `[bond-app ask #<n> de <agent>] …`; gru answers with `bond-app answer <n> "<text>"`;
9
+ * - gru closes a review round with `bond-app loop next --progress yes|no "<summary>"`, asks the
10
+ * person with `bond-app loop needs-human "<why>"`, and ends with
11
+ * `bond-app loop finish --result pass|fail --report <path>`.
12
+ *
13
+ * Decisions: D1 (bond-app holds the clock), D2 (an iteration is one review round of gru), D3
14
+ * (questions through bond-app ask), D5 (pass delivers, fail waits), D6 (start from the run),
15
+ * D7 (hub only); the environment variables instead of an AGENTS.md block (bond#91).
16
+ */
17
+
18
+ export type LoopState = 'running' | 'paused' | 'finishing' | 'finished' | 'stopped';
19
+
20
+ /** Where gru keeps the loop log (in the hub), by default. */
21
+ export const loopLogPath = (runId: string) => `docs/loops/${runId}.md`;
22
+
23
+ /** The file the agents' environment loads (via agent-env.sh) while the loop runs. */
24
+ export const LOOP_ENV_FILE = '/home/runner/.config/bond-app/loop.env';
25
+
26
+ /**
27
+ * The loop's environment: BOND_LOOP=1 for every agent of the run, and the role from BOND_AGENT
28
+ * (`<kind>/gru` is the leader, the rest members). Loaded by every agent shell through
29
+ * agent-env.sh, so agents already running see it from their next command on.
30
+ */
31
+ export function loopEnv(runId: string): string {
32
+ return [
33
+ '# bond-app LOOP (issue #2): written when the loop starts, removed when it ends.',
34
+ 'export BOND_LOOP=1',
35
+ 'case "${BOND_AGENT:-}" in */gru) export BOND_LOOP_ROLE=lead ;; *) export BOND_LOOP_ROLE=member ;; esac',
36
+ `export BOND_LOOP_LOG='${loopLogPath(runId)}'`,
37
+ '',
38
+ ].join('\n');
39
+ }
40
+
41
+ /**
42
+ * As runner: write loop.env (on stdin) and make agent-env.sh load it (once). An agent-env.sh
43
+ * from before the loop existed gets the line appended.
44
+ */
45
+ export const LOOP_ENV_ON_COMMAND = [
46
+ 'sh', '-c',
47
+ [
48
+ 'set -eu; umask 077',
49
+ 'd=/home/runner/.config/bond-app; mkdir -p "$d"',
50
+ 'cat > "$d/loop.env"',
51
+ 'line=\'[ -r /home/runner/.config/bond-app/loop.env ] && . /home/runner/.config/bond-app/loop.env\'',
52
+ 'touch "$d/agent-env.sh"',
53
+ 'grep -qF "$line" "$d/agent-env.sh" || printf \'%s\\n\' "$line" >> "$d/agent-env.sh"',
54
+ ].join('\n'),
55
+ ];
56
+
57
+ /** As runner: the loop is over; agents stop seeing BOND_LOOP from their next command. */
58
+ export const LOOP_ENV_OFF_COMMAND = ['sh', '-c', 'rm -f /home/runner/.config/bond-app/loop.env'];
59
+
60
+ /**
61
+ * As runner, in the hub: make the loop skills available to the run's agents. They come with
62
+ * bond (catalog, bond#91) and are copied from its runtime into the hub's `.agents/skills`,
63
+ * linked from `.claude/skills` when that folder exists. A skill the hub already tracks in git
64
+ * is the hub's own: left as it is. What bond-app adds goes to the clone's .git/info/exclude,
65
+ * so it never ends up in the hub's commits or PR. Exit 4 when the image's bond does not carry
66
+ * them (older than the loop).
67
+ */
68
+ export const LOOP_SKILLS_SCRIPT = [
69
+ 'set -eu',
70
+ 'cd "$1"',
71
+ 'bond --version >/dev/null 2>&1 || true',
72
+ 'exclude=$(git rev-parse --git-path info/exclude 2>/dev/null || true)',
73
+ 'ignore() { [ -n "$exclude" ] || return 0; mkdir -p "$(dirname "$exclude")"; touch "$exclude"; grep -qxF "$1" "$exclude" || printf \'%s\\n\' "$1" >> "$exclude"; }',
74
+ 'for s in loop-lead loop-member; do',
75
+ ' src=$(ls -d "$HOME"/.bond/runtime/*/catalog/skills/"$s" 2>/dev/null | sort -V | tail -1)',
76
+ ' [ -n "$src" ] || { echo "missing $s" >&2; exit 4; }',
77
+ ' if [ -n "$(git ls-files -- ".agents/skills/$s" 2>/dev/null)" ]; then echo "hub $s"; continue; fi',
78
+ ' mkdir -p .agents/skills',
79
+ ' rm -rf ".agents/skills/$s" && cp -R "$src" ".agents/skills/$s"',
80
+ ' ignore "/.agents/skills/$s/"',
81
+ ' if [ -d .claude/skills ] && [ ! -e ".claude/skills/$s" ]; then ln -s "../../.agents/skills/$s" ".claude/skills/$s"; ignore "/.claude/skills/$s"; fi',
82
+ 'done',
83
+ 'echo ok',
84
+ ].join('\n');
85
+
86
+ export interface LoopRound {
87
+ iteration: number;
88
+ stalls: number;
89
+ action: 'continue' | 'finish' | 'stall';
90
+ }
91
+
92
+ /**
93
+ * gru closed a review round: count it, and count the rounds in a row without progress. At the
94
+ * stall limit the loop stops (a person is needed); at the maximum, gru is told to finish with
95
+ * its evaluation. `max` null = no limit.
96
+ */
97
+ export function nextRound(cur: { iteration: number; stalls: number }, progress: boolean, max: number | null, stallLimit: number): LoopRound {
98
+ const iteration = cur.iteration + 1;
99
+ const stalls = progress ? 0 : cur.stalls + 1;
100
+ if (stalls >= stallLimit) return { iteration, stalls, action: 'stall' };
101
+ if (max !== null && iteration >= max) return { iteration, stalls, action: 'finish' };
102
+ return { iteration, stalls, action: 'continue' };
103
+ }
104
+
105
+ /** A plan gru can carry out: a Markdown file right under the hub's docs/plans/. */
106
+ export const PLAN_PATH_RE = /^docs\/plans\/[A-Za-z0-9][A-Za-z0-9._-]{0,150}\.md$/;
107
+
108
+ /** The person's free text in one line (it is typed into gru's terminal). */
109
+ const oneLine = (text: string) => text.replace(/\s+/g, ' ').trim();
110
+
111
+ /** Instructions inline in the start message, at most; the full text is in the loop log. */
112
+ export const LOOP_INLINE_MAX = 1200;
113
+
114
+ /** The first message to gru when the loop starts (one line: it is typed into its terminal). */
115
+ export function loopStartMessage(runId: string, max: number | null, plan = '', instructions = ''): string {
116
+ const limit = max === null ? 'sin límite de iteraciones' : `máximo ${max} iteraciones`;
117
+ const log = loopLogPath(runId);
118
+ const what = plan ? `el plan ${plan}` : 'el plan de la historia del ticket (si no está en docs/plans/, escríbelo ahí primero con plan-create)';
119
+ const base = `[bond-app loop] Arranca el modo loop (${limit}). Usa la skill loop-lead: ejecuta ${what} con el equipo, una vuelta de revisión por iteración; registro del loop en ${log}; cierra cada vuelta con bond-app loop next --progress yes|no "<resumen>" y termina con bond-app loop finish.`;
120
+ const text = oneLine(instructions);
121
+ if (!text) return base;
122
+ const inline = text.length > LOOP_INLINE_MAX ? `${text.slice(0, LOOP_INLINE_MAX)}… (sigue en el registro)` : text;
123
+ return `${base} Instrucciones de la persona para este loop (están al principio de ${log}; reléelas en cada vuelta y cúmplelas): ${inline}`;
124
+ }
125
+
126
+ /** A message from the person while the loop runs, as it reaches gru (one line). */
127
+ export function loopMessageText(runId: string, text: string): string {
128
+ return `[bond-app loop] Nueva instrucción de la persona (queda en ${loopLogPath(runId)}; tenla en cuenta desde ahora y en las vueltas siguientes): ${oneLine(text)}`;
129
+ }
130
+
131
+ /** The block bond-app writes at the top of the loop log when the loop starts. */
132
+ export function loopLogStart(at: string, plan: string, max: number | null, instructions: string): string {
133
+ const text = instructions.trim();
134
+ return [
135
+ `## Inicio del loop (${at})`,
136
+ '',
137
+ plan ? `- Plan: \`${plan}\`` : '- Plan: el de la historia del ticket (sin fichero en docs/plans/ al empezar)',
138
+ `- Iteraciones: ${max === null ? 'sin límite' : `máximo ${max}`}`,
139
+ '',
140
+ '### Instrucciones de la persona',
141
+ '',
142
+ text || '(ninguna: sigue el plan tal cual)',
143
+ '',
144
+ ].join('\n');
145
+ }
146
+
147
+ /** A message of the person, appended to the loop log. */
148
+ export function loopLogMessage(at: string, text: string): string {
149
+ return ['', `## Instrucción de la persona (${at})`, '', text.trim(), ''].join('\n');
150
+ }
151
+
152
+ /**
153
+ * As runner: append stdin to the loop log in the hub ($1 hub dir, $2 log path, $3 run id),
154
+ * with a title when the file is new.
155
+ */
156
+ export const LOOP_LOG_APPEND_SCRIPT = [
157
+ 'set -eu',
158
+ 'cd "$1"',
159
+ 'mkdir -p "$(dirname "$2")"',
160
+ 'if [ -s "$2" ]; then printf \'\\n\' >> "$2"; else printf \'# Registro del loop %s\\n\\n\' "$3" > "$2"; fi',
161
+ 'cat >> "$2"',
162
+ ].join('\n');
163
+
164
+ /** As runner, in the hub ($1): the plans gru can carry out, one path per line. */
165
+ export const LOOP_PLANS_SCRIPT = 'cd "$1" && for f in docs/plans/*.md; do [ -f "$f" ] && printf \'%s\\n\' "$f"; done; true';
166
+
167
+ /** The plans, newest first (their names start with the date). */
168
+ export function sortPlans(lines: string): string[] {
169
+ return [...new Set(lines.split('\n').map((l) => l.trim()).filter((l) => PLAN_PATH_RE.test(l)))].sort().reverse();
170
+ }
171
+
172
+ /** A member's question as it reaches gru (one line). */
173
+ export function askMessage(n: number, agent: string, question: string): string {
174
+ const q = question.replace(/\s+/g, ' ').trim();
175
+ return `[bond-app ask #${n} de ${agent}] ${q} (contesta con: bond-app answer ${n} "<tu respuesta>")`;
176
+ }
177
+
178
+ /** Texts going through the FIFO stay under PIPE_BUF once encoded (one atomic line). */
179
+ export const LOOP_TEXT_MAX = 2000;
180
+
181
+ /**
182
+ * The in-container CLI for `bond-app ask|answer|loop` (node, installed next to the `bond-app`
183
+ * shell script, which hands these commands to it). It writes one line
184
+ * `<token> <reqId> <base64 json>` to the run's FIFO and waits for
185
+ * /var/run/bond-app/pr-<reqId>.json.
186
+ */
187
+ export const BOND_APP_LOOP_CLI = String.raw`#!/usr/bin/env node
188
+ // bond-app loop CLI (issue #2): ask, answer and loop, through the run's FIFO channel.
189
+ const fs = require('fs');
190
+ const crypto = require('crypto');
191
+ const MAX = ${LOOP_TEXT_MAX};
192
+ const [cmd, ...args] = process.argv.slice(2);
193
+ const die = (m, code = 1) => { process.stderr.write('bond-app: ' + m + '\n'); process.exit(code); };
194
+ const usage = 'uso: bond-app ask "<pregunta>" | bond-app answer <n> "<respuesta>" | bond-app loop next --progress yes|no "<resumen>" | bond-app loop needs-human "<motivo>" | bond-app loop finish --result pass|fail --report <ruta> | bond-app loop status';
195
+ const text = (s) => { const t = String(s || '').trim(); if (!t) die(usage); return t.slice(0, MAX); };
196
+ const opt = (name) => { const i = args.indexOf(name); return i >= 0 ? args[i + 1] : undefined; };
197
+ const rest = () => args.filter((a, i) => !a.startsWith('--') && !(i > 0 && args[i - 1].startsWith('--'))).slice(1).join(' ');
198
+ let req;
199
+ if (cmd === 'ask') req = { cmd: 'ask', agent: process.env.BOND_AGENT || 'agente', question: text(args.join(' ')) };
200
+ else if (cmd === 'answer') {
201
+ const n = Number(args[0]);
202
+ if (!Number.isInteger(n) || n < 1) die(usage);
203
+ req = { cmd: 'answer', n, text: text(args.slice(1).join(' ')) };
204
+ } else if (cmd === 'loop') {
205
+ const sub = args[0];
206
+ if (sub === 'next') {
207
+ const p = opt('--progress');
208
+ if (p !== 'yes' && p !== 'no') die(usage);
209
+ req = { cmd: 'loop-next', progress: p === 'yes', summary: text(rest()) };
210
+ } else if (sub === 'needs-human') req = { cmd: 'loop-needs-human', why: text(args.slice(1).join(' ')) };
211
+ else if (sub === 'finish') {
212
+ const r = opt('--result');
213
+ if (r !== 'pass' && r !== 'fail') die(usage);
214
+ req = { cmd: 'loop-finish', result: r, report: String(opt('--report') || '').slice(0, 300) };
215
+ } else if (sub === 'status') req = { cmd: 'loop-status' };
216
+ else die(usage);
217
+ } else die(usage);
218
+ req.agent = req.agent || process.env.BOND_AGENT || '';
219
+ const dir = process.env.BOND_APP_RUN_DIR || '/var/run/bond-app';
220
+ const env = dir + '/pr.env', fifo = dir + '/pr.fifo';
221
+ let token = '';
222
+ try { token = (/BOND_APP_PR_TOKEN=([a-f0-9]+)/.exec(fs.readFileSync(env, 'utf8')) || [])[1] || ''; } catch {}
223
+ if (!token) die('canal de bond-app no configurado (' + env + ')');
224
+ if (!fs.existsSync(fifo)) die('canal de bond-app no disponible (' + fifo + ')');
225
+ const id = Date.now() + '-' + process.pid + '-' + crypto.randomBytes(4).toString('hex');
226
+ const res = dir + '/pr-' + id + '.json';
227
+ fs.writeFileSync(fifo, token + ' ' + id + ' ' + Buffer.from(JSON.stringify(req)).toString('base64') + '\n');
228
+ const limit = Date.now() + (cmd === 'ask' ? Number(process.env.BOND_APP_ASK_TIMEOUT_S || 3600) : 120) * 1000;
229
+ const tick = () => {
230
+ if (fs.existsSync(res)) {
231
+ let out = {};
232
+ try { out = JSON.parse(fs.readFileSync(res, 'utf8')); } catch {}
233
+ try { fs.unlinkSync(res); } catch {}
234
+ if (out.message) process.stdout.write(out.message + '\n');
235
+ process.exit(out.ok ? 0 : 1);
236
+ }
237
+ if (Date.now() > limit) die(cmd === 'ask' ? 'gru no ha contestado a tiempo: sigue con lo que puedas y cuéntalo en tu informe' : 'bond-app no responde');
238
+ setTimeout(tick, 1000);
239
+ };
240
+ tick();
241
+ `;