duckhunt-runner 0.4.1 → 0.7.0

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.
Files changed (45) hide show
  1. package/README.md +63 -9
  2. package/dist/access-token.d.ts +15 -0
  3. package/dist/access-token.d.ts.map +1 -0
  4. package/dist/access-token.js +40 -0
  5. package/dist/access-token.js.map +1 -0
  6. package/dist/claim.d.ts +16 -0
  7. package/dist/claim.d.ts.map +1 -1
  8. package/dist/claim.js +112 -10
  9. package/dist/claim.js.map +1 -1
  10. package/dist/claude-args.d.ts +1 -0
  11. package/dist/claude-args.d.ts.map +1 -1
  12. package/dist/claude-args.js +4 -2
  13. package/dist/claude-args.js.map +1 -1
  14. package/dist/config.d.ts +3 -0
  15. package/dist/config.d.ts.map +1 -1
  16. package/dist/config.js +7 -0
  17. package/dist/config.js.map +1 -1
  18. package/dist/conversation-gc.d.ts +3 -2
  19. package/dist/conversation-gc.d.ts.map +1 -1
  20. package/dist/conversation-gc.js +8 -5
  21. package/dist/conversation-gc.js.map +1 -1
  22. package/dist/daemon.d.ts +10 -5
  23. package/dist/daemon.d.ts.map +1 -1
  24. package/dist/daemon.js +157 -100
  25. package/dist/daemon.js.map +1 -1
  26. package/dist/keyed-mutex.d.ts +10 -0
  27. package/dist/keyed-mutex.d.ts.map +1 -0
  28. package/dist/keyed-mutex.js +36 -0
  29. package/dist/keyed-mutex.js.map +1 -0
  30. package/dist/run-lease.d.ts +21 -0
  31. package/dist/run-lease.d.ts.map +1 -0
  32. package/dist/run-lease.js +58 -0
  33. package/dist/run-lease.js.map +1 -0
  34. package/dist/status.d.ts.map +1 -1
  35. package/dist/status.js +2 -1
  36. package/dist/status.js.map +1 -1
  37. package/dist/user-permissions.d.ts +5 -0
  38. package/dist/user-permissions.d.ts.map +1 -0
  39. package/dist/user-permissions.js +40 -0
  40. package/dist/user-permissions.js.map +1 -0
  41. package/dist/worktree.d.ts +5 -0
  42. package/dist/worktree.d.ts.map +1 -1
  43. package/dist/worktree.js +30 -1
  44. package/dist/worktree.js.map +1 -1
  45. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"conversation-gc.js","sourceRoot":"","sources":["../src/conversation-gc.ts"],"names":[],"mappings":"AAAA,kGAAkG;AAClG,+EAA+E;AAC/E,qFAAqF;AACrF,oFAAoF;AACpF,oGAAoG;AACpG,kGAAkG;AAClG,gEAAgE;AAEhE,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,4BAA4B,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAElI,yFAAyF;AACzF,+CAA+C;AAC/C,MAAM,CAAC,MAAM,wBAAwB,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,MAAM,CAAC;AAC7D,uDAAuD;AACvD,MAAM,CAAC,MAAM,2BAA2B,GAAG,EAAE,GAAG,MAAM,CAAC;AACvD,2EAA2E;AAC3E,MAAM,CAAC,MAAM,uBAAuB,GAAG,GAAG,CAAC;AAU3C,MAAM,YAAY,GAAG,OAAO,CAAC;AAE7B,SAAS,WAAW,CAAC,QAAgB,EAAE,IAAY;IACjD,MAAM,IAAI,GAAG,IAAI,CAAC,UAAU,CAAC,4BAA4B,CAAC,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,mBAAmB,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC;IAClI,IAAI,CAAC,IAAI;QAAE,OAAO,IAAI,CAAC;IACvB,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,KAAK,cAAc,CAAC,CAAC,CAAC,4BAA4B,CAAC,MAAM,CAAC,CAAC,CAAC,mBAAmB,CAAC,MAAM,CAAC,CAAC;IACtH,MAAM,KAAK,GAAG,YAAY,CAAC,IAAI,CAAC,MAAM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I,SAAS;YACX,CAAC;YACD,MAAM,mBAAmB,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;YAClD,OAAO,EAAE,CAAC;QACZ,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,OAAO,CAAC,KAAK,CAAC,2CAA2C,IAAI,KAAM,GAAa,CAAC,OAAO,EAAE,CAAC,CAAC;QAC9F,CAAC;IACH,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC"}
