@jmanuelcorral/bond-app 0.1.6 → 0.2.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.
@@ -46,7 +46,7 @@ export function assertPushTarget(ticket: Ticket, repoUrl: string, branch: string
46
46
  */
47
47
  export function assertHubPushTarget(ticket: Ticket, allowedUrls: string[], repoUrl: string, branch: string, base: string): void {
48
48
  const allowed = new Set(allowedUrls.map(normalizeRepoUrl));
49
- if (!validateGitHubUrl(repoUrl) || !allowed.has(normalizeRepoUrl(repoUrl))) {
49
+ if (!validateRepoUrl(repoUrl) || !allowed.has(normalizeRepoUrl(repoUrl))) {
50
50
  throw new PushNotAllowedError(`Push refused: '${repoUrl}' is not a repo of this run`);
51
51
  }
52
52
  if (!validateBranchName(branch) || branch.startsWith('refs/') || branch !== ticket.target_branch) {
@@ -144,7 +144,7 @@ export const COMMIT_SCRIPT = [
144
144
  ].join('\n');
145
145
 
146
146
  /** Exit codes of PUSH_SCRIPT the orchestrator maps to a run outcome. */
147
- export const PUSH_EXIT = { mismatch: 6, nothingToDeliver: 7, workflows: 8 } as const;
147
+ export const PUSH_EXIT = { mismatch: 6, nothingToDeliver: 7, workflows: 8, nonFastForward: 9 } as const;
148
148
 
149
149
  /**
150
150
  * Runs as root with the token as the first line of stdin. Args: repo URL, branch, bundle,
@@ -185,6 +185,17 @@ export const PUSH_SCRIPT = [
185
185
  'wf=$( { git -C "$d/r.git" diff --name-only "refs/heads/_bond_base...refs/heads/$branch" -- .github/workflows;',
186
186
  ' git -C "$d/r.git" diff --name-only "refs/heads/_bond_base" "refs/heads/$branch" -- .github/workflows; } | sort -u)',
187
187
  `if [ -n "$wf" ]; then echo "runner-push: the branch changes .github/workflows: $(printf '%s' "$wf" | tr '\\n' ' ')"; exit ${'${PUSH_EXIT_WORKFLOWS}'}; fi`,
188
+ // P2 (D4): if the target branch already exists on origin, fetch it and require fast-forward (never force).
189
+ 'ls_rc=0',
190
+ 'ls_out="$(g ls-remote --exit-code --heads "$url" "refs/heads/$branch" 2>&1)" || ls_rc=$?',
191
+ 'if [ "$ls_rc" -eq 0 ]; then',
192
+ ' out="$(g fetch -q --no-tags "$url" "refs/heads/$branch:refs/heads/_bond_remote" 2>&1)" || { printf \'%s\\n\' "$out" | mask >&2; echo "runner-push: cannot fetch remote branch $branch" >&2; exit 5; }',
193
+ ' if ! git -C "$d/r.git" merge-base --is-ancestor "refs/heads/_bond_remote" "refs/heads/$branch"; then',
194
+ ` echo "runner-push: remote branch $branch advanced (not fast-forward); bundle kept at $bundle" >&2; exit ${'${PUSH_EXIT_NON_FF}'};`,
195
+ ' fi',
196
+ 'elif [ "$ls_rc" -ne 2 ]; then',
197
+ ' printf \'%s\\n\' "$ls_out" | mask >&2; echo "runner-push: cannot check remote branch $branch" >&2; exit 5;',
198
+ 'fi',
188
199
  'out="$(g push --porcelain "$url" "refs/heads/$branch:refs/heads/$branch" 2>&1)"',
189
200
  'rc=$?',
190
201
  'printf \'%s\\n\' "$out" | mask',
@@ -195,16 +206,22 @@ export const PUSH_SCRIPT = [
195
206
  .join('\n')
196
207
  .replace('${PUSH_EXIT_MISMATCH}', String(PUSH_EXIT.mismatch))
197
208
  .replace('${PUSH_EXIT_NOTHING}', String(PUSH_EXIT.nothingToDeliver))
198
- .replace('${PUSH_EXIT_WORKFLOWS}', String(PUSH_EXIT.workflows));
209
+ .replace('${PUSH_EXIT_WORKFLOWS}', String(PUSH_EXIT.workflows))
210
+ .replace('${PUSH_EXIT_NON_FF}', String(PUSH_EXIT.nonFastForward));
211
+
212
+ export type SiblingPullRequest = string | { name: string; url?: string | null };
199
213
 
200
214
  /** The pull request's body: the ticket summary, the run and its verification. */
201
- export function pullRequestBody(ticket: Ticket, run: Run, verification: string[], target?: { base: string; others: string[] }): string {
215
+ export function pullRequestBody(ticket: Ticket, run: Run, verification: string[], target?: { base: string; others: SiblingPullRequest[] }): string {
202
216
  const lines = [`## ${ticket.title}`, ''];
203
217
  if (ticket.description) lines.push(ticket.description.trim(), '');
204
218
  if (ticket.prompt) lines.push('**Encargo al agente**', '', '> ' + ticket.prompt.trim().split('\n').join('\n> '), '');
205
219
  lines.push(`- Ticket: \`${ticket.id}\``, `- Run: \`${run.id}\``, `- Agente: ${ticket.agent}${ticket.model ? ` (${ticket.model})` : ''}`);
206
220
  lines.push(`- Rama: \`${ticket.target_branch}\` → \`${target?.base ?? ticket.base_branch}\``);
207
- if (target && target.others.length > 0) lines.push(`- Mismo ticket en: ${target.others.join(', ')}`);
221
+ if (target && target.others.length > 0) {
222
+ const formatted = target.others.map((o) => (typeof o === 'string' ? o : o.url ? `[${o.name}](${o.url})` : o.name));
223
+ lines.push(`- Mismo ticket en: ${formatted.join(', ')}`);
224
+ }
208
225
  if (verification.length > 0) {
209
226
  lines.push('', '**Verificación**', '', ...verification.map((v) => `- ${v}`));
210
227
  } else {
@@ -219,3 +236,103 @@ export function tail(text: string, lines = 20, maxChars = 2000): string {
219
236
  const t = text.trim().split('\n').slice(-lines).join('\n');
220
237
  return t.length > maxChars ? t.slice(-maxChars) : t;
221
238
  }
239
+
240
+ /**
241
+ * Decision 2026-11-25 (git en el run): runs inside the container as `runner` (node), with a
242
+ * JSON object on stdin — { name, email, branch, repos: [{dir, base}], creds: [{host, token}] }.
243
+ * Sets the person's identity and push defaults, writes each host's token to
244
+ * ~/.config/bond-app/git-credentials.d/<host> (0600) behind a credential helper, and a
245
+ * global pre-push hook that only lets the run's branch through (fast-forward, no deletion,
246
+ * nothing under .github/workflows). Tokens only travel on stdin. Plain JS on purpose: it is
247
+ * serialised with toString() and run with `node -e`.
248
+ */
249
+ function gitSetupInContainer() {
250
+ const fs = require('fs');
251
+ const path = require('path');
252
+ const execFileSync = require('child_process').execFileSync;
253
+ const cfg = JSON.parse(fs.readFileSync(0, 'utf8'));
254
+ const home = process.env.HOME || '/home/runner';
255
+ const dir = path.join(home, '.config', 'bond-app');
256
+ const credDir = path.join(dir, 'git-credentials.d');
257
+ const hookDir = path.join(dir, 'git-hooks');
258
+ for (const d of [dir, credDir, hookDir]) fs.mkdirSync(d, { recursive: true, mode: 0o700 });
259
+ const git = (...a: string[]) => execFileSync('git', a, { stdio: ['ignore', 'ignore', 'inherit'] });
260
+ git('config', '--global', 'user.name', String(cfg.name));
261
+ git('config', '--global', 'user.email', String(cfg.email));
262
+ git('config', '--global', 'push.default', 'current');
263
+ git('config', '--global', 'push.autoSetupRemote', 'true');
264
+ git('config', '--global', 'core.hooksPath', hookDir);
265
+ fs.writeFileSync(path.join(dir, 'git-push-branch'), String(cfg.branch) + '\n', { mode: 0o600 });
266
+ for (const r of cfg.repos || []) {
267
+ try { git('-C', String(r.dir), 'config', 'bondapp.base', String(r.base)); } catch (e) { /* not a checkout yet */ }
268
+ }
269
+ const helper = path.join(dir, 'git-credential');
270
+ fs.writeFileSync(helper, [
271
+ '#!/bin/sh',
272
+ '# bond-app: the run token of each host (0600 files written by bond-app).',
273
+ '[ "$1" = get ] || exit 0',
274
+ 'host=',
275
+ 'while IFS= read -r line; do [ -z "$line" ] && break; case "$line" in host=*) host=${line#host=};; esac; done',
276
+ 'case "$host" in ""|*[!A-Za-z0-9.-]*) exit 0;; esac',
277
+ 'f="$HOME/.config/bond-app/git-credentials.d/$host"',
278
+ '[ -r "$f" ] || exit 0',
279
+ 'user=bond-app; [ "$host" = github.com ] && user=x-access-token',
280
+ 'printf "username=%s\\npassword=%s\\n" "$user" "$(cat "$f")"',
281
+ ''].join('\n'), { mode: 0o700 });
282
+ for (const f of fs.readdirSync(credDir)) fs.rmSync(path.join(credDir, f), { force: true });
283
+ for (const c of cfg.creds || []) {
284
+ if (!/^[A-Za-z0-9.-]+$/.test(String(c.host))) continue;
285
+ fs.writeFileSync(path.join(credDir, String(c.host)), String(c.token), { mode: 0o600 });
286
+ }
287
+ if ((cfg.creds || []).length) {
288
+ try { git('config', '--global', '--unset-all', 'credential.helper'); } catch (e) { /* none set */ }
289
+ git('config', '--global', 'credential.helper', '!' + helper);
290
+ }
291
+ fs.writeFileSync(path.join(hookDir, 'pre-push'), [
292
+ '#!/bin/sh',
293
+ '# bond-app: a push from the run only updates the run branch, fast-forward, and never',
294
+ '# touches .github/workflows (the same barriers as the delivery).',
295
+ 'branch=$(cat "$HOME/.config/bond-app/git-push-branch" 2>/dev/null)',
296
+ 'zero=0000000000000000000000000000000000000000',
297
+ 'base=$(git config bondapp.base 2>/dev/null || true)',
298
+ 'while read -r lref lsha rref rsha; do',
299
+ ' [ -n "$rref" ] || continue',
300
+ ' if [ "$rref" != "refs/heads/$branch" ]; then echo "bond-app: desde el run solo se hace push de su rama ($branch), no de $rref" >&2; exit 1; fi',
301
+ ' if [ "$lsha" = "$zero" ]; then echo "bond-app: la rama del run no se borra" >&2; exit 1; fi',
302
+ ' from=',
303
+ ' if [ "$rsha" != "$zero" ]; then',
304
+ ' if ! git cat-file -e "$rsha^{commit}" 2>/dev/null; then echo "bond-app: la rama remota tiene commits que no tienes; haz git fetch y unelos antes del push" >&2; exit 1; fi',
305
+ ' if ! git merge-base --is-ancestor "$rsha" "$lsha"; then echo "bond-app: push que no es fast-forward rechazado (desde el run no se fuerza)" >&2; exit 1; fi',
306
+ ' from=$rsha',
307
+ ' elif [ -n "$base" ]; then',
308
+ ' from=$(git merge-base "$lsha" "origin/$base" 2>/dev/null || true)',
309
+ ' fi',
310
+ ' if [ -n "$from" ] && [ -n "$(git diff --name-only "$from" "$lsha" -- .github/workflows)" ]; then echo "bond-app: el push cambia .github/workflows; eso no sale de un run" >&2; exit 1; fi',
311
+ 'done',
312
+ 'exit 0',
313
+ ''].join('\n'), { mode: 0o700 });
314
+ }
315
+
316
+ /** The command that runs gitSetupInContainer (its config on stdin). */
317
+ export const GIT_SETUP_COMMAND = ['sh', '-c', 'set -eu; umask 077; exec node -e "$1"', 'bond-git-setup', `(${gitSetupInContainer.toString()})()`];
318
+
319
+ /**
320
+ * Decision 2026-11-25 (bond sync en el run): in /workspace/repo, if it is a bond repo with a
321
+ * clean tree, run `bond sync` and commit whatever it rewrote as `chore: bond sync (bond X)`
322
+ * (the person's identity is already configured). Prints `committed` and `message=...` when
323
+ * it made a commit, `clean` when there was nothing to sync, `skipped` otherwise.
324
+ */
325
+ export const BOND_SYNC_COMMIT_SCRIPT = [
326
+ 'set -eu',
327
+ 'cd /workspace/repo',
328
+ 'command -v bond >/dev/null 2>&1 && [ -f .bond/bond.toml ] || { echo skipped; exit 0; }',
329
+ '[ -z "$(git status --porcelain)" ] || { echo skipped; exit 0; }',
330
+ 'bond sync </dev/null >/dev/null',
331
+ '[ -n "$(git status --porcelain)" ] || { echo clean; exit 0; }',
332
+ "v=$(bond --version 2>/dev/null | head -n1 | tr -d '\\r')",
333
+ 'msg="chore: bond sync (bond ${v:-?})"',
334
+ 'git add -A',
335
+ 'git commit -q -m "$msg"',
336
+ 'echo committed',
337
+ "printf 'message=%s\\n' \"$msg\"",
338
+ ].join('\n');