package/dist/daemon.d.ts CHANGED
@@ -5,28 +5,33 @@ export interface DaemonOptions {
5
5
  export declare class RunnerDaemon {
6
6
  private readonly cfg;
7
7
  private readonly opts;
8
- private access;
8
+ private readonly auth;
9
9
  private claude;
10
10
  private hasAws;
11
- private active;
12
- private killActive;
11
+ private readonly leases;
12
+ private readonly slots;
13
+ private readonly gitLocks;
14
+ private readonly cwdLocks;
13
15
  private stopping;
14
16
  private exitCode;
15
17
  private wake;
16
18
  private lastGcAt;
17
19
  constructor(cfg: RunnerConfig, opts?: DaemonOptions);
18
- private accessToken;
19
20
  private api;
20
21
  private label;
21
22
  private capabilities;
22
- /** loop principal: gc → claim → ejecutar → repetir, hasta SIGINT/SIGTERM. devuelve el exit code. */
23
+ /** loop principal: gc → claim → ejecutar en un slot libre → repetir, hasta SIGINT/SIGTERM.
24
+ * devuelve el exit code tras esperar el cierre de los runs en vuelo. */
23
25
  run(): Promise<number>;
24
26
  private idle;
25
27
  private installSignalHandlers;
26
28
  private claim;
29
+ private start;
27
30
  private openConversations;
28
31
  private collectWorktrees;
29
32
  private prepareWorkdir;
33
+ private holdCwd;
34
+ private startHeartbeat;
30
35
  private envFor;
31
36
  private executeRun;
32
37
  private runAttempts;
@@ -1 +1 @@
1
- {"version":3,"file":"daemon.d.ts","sourceRoot":"","sources":["../src/daemon.ts"],"names":[],"mappings":"AA0BA,OAAO,EAAwC,KAAK,YAAY,EAAE,MAAM,aAAa,CAAC;AA8DtF,MAA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AAO,CAAC,MAAM,CAAS;IAGvB,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAuB;IAC9C,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAS;IAE/B,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAoB;IAC7C,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAoB;IAC7C,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,QAAQ,CAAK;IACrB,OAAO,CAAC,IAAI,CAA6B;IACzC,OAAO,CAAC,QAAQ,CAAK;gBAGF,GAAG,EAAE,YAAY,EACjB,IAAI,GAAE,aAAkB;YAO7B,GAAG;IAkBjB,OAAO,CAAC,KAAK;IAMb,OAAO,CAAC,YAAY;IAUpB;6EACyE;IACnE,GAAG,IAAI,OAAO,CAAC,MAAM,CAAC;IA+B5B,OAAO,CAAC,IAAI;IAgBZ,OAAO,CAAC,qBAAqB;YAoBf,KAAK;IAyCnB,OAAO,CAAC,KAAK;YAgBC,iBAAiB;YAmBjB,gBAAgB;YAuBhB,cAAc;YA4Bd,OAAO;IAerB,OAAO,CAAC,cAAc;IAuBtB,OAAO,CAAC,MAAM;YAgBA,UAAU;YAuEV,WAAW;IA0CzB,OAAO,CAAC,WAAW;YAmGL,UAAU;YAMV,UAAU;CAmBzB"}
package/dist/daemon.js CHANGED
@@ -1,14 +1,24 @@
1
1
  // loop del daemon (contrato 42 + prompts libres t#378): reclama runs por poll, lanza `claude -p`
2
2
  // headless en un worktree del checkout del repo (o en el scratch dir si no hay repo) con el mcp de
3
- // duckhunt adjunto y el perfil de tools del claim, sube el feed de progreso y reporta el cierre. un
4
- // run a la vez: el cómputo es la máquina del usuario. el server nunca ve paths ni perfiles — el mapa
5
- // repo→checkout y cuenta→perfil vive en la config local.
3
+ // duckhunt adjunto y el perfil de tools del claim, sube el feed de progreso y reporta el cierre.
4
+ // hasta `defaults.maxConcurrent` runs a la vez (slots, default 1): el cómputo es la máquina del
5
+ // usuario. el server nunca ve paths ni perfiles — el mapa repo→checkout y cuenta→perfil vive en la
6
+ // config local.
6
7
  // decisiones:
7
8
  // - claude corre en su PROPIO grupo de procesos (detached): cancelar, el timeout o parar el daemon
8
9
  // matan también lo que lanzó la tool Bash (tests, servidores). por eso el daemon instala sus
9
10
  // handlers de SIGINT/SIGTERM: ctrl-c ya no le llega al hijo por la terminal.
10
11
  // - kind=prompt usa un worktree POR CONVERSACIÓN que sobrevive entre segmentos (worktree.ts); lo
11
- // recoge conversation-gc.ts entre runs. los runs de reglas siguen con su worktree efímero.
12
+ // recoge conversation-gc.ts en el loop de claim. los runs de reglas siguen con su worktree efímero.
13
+ // si el usuario abrió la conversación en el checkout (run.isolation, 0.6.0), corre en el checkout
14
+ // tal cual, sin worktree, y se turna con los demás runs de ese checkout (cwdLocks).
15
+ // - runs en paralelo (r#105): el server ya reclama atómicamente y una conversación es UNA fila, así
16
+ // que nunca corre dos veces a la vez. lo compartido en la máquina se serializa aquí: git sobre un
17
+ // mismo checkout (gitLocks: preparar, borrar, gc) y el cwd de los runs no aislados (cwdLocks:
18
+ // checkout con `worktree: false`, scratch en perfil edit). el latido arranca en el claim
19
+ // (run-lease.ts), así un run que espera turno sigue vivo para el server.
20
+ // - el worktree de un run se toca (touch / borrado) ANTES de reportar el status: el server puede
21
+ // re-encolar la misma fila al recibirlo y otro slot la reclamaría sobre el worktree que se borra.
12
22
  // - el feed (event-uploader.ts) se vacía ANTES de reportar el status: el server rechaza eventos de
13
23
  // un run cerrado.
14
24
  // - el segmento del claim viaja en heartbeat/progress/events/status: es lo que distingue a ESTE
@@ -23,21 +33,23 @@ import path from 'node:path';
23
33
  import readline from 'node:readline';
24
34
  import { promisify } from 'node:util';
25
35
  import { refreshAccess } from './oauth.js';
26
- import { logsDir, scratchDir } from './config.js';
36
+ import { AccessTokenSource } from './access-token.js';
37
+ import { concurrency, logsDir, scratchDir } from './config.js';
27
38
  import { consumeStreamLine, detectClaude, newStreamState } from './claude.js';
28
39
  import { buildClaudeArgs, PROMPT_REQUIRED_FLAGS } from './claude-args.js';
29
- import { claimRunId, EVENTS_DEFAULTS, parseClaim, RUN_KIND, RUNNER_CAPABILITY } from './claim.js';
40
+ import { userBashDeny } from './user-permissions.js';
41
+ import { claimRunId, EVENTS_DEFAULTS, parseClaim, PROMPT_PROFILE, RUN_ISOLATION, RUN_KIND, RUNNER_CAPABILITY } from './claim.js';
30
42
  import { EventUploader } from './event-uploader.js';
31
43
  import { clip, feedEventsFromStream, systemEvent } from './feed.js';
32
44
  import { scrubEnv } from './scrub-env.js';
33
45
  import { clampReport, reportFor } from './status-report.js';
34
- import { prepareConversationWorktree, prepareRunWorktree, removeRunWorktree, touchWorktree } from './worktree.js';
46
+ import { prepareCheckout, prepareConversationWorktree, prepareRunWorktree, removeRunWorktree, touchWorktree } from './worktree.js';
35
47
  import { chunk, CONVERSATION_GC_INTERVAL_MS, listWorktreeCandidates, removeWorktrees, selectForRemoval } from './conversation-gc.js';
48
+ import { KeyedMutex } from './keyed-mutex.js';
49
+ import { RunLease, signalGroup } from './run-lease.js';
36
50
  import { runnerVersion } from './version.js';
37
51
  const execFileP = promisify(execFile);
38
52
  const CLAIM_POLL_MS = 5_000;
39
- // margen para refrescar el access token del daemon antes de que caduque.
40
- const TOKEN_REFRESH_MARGIN_MS = 5 * 60_000;
41
53
  // SIGTERM → SIGKILL (al grupo) si el proceso no muere en este margen.
42
54
  const KILL_GRACE_MS = 10_000;
43
55
  // tras la salida de claude, espera máxima a que se cierren sus pipes: un proceso en background que
@@ -71,28 +83,19 @@ const HTTP_TOO_MANY = 429;
71
83
  const HTTP_SERVER_ERROR = 500;
72
84
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
73
85
  const isTransient = (status) => status === HTTP_TIMEOUT || status === HTTP_TOO_MANY || status >= HTTP_SERVER_ERROR;
74
- // señal a todo el grupo de procesos del hijo (spawn detached → pgid = pid del hijo).
75
- function signalGroup(child, signal) {
76
- if (child.pid === undefined)
77
- return;
78
- try {
79
- process.kill(-child.pid, signal);
80
- }
81
- catch (err) {
82
- // ESRCH: el grupo ya no existe. cualquier otro fallo: al menos al hijo directo.
83
- if (err.code !== 'ESRCH')
84
- child.kill(signal);
85
- }
86
- }
87
86
  export class RunnerDaemon {
88
87
  cfg;
89
88
  opts;
90
- access = null;
89
+ auth;
91
90
  claude = { version: null, supported: new Set() };
92
91
  hasAws = false;
93
- // hijo en curso (un run a la vez) y su kill con motivo.
94
- active = null;
95
- killActive = null;
92
+ // runs en vuelo, uno por slot ocupado. por objeto y no por id: la misma fila re-encolada puede
93
+ // reclamarse mientras el segmento anterior aún cierra.
94
+ leases = new Set();
95
+ slots;
96
+ // git sobre un mismo checkout (clave: path resuelto del checkout) y cwd compartidos (clave: cwd).
97
+ gitLocks = new KeyedMutex();
98
+ cwdLocks = new KeyedMutex();
96
99
  stopping = false;
97
100
  exitCode = 0;
98
101
  wake = null;
@@ -100,29 +103,26 @@ export class RunnerDaemon {
100
103
  constructor(cfg, opts = {}) {
101
104
  this.cfg = cfg;
102
105
  this.opts = opts;
103
- }
104
- async accessToken() {
105
- if (!this.access || this.access.expiresAt - Date.now() < TOKEN_REFRESH_MARGIN_MS) {
106
- this.access = await refreshAccess(this.cfg);
107
- }
108
- return this.access.token;
106
+ this.auth = new AccessTokenSource(() => refreshAccess(cfg));
107
+ this.slots = concurrency(cfg.defaults);
109
108
  }
110
109
  // fetch autenticado contra /api/runner con timeout y un reintento tras refresh en 401.
111
110
  async api(pathname, body) {
112
- const call = async () => fetch(`${this.cfg.baseUrl}/api/runner${pathname}`, {
111
+ const call = async (token) => fetch(`${this.cfg.baseUrl}/api/runner${pathname}`, {
113
112
  method: 'POST',
114
113
  headers: {
115
- Authorization: `Bearer ${await this.accessToken()}`,
114
+ Authorization: `Bearer ${token}`,
116
115
  'Content-Type': 'application/json',
117
116
  },
118
117
  body: body === undefined ? '{}' : JSON.stringify(body),
119
118
  signal: AbortSignal.timeout(API_TIMEOUT_MS),
120
119
  });
121
- const first = await call();
120
+ const token = await this.auth.token();
121
+ const first = await call(token);
122
122
  if (first.status !== 401)
123
123
  return first;
124
- this.access = null;
125
- return call();
124
+ this.auth.invalidate(token);
125
+ return call(await this.auth.token());
126
126
  }
127
127
  label() {
128
128
  return this.cfg.label ?? os.hostname();
@@ -132,11 +132,14 @@ export class RunnerDaemon {
132
132
  capabilities() {
133
133
  return [
134
134
  ...(this.hasAws ? [RUNNER_CAPABILITY.aws] : []),
135
- ...(PROMPT_REQUIRED_FLAGS.every((f) => this.claude.supported.has(f)) ? [RUNNER_CAPABILITY.prompt] : []),
135
+ // read_shell va con prompt: los dos exigen poder cumplir el perfil read (parseClaim lo valida).
136
+ ...(PROMPT_REQUIRED_FLAGS.every((f) => this.claude.supported.has(f)) ? [RUNNER_CAPABILITY.prompt, RUNNER_CAPABILITY.readShell] : []),
136
137
  RUNNER_CAPABILITY.events,
138
+ RUNNER_CAPABILITY.checkout,
137
139
  ];
138
140
  }
139
- /** loop principal: gc → claim → ejecutar → repetir, hasta SIGINT/SIGTERM. devuelve el exit code. */
141
+ /** loop principal: gc → claim → ejecutar en un slot libre → repetir, hasta SIGINT/SIGTERM.
142
+ * devuelve el exit code tras esperar el cierre de los runs en vuelo. */
140
143
  async run() {
141
144
  this.claude = await detectClaude();
142
145
  if (!this.claude.version) {
@@ -144,19 +147,23 @@ export class RunnerDaemon {
144
147
  }
145
148
  this.hasAws = await execFileP('aws', ['--version']).then(() => true, () => false);
146
149
  this.installSignalHandlers();
147
- console.log(`[runner] duckhunt-runner ${runnerVersion() ?? '?'} · ${this.label()} → ${this.cfg.baseUrl} (claude ${this.claude.version}, aws cli ${this.hasAws ? 'sí' : 'no'}, ${Object.keys(this.cfg.repos).length} repos, ${Object.keys(this.cfg.aws).length} cuentas aws, capacidades ${this.capabilities().join(',')}, poll ${CLAIM_POLL_MS / 1000}s)`);
150
+ console.log(`[runner] duckhunt-runner ${runnerVersion() ?? '?'} · ${this.label()} → ${this.cfg.baseUrl} (claude ${this.claude.version}, aws cli ${this.hasAws ? 'sí' : 'no'}, ${Object.keys(this.cfg.repos).length} repos, ${Object.keys(this.cfg.aws).length} cuentas aws, capacidades ${this.capabilities().join(',')}, ${this.slots} slot${this.slots === 1 ? '' : 's'}, poll ${CLAIM_POLL_MS / 1000}s)`);
148
151
  while (!this.stopping) {
152
+ // slots llenos: el cierre de un run despierta el loop (o el siguiente poll).
153
+ if (this.leases.size >= this.slots) {
154
+ await this.idle(CLAIM_POLL_MS);
155
+ continue;
156
+ }
149
157
  await this.collectWorktrees();
150
158
  const claim = this.stopping ? null : await this.claim();
151
- if (claim) {
152
- await this.executeRun(claim).catch((err) => {
153
- console.error(`[runner] run ${claim.run.id} reventó: ${err.message}`);
154
- });
155
- }
156
- else if (!this.stopping) {
159
+ if (claim)
160
+ this.start(claim);
161
+ else if (!this.stopping)
157
162
  await this.idle(CLAIM_POLL_MS);
158
- }
159
163
  }
164
+ // parada: cada run en vuelo recibió kill('shutdown'); se espera a que reporte su cierre.
165
+ while (this.leases.size > 0)
166
+ await this.idle(CLAIM_POLL_MS);
160
167
  console.log('[runner] detenido');
161
168
  return this.exitCode;
162
169
  }
@@ -174,21 +181,20 @@ export class RunnerDaemon {
174
181
  };
175
182
  });
176
183
  }
177
- // primera señal: parar tras cerrar el run en curso (se mata su grupo y se reporta); segunda
178
- // señal o margen agotado: salida inmediata matando el grupo.
184
+ // primera señal: parar tras cerrar los runs en curso (se mata cada grupo y se reporta); segunda
185
+ // señal o margen agotado: salida inmediata matando todos los grupos.
179
186
  installSignalHandlers() {
180
187
  const onSignal = (signal, code) => {
181
188
  const forceExit = () => {
182
- if (this.active)
183
- signalGroup(this.active, 'SIGKILL');
189
+ this.leases.forEach((lease) => lease.forceKill());
184
190
  process.exit(code);
185
191
  };
186
192
  if (this.stopping)
187
193
  forceExit();
188
194
  this.stopping = true;
189
195
  this.exitCode = code;
190
- console.log(`[runner] ${signal}: deteniendo${this.killActive ? ' el run en curso' : ''} (otra señal fuerza la salida)`);
191
- this.killActive?.('shutdown');
196
+ console.log(`[runner] ${signal}: deteniendo${this.leases.size > 0 ? ` ${this.leases.size} run(s) en curso` : ''} (otra señal fuerza la salida)`);
197
+ this.leases.forEach((lease) => lease.kill('shutdown'));
192
198
  this.wake?.();
193
199
  setTimeout(forceExit, SHUTDOWN_GRACE_MS).unref();
194
200
  };
@@ -204,6 +210,7 @@ export class RunnerDaemon {
204
210
  repos: Object.keys(this.cfg.repos),
205
211
  awsAccounts: Object.keys(this.cfg.aws),
206
212
  capabilities: this.capabilities(),
213
+ slots: this.slots,
207
214
  ...(runnerVersion() ? { version: runnerVersion() } : {}),
208
215
  ...(this.claude.version ? { claudeVersion: this.claude.version.slice(0, CLAUDE_VERSION_MAX_CHARS) } : {}),
209
216
  });
@@ -237,7 +244,21 @@ export class RunnerDaemon {
237
244
  return null;
238
245
  }
239
246
  }
240
- // --- gc de worktrees (entre runs, throttled) ---
247
+ // registra el run en su slot y lo ejecuta en segundo plano; al terminar libera el slot y despierta
248
+ // el loop para reclamar el siguiente sin esperar al poll.
249
+ start(claim) {
250
+ const lease = new RunLease(claim.run.id);
251
+ this.leases.add(lease);
252
+ if (this.stopping)
253
+ lease.kill('shutdown');
254
+ void this.executeRun(claim, lease)
255
+ .catch((err) => console.error(`[runner] run ${lease.runId} reventó: ${err.message}`))
256
+ .finally(() => {
257
+ this.leases.delete(lease);
258
+ this.wake?.();
259
+ });
260
+ }
261
+ // --- gc de worktrees (en el loop de claim, throttled) ---
241
262
  // conversaciones abiertas según el server. si no contesta (o es anterior a t#378), todas se dan
242
263
  // por abiertas: entonces solo actúa el ttl de inactividad, que nunca pierde trabajo.
243
264
  async openConversations(runIds) {
@@ -268,10 +289,13 @@ export class RunnerDaemon {
268
289
  if (candidates.length === 0)
269
290
  return;
270
291
  const open = await this.openConversations(candidates.filter((c) => c.kind === 'conversation').map((c) => c.runId));
271
- const targets = selectForRemoval(candidates, open, Date.now());
292
+ const inFlight = new Set([...this.leases].map((lease) => lease.runId));
293
+ const targets = selectForRemoval(candidates, open, Date.now(), inFlight);
272
294
  if (targets.length === 0)
273
295
  return;
274
- const removed = await removeWorktrees(targets, scrubEnv(process.env));
296
+ const env = scrubEnv(process.env);
297
+ const byRepo = targets.reduce((acc, c) => acc.set(c.repoPath, [...(acc.get(c.repoPath) ?? []), c]), new Map());
298
+ const removed = (await Promise.all([...byRepo].map(([repoPath, group]) => this.gitLocks.run(path.resolve(repoPath), () => removeWorktrees(group, env))))).reduce((a, b) => a + b, 0);
275
299
  if (removed > 0)
276
300
  console.log(`[runner] gc: ${removed} worktree(s) recogido(s)`);
277
301
  }
@@ -291,16 +315,63 @@ export class RunnerDaemon {
291
315
  console.log(`[runner] run ${run.id}: el checkout ${repoCfg.path} no existe`);
292
316
  return scratch('scratch · checkout no encontrado', [`el checkout de ${run.repo} no existe en este runner: corriendo en scratch`]);
293
317
  }
318
+ if (run.kind === RUN_KIND.prompt && run.isolation === RUN_ISOLATION.checkout) {
319
+ const co = await this.gitLocks.run(path.resolve(repoCfg.path), () => prepareCheckout(repoCfg.path, env));
320
+ return { ...co, repoCfg, worktree: null, conversation: false };
321
+ }
294
322
  if (run.kind === RUN_KIND.prompt) {
295
- // worktree siempre: `worktree: false` y skip-permissions del repo son solo para runs de reglas.
296
- const wt = await prepareConversationWorktree(repoCfg.path, run.id, run.branch, env);
323
+ // worktree salvo que el usuario eligiera el checkout: `worktree: false` y skip-permissions del
324
+ // repo son solo para runs de reglas.
325
+ const wt = await this.gitLocks.run(path.resolve(repoCfg.path), () => prepareConversationWorktree(repoCfg.path, run.id, run.branch, env));
297
326
  return { ...wt, repoCfg, worktree: wt.workdir, conversation: true };
298
327
  }
299
328
  if (repoCfg.worktree === false)
300
329
  return { workdir: repoCfg.path, repoCfg, worktree: null, conversation: false, note: 'checkout · sin worktree', warnings: [] };
301
- const wt = await prepareRunWorktree(repoCfg.path, run.id, run.branch, env);
330
+ const wt = await this.gitLocks.run(path.resolve(repoCfg.path), () => prepareRunWorktree(repoCfg.path, run.id, run.branch, env));
302
331
  return { ...wt, repoCfg, worktree: wt.workdir, conversation: false };
303
332
  }
333
+ // runs que comparten un cwd no aislado se turnan: el checkout (un repo con `worktree: false` o una
334
+ // conversación abierta en el checkout) y el scratch en perfil edit (dos runs de reglas en scratch
335
+ // conviven: la auto-memory compartida es la gracia del cwd fijo). devuelve con qué soltar el turno: no-op si no hacía falta, o si el run
336
+ // murió esperándolo (entonces se suelta en cuanto llega).
337
+ async holdCwd(run, prepared, lease, note) {
338
+ const shared = prepared.worktree === null && (prepared.repoCfg !== null || run.profile === PROMPT_PROFILE.edit);
339
+ if (!shared)
340
+ return () => { };
341
+ const key = path.resolve(prepared.workdir);
342
+ if (this.cwdLocks.busy(key))
343
+ note('esperando turno: otro run trabaja en este mismo directorio');
344
+ const acquiring = this.cwdLocks.acquire(key);
345
+ const release = await Promise.race([acquiring, lease.killed.then(() => null)]);
346
+ if (release)
347
+ return release;
348
+ void acquiring.then((r) => r());
349
+ return () => { };
350
+ }
351
+ // latido del run desde el claim hasta el cierre: transporta el soft-cancel del server (y refresca
352
+ // la presencia del runner). el run muere si ya no es suyo: cancel, un estado que no es running, o
353
+ // el run no existe.
354
+ startHeartbeat(lease, heartbeatMs, seg) {
355
+ const runId = lease.runId;
356
+ return setInterval(() => {
357
+ void this.api(`/runs/${runId}/heartbeat`, seg)
358
+ .then(async (res) => {
359
+ if (res.status === HTTP_NOT_FOUND) {
360
+ console.log(`[runner] run ${runId} ya no existe en el server; deteniéndolo`);
361
+ lease.kill('cancel');
362
+ return;
363
+ }
364
+ if (!res.ok)
365
+ return;
366
+ const body = (await res.json().catch(() => null));
367
+ if (body?.cancel || (typeof body?.status === 'string' && body.status !== RUN_STATUS_RUNNING)) {
368
+ console.log(`[runner] run ${runId} ya no es de este proceso (${body?.status ?? 'cancelado'}); deteniéndolo`);
369
+ lease.kill('cancel');
370
+ }
371
+ })
372
+ .catch((err) => console.error(`[runner] heartbeat del run ${runId} falló: ${err.message}`));
373
+ }, Math.max(MIN_HEARTBEAT_MS, heartbeatMs));
374
+ }
304
375
  // --- env del run: el del usuario saneado + perfil aws mapeado ---
305
376
  envFor(run) {
306
377
  const env = { ...scrubEnv(process.env), AWS_PAGER: '' };
@@ -318,19 +389,21 @@ export class RunnerDaemon {
318
389
  return env;
319
390
  }
320
391
  // --- ejecución ---
321
- async executeRun(claim) {
392
+ async executeRun(claim, lease) {
322
393
  const { run } = claim;
323
394
  const tag = `run ${run.id}`;
324
395
  console.log(`[runner] ${tag} reclamado (${run.kind}${run.profile ? `, perfil ${run.profile}` : ''}, entry ${run.entryId}${claim.tier ? `, tier ${claim.tier}` : ''}${run.repo ? `, repo ${run.repo}${run.branch ? `@${run.branch}` : ''}` : ''}${run.sessionId ? `, sesión ${run.sessionId}` : ''})`);
325
396
  const env = this.envFor(run);
326
397
  // identidad del proceso en cada llamada del run (servers anteriores a los segmentos: nada).
327
398
  const seg = run.segment !== null ? { segment: run.segment } : {};
399
+ const heartbeat = this.startHeartbeat(lease, claim.heartbeatMs, seg);
328
400
  const feed = claim.events?.enabled ? new EventUploader((events) => this.postEvents(run.id, events, seg), claim.events, tag) : null;
329
401
  let prepared;
330
402
  try {
331
403
  prepared = await this.prepareWorkdir(run, env);
332
404
  }
333
405
  catch (err) {
406
+ clearInterval(heartbeat);
334
407
  await feed?.close();
335
408
  await this.postStatus(run.id, { status: 'failed', error: `no se pudo preparar el directorio del run: ${err.message}`, ...seg });
336
409
  return;
@@ -347,6 +420,7 @@ export class RunnerDaemon {
347
420
  };
348
421
  note(prepared.note);
349
422
  [...claim.warnings, ...prepared.warnings].forEach(note);
423
+ const releaseCwd = await this.holdCwd(run, prepared, lease, note);
350
424
  // mcp-config temporal con el token per-run (0600; se borra al terminar).
351
425
  const mcpFile = path.join(os.tmpdir(), `duckhunt-runner-${run.id}-${crypto.randomBytes(4).toString('hex')}.json`);
352
426
  let report;
@@ -356,31 +430,36 @@ export class RunnerDaemon {
356
430
  [claim.mcp.serverName]: { type: 'http', url: claim.mcp.url, headers: { Authorization: `Bearer ${claim.mcp.token}` } },
357
431
  },
358
432
  }), { mode: 0o600 });
359
- report = await this.runAttempts(claim, prepared, env, mcpFile, feed, ctx, note);
433
+ report = await this.runAttempts(claim, lease, prepared, env, mcpFile, feed, ctx, note);
360
434
  }
361
435
  catch (err) {
362
436
  report = { status: 'failed', error: err.message };
363
437
  }
364
438
  finally {
365
439
  fs.rmSync(mcpFile, { force: true });
440
+ releaseCwd();
441
+ clearInterval(heartbeat);
366
442
  }
367
443
  await feed?.close();
368
- await this.postStatus(run.id, { ...report, ...seg });
369
- if (prepared.worktree && prepared.conversation) {
370
- touchWorktree(prepared.worktree);
444
+ const { worktree, repoCfg } = prepared;
445
+ if (worktree && prepared.conversation) {
446
+ touchWorktree(worktree);
371
447
  }
372
- else if (prepared.worktree && prepared.repoCfg) {
448
+ else if (worktree && repoCfg) {
373
449
  if (report.status === 'done')
374
- await removeRunWorktree(prepared.repoCfg.path, prepared.worktree, env);
450
+ await this.gitLocks.run(path.resolve(repoCfg.path), () => removeRunWorktree(repoCfg.path, worktree, env));
375
451
  else
376
- console.log(`[runner] worktree conservado para autopsia: ${prepared.worktree}`);
452
+ console.log(`[runner] worktree conservado para autopsia: ${worktree}`);
377
453
  }
454
+ await this.postStatus(run.id, { ...report, ...seg });
378
455
  console.log(`[runner] ${tag} terminado (${report.status}${report.error ? `: ${report.error}` : ''})`);
379
456
  }
380
457
  // uno o dos intentos: reanudación fallida antes de que el asistente hablara (sesión inexistente
381
458
  // en esta máquina, borrada, de otro daemon) → un solo reintento desde cero con el prompt de respaldo.
382
- async runAttempts(claim, prepared, env, mcpFile, feed, ctx, note) {
459
+ async runAttempts(claim, lease, prepared, env, mcpFile, feed, ctx, note) {
383
460
  const { run } = claim;
461
+ // settings de usuario leídos por run (pueden cambiar con el daemon vivo); solo pesan en lectura.
462
+ const userDeny = run.kind === RUN_KIND.prompt && run.profile === PROMPT_PROFILE.read ? userBashDeny() : [];
384
463
  const args = (prompt, resumeSessionId) => buildClaudeArgs({
385
464
  claim,
386
465
  prompt,
@@ -391,25 +470,28 @@ export class RunnerDaemon {
391
470
  configBudgetUsd: this.cfg.defaults.maxBudgetUsd,
392
471
  skipPermissions: prepared.repoCfg?.dangerouslySkipPermissions === true,
393
472
  payingWithApiKey: !!process.env.ANTHROPIC_API_KEY,
473
+ userBashDeny: userDeny,
394
474
  });
395
475
  // reanudar o no lo decide el server: manda sessionId solo cuando hay sesión que retomar.
396
476
  const resume = run.sessionId;
397
- let attempt = await this.spawnClaude(claim, args(claim.prompt, resume), prepared, env, feed, ctx);
477
+ let attempt = await this.spawnClaude(claim, lease, args(claim.prompt, resume), prepared, env, feed, ctx);
398
478
  let resumed = resume ? true : undefined;
399
479
  if (resume && attempt.killedBy === null && attempt.exitCode !== 0 && !attempt.stream.sawAssistant && claim.fallbackPrompt) {
400
480
  console.log(`[runner] run ${run.id}: la sesión ${resume} no se pudo reanudar`);
401
481
  note('la sesión anterior no se pudo reanudar en este runner: reintento desde cero');
402
- attempt = await this.spawnClaude(claim, args(claim.fallbackPrompt, null), prepared, env, feed, ctx);
482
+ attempt = await this.spawnClaude(claim, lease, args(claim.fallbackPrompt, null), prepared, env, feed, ctx);
403
483
  resumed = false;
404
484
  }
405
485
  return reportFor(attempt, resumed);
406
486
  }
407
487
  // spawnea claude en su propio grupo de procesos, consume stdout (stream-json → contadores + feed)
408
- // y stderr (tail), bombea heartbeat (soft-cancel) y progreso, y aplica el timeout wall-clock.
409
- // resuelve siempre (nunca rechaza).
410
- spawnClaude(claim, args, prepared, env, feed, ctx) {
488
+ // y stderr (tail), bombea el progreso y aplica el timeout wall-clock. si el run ya murió (cancel o
489
+ // parada mientras esperaba turno) no lo lanza. resuelve siempre (nunca rechaza).
490
+ spawnClaude(claim, lease, args, prepared, env, feed, ctx) {
411
491
  const runId = claim.run.id;
412
492
  const seg = claim.run.segment !== null ? { segment: claim.run.segment } : {};
493
+ if (lease.killedBy)
494
+ return Promise.resolve({ exitCode: null, killedBy: lease.killedBy, stream: newStreamState(), stderrTail: '' });
413
495
  return new Promise((resolve) => {
414
496
  const stream = newStreamState();
415
497
  const stderrTail = [];
@@ -442,10 +524,7 @@ export class RunnerDaemon {
442
524
  signalGroup(child, 'SIGTERM');
443
525
  killTimer = setTimeout(() => signalGroup(child, 'SIGKILL'), KILL_GRACE_MS);
444
526
  };
445
- this.active = child;
446
- this.killActive = kill;
447
- if (this.stopping)
448
- kill('shutdown');
527
+ lease.attach(child, kill);
449
528
  readline.createInterface({ input: child.stdout }).on('line', (line) => {
450
529
  const ev = consumeStreamLine(stream, line);
451
530
  if (ev && feed)
@@ -460,26 +539,6 @@ export class RunnerDaemon {
460
539
  if (logFile !== null)
461
540
  fs.writeSync(logFile, `${JSON.stringify({ type: 'stderr', line })}\n`);
462
541
  });
463
- // heartbeat: transporta el soft-cancel del server (y refresca la presencia del runner). el
464
- // proceso muere si el run ya no es suyo: cancel, un estado que no es running, o el run no existe.
465
- const heartbeat = setInterval(() => {
466
- void this.api(`/runs/${runId}/heartbeat`, seg)
467
- .then(async (res) => {
468
- if (res.status === HTTP_NOT_FOUND) {
469
- console.log(`[runner] run ${runId} ya no existe en el server; deteniendo claude`);
470
- kill('cancel');
471
- return;
472
- }
473
- if (!res.ok)
474
- return;
475
- const body = (await res.json().catch(() => null));
476
- if (body?.cancel || (typeof body?.status === 'string' && body.status !== RUN_STATUS_RUNNING)) {
477
- console.log(`[runner] run ${runId} ya no es de este proceso (${body?.status ?? 'cancelado'}); deteniendo claude`);
478
- kill('cancel');
479
- }
480
- })
481
- .catch((err) => console.error(`[runner] heartbeat falló: ${err.message}`));
482
- }, Math.max(MIN_HEARTBEAT_MS, claim.heartbeatMs));
483
542
  // progreso: tool calls del segmento (throttled) + la nota de workdir en el primer envío.
484
543
  const postProgress = (toolCalls, workdir) => {
485
544
  void this.api(`/runs/${runId}/progress`, { toolCalls, ...(workdir ? { workdir } : {}), ...seg }).catch((err) => console.error(`[runner] progress falló: ${err.message}`));
@@ -510,7 +569,6 @@ export class RunnerDaemon {
510
569
  }, EXIT_DRAIN_MS);
511
570
  });
512
571
  child.on('close', (code) => {
513
- clearInterval(heartbeat);
514
572
  clearInterval(progress);
515
573
  clearTimeout(timeout);
516
574
  if (killTimer)
@@ -519,8 +577,7 @@ export class RunnerDaemon {
519
577
  clearTimeout(drainTimer);
520
578
  if (logFile !== null)
521
579
  fs.closeSync(logFile);
522
- this.active = null;
523
- this.killActive = null;
580
+ lease.detach();
524
581
  resolve({ exitCode: code, killedBy, stream, stderrTail: stderrTail.join('\n').slice(-STDERR_TAIL_MAX_CHARS) });
525
582
  });
526
583
  });