@tablation/crew 0.132.2 → 0.133.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 (2) hide show
  1. package/dist/cli.js +468 -246
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -6511,7 +6511,7 @@ import { join as join31 } from "path";
6511
6511
 
6512
6512
  // src/agent.ts
6513
6513
  import { spawnSync as spawnSync6 } from "child_process";
6514
- import { readFileSync as readFileSync27, existsSync as existsSync27, statSync as statSync8, mkdirSync as mkdirSync19, writeFileSync as writeFileSync20, createWriteStream, openSync as openSync4, closeSync as closeSync4, readSync } from "fs";
6514
+ import { readFileSync as readFileSync27, existsSync as existsSync27, statSync as statSync9, mkdirSync as mkdirSync19, writeFileSync as writeFileSync20, createWriteStream, openSync as openSync4, closeSync as closeSync4, readSync } from "fs";
6515
6515
  import { StringDecoder } from "string_decoder";
6516
6516
  import { finished } from "stream/promises";
6517
6517
  import { join as join30, dirname as dirname15, basename as basename9 } from "path";
@@ -10362,14 +10362,14 @@ async function findTicketRecord(target, t, ref) {
10362
10362
  );
10363
10363
  return rows.length === 1 ? rows[0].id : void 0;
10364
10364
  }
10365
- function counterIncrements(run3, cols, have) {
10365
+ function counterIncrements(run4, cols, have) {
10366
10366
  const figures = [
10367
10367
  [cols.agentRuns, 1],
10368
- [cols.tokensIn, run3.tokensIn],
10369
- [cols.tokensOut, run3.tokensOut],
10370
- [cols.cacheReadTokens, run3.cacheReadTokens],
10371
- [cols.cacheWriteTokens, run3.cacheWriteTokens],
10372
- [cols.costUsd, run3.costUsd]
10368
+ [cols.tokensIn, run4.tokensIn],
10369
+ [cols.tokensOut, run4.tokensOut],
10370
+ [cols.cacheReadTokens, run4.cacheReadTokens],
10371
+ [cols.cacheWriteTokens, run4.cacheWriteTokens],
10372
+ [cols.costUsd, run4.costUsd]
10373
10373
  ];
10374
10374
  const out = {};
10375
10375
  for (const [column, value2] of figures) {
@@ -10448,42 +10448,42 @@ async function post(target, path, body) {
10448
10448
  if (!res.ok) throw new AgentLogHttpError(`${path}: ${res.status} ${res.statusText}`, res.status);
10449
10449
  return await res.json();
10450
10450
  }
10451
- async function reportAgentRun(target, run3) {
10451
+ async function reportAgentRun(target, run4) {
10452
10452
  let ticketRecordId;
10453
- if (target.tickets && run3.ticketReference) {
10453
+ if (target.tickets && run4.ticketReference) {
10454
10454
  try {
10455
- ticketRecordId = await findTicketRecord(target, target.tickets, run3.ticketReference);
10455
+ ticketRecordId = await findTicketRecord(target, target.tickets, run4.ticketReference);
10456
10456
  } catch {
10457
10457
  }
10458
10458
  }
10459
10459
  const body = {
10460
10460
  agentId: target.agentId,
10461
- ticketReference: run3.ticketReference,
10462
- outcome: run3.outcome,
10463
- startedAt: run3.startedAt,
10464
- finishedAt: run3.finishedAt,
10461
+ ticketReference: run4.ticketReference,
10462
+ outcome: run4.outcome,
10463
+ startedAt: run4.startedAt,
10464
+ finishedAt: run4.finishedAt,
10465
10465
  source: "client",
10466
10466
  client: "crew",
10467
- model: run3.model,
10468
- tokensIn: run3.tokensIn,
10469
- tokensOut: run3.tokensOut,
10470
- cacheReadTokens: run3.cacheReadTokens,
10471
- cacheWriteTokens: run3.cacheWriteTokens,
10472
- costUsd: run3.costUsd,
10473
- numTurns: run3.numTurns,
10474
- prefixTokens: run3.prefixTokens,
10475
- promptVersion: run3.promptVersion,
10476
- promptSha: run3.promptSha
10467
+ model: run4.model,
10468
+ tokensIn: run4.tokensIn,
10469
+ tokensOut: run4.tokensOut,
10470
+ cacheReadTokens: run4.cacheReadTokens,
10471
+ cacheWriteTokens: run4.cacheWriteTokens,
10472
+ costUsd: run4.costUsd,
10473
+ numTurns: run4.numTurns,
10474
+ prefixTokens: run4.prefixTokens,
10475
+ promptVersion: run4.promptVersion,
10476
+ promptSha: run4.promptSha
10477
10477
  };
10478
- const { runId, ...legacyBody } = { ...body, runId: run3.runId };
10478
+ const { runId, ...legacyBody } = { ...body, runId: run4.runId };
10479
10479
  const workItem = target.tickets && ticketRecordId ? { workItemTable: target.tickets.issuesModelId, workItemRecordId: ticketRecordId } : {};
10480
10480
  let entry;
10481
10481
  try {
10482
- entry = await post(target, "/agents/log", { ...body, ...runId ? { runId } : {}, ...workItem, harness: run3.harness, provider: run3.provider });
10482
+ entry = await post(target, "/agents/log", { ...body, ...runId ? { runId } : {}, ...workItem, harness: run4.harness, provider: run4.provider });
10483
10483
  } catch (e) {
10484
10484
  if (!(e instanceof AgentLogHttpError)) throw new AgentLogUnreachableError(e.message);
10485
10485
  if (e.status >= 500) throw new AgentLogUnreachableError(e.message);
10486
- if (e.status !== 400 || !run3.harness && !run3.provider && !ticketRecordId && !runId) {
10486
+ if (e.status !== 400 || !run4.harness && !run4.provider && !ticketRecordId && !runId) {
10487
10487
  e.row = true;
10488
10488
  throw e;
10489
10489
  }
@@ -10494,7 +10494,7 @@ async function reportAgentRun(target, run3) {
10494
10494
  throw e2;
10495
10495
  }
10496
10496
  }
10497
- for (const cycle of run3.cycles) {
10497
+ for (const cycle of run4.cycles) {
10498
10498
  await post(target, `/agents/log/${entry.id}/cycles`, {
10499
10499
  cycleIndex: cycle.cycleIndex,
10500
10500
  occurredAt: cycle.occurredAt,
@@ -10502,20 +10502,20 @@ async function reportAgentRun(target, run3) {
10502
10502
  ...cycle.role ? { role: cycle.role } : {}
10503
10503
  });
10504
10504
  }
10505
- if (run3.beforeFirstEdit) await writeBeforeFirstEdit(target, entry.id, run3.beforeFirstEdit);
10505
+ if (run4.beforeFirstEdit) await writeBeforeFirstEdit(target, entry.id, run4.beforeFirstEdit);
10506
10506
  if (target.tickets && ticketRecordId) {
10507
10507
  const bounces = await countAcceptanceBounces(target, target.tickets.issuesModelId, ticketRecordId);
10508
10508
  if (bounces !== null) await writeHandoffBounces(target, entry.id, bounces);
10509
10509
  }
10510
10510
  let counterWarning;
10511
- let counted = run3;
10511
+ let counted = run4;
10512
10512
  if (runId && target.tickets && ticketRecordId) {
10513
10513
  try {
10514
10514
  const totals = await inferenceTotalsFor(target, runId);
10515
- if (totals) counted = { ...run3, tokensIn: totals.tokensIn, tokensOut: totals.tokensOut, cacheReadTokens: totals.cacheReadTokens, cacheWriteTokens: totals.cacheWriteTokens, costUsd: totals.costUsd };
10516
- else counted = { ...run3, ...run3.harnessTotals };
10515
+ if (totals) counted = { ...run4, tokensIn: totals.tokensIn, tokensOut: totals.tokensOut, cacheReadTokens: totals.cacheReadTokens, cacheWriteTokens: totals.cacheWriteTokens, costUsd: totals.costUsd };
10516
+ else counted = { ...run4, ...run4.harnessTotals };
10517
10517
  } catch (e) {
10518
- counterWarning = `could not sum run ${runId}'s inference rows for ${run3.ticketReference}: ${e.message}`;
10518
+ counterWarning = `could not sum run ${runId}'s inference rows for ${run4.ticketReference}: ${e.message}`;
10519
10519
  }
10520
10520
  }
10521
10521
  const counters = target.tickets && ticketRecordId ? await addRunToTicket(target, target.tickets, ticketRecordId, counted) : void 0;
@@ -10532,20 +10532,20 @@ async function writeCounters(target, w) {
10532
10532
  if (Object.keys(body).length === 0) return;
10533
10533
  await request(target, "PATCH", `/data-models/${w.issuesModelId}/records/${w.recordId}`, body);
10534
10534
  }
10535
- async function addRunToTicket(target, t, recordId, run3) {
10535
+ async function addRunToTicket(target, t, recordId, run4) {
10536
10536
  const write = {
10537
10537
  issuesModelId: t.issuesModelId,
10538
10538
  recordId,
10539
- ticketReference: run3.ticketReference,
10539
+ ticketReference: run4.ticketReference,
10540
10540
  counters: t.counters,
10541
- body: counterIncrements(run3, t.counters, new Set(Object.values(t.counters)))
10541
+ body: counterIncrements(run4, t.counters, new Set(Object.values(t.counters)))
10542
10542
  };
10543
10543
  try {
10544
10544
  await writeCounters(target, write);
10545
10545
  return {};
10546
10546
  } catch (e) {
10547
10547
  return {
10548
- warning: `could not add run spend to ${run3.ticketReference}: ${e.message}`,
10548
+ warning: `could not add run spend to ${run4.ticketReference}: ${e.message}`,
10549
10549
  ...isRetryable(e) ? { retry: write } : {}
10550
10550
  };
10551
10551
  }
@@ -10878,7 +10878,7 @@ var HandoffTranscriptTracker = class {
10878
10878
  import { createHash as createHash4 } from "crypto";
10879
10879
  import { spawn as spawn3 } from "child_process";
10880
10880
  import { execFileSync as execFileSync7 } from "child_process";
10881
- import { existsSync as existsSync24, mkdirSync as mkdirSync17, readFileSync as readFileSync24, renameSync as renameSync3, writeFileSync as writeFileSync18, rmSync as rmSync14 } from "fs";
10881
+ import { existsSync as existsSync24, mkdirSync as mkdirSync17, readFileSync as readFileSync24, renameSync as renameSync3, writeFileSync as writeFileSync18, rmSync as rmSync14, statSync as statSync8 } from "fs";
10882
10882
  import { dirname as dirname13, join as join26 } from "path";
10883
10883
  import { fileURLToPath } from "url";
10884
10884
  import { tmpdir as tmpdir3 } from "os";
@@ -11114,6 +11114,7 @@ function sandboxImageStatus(state, plan) {
11114
11114
  if (current.tag !== plan.tag) return { status: "stale", detail: `running ${current.tag} (claude ${current.claude ?? "unknown"}), declaration now builds ${plan.tag} (claude ${plan.claude})` };
11115
11115
  return { status: "ok", detail: `${current.tag} built ${current.builtAt}, claude ${current.claude ?? "unknown"}` };
11116
11116
  }
11117
+ var BUILD_INTERRUPTED = -1;
11117
11118
  var spawnBuildRunner = (engine = "docker") => (args, logPath) => new Promise((resolve8) => {
11118
11119
  const child = spawn3(engine, args, { stdio: ["ignore", "pipe", "pipe"] });
11119
11120
  const chunks = [];
@@ -11126,7 +11127,7 @@ ${Buffer.concat(chunks).toString("utf8")}${extra}`, { flag: "a" });
11126
11127
  };
11127
11128
  child.on("error", (e) => done(127, `${e.message}
11128
11129
  `));
11129
- child.on("close", (code) => done(code ?? 1));
11130
+ child.on("close", (code) => done(code ?? BUILD_INTERRUPTED));
11130
11131
  });
11131
11132
  var engineHasImage = (engine = "docker", exec = realExec) => (tag) => {
11132
11133
  try {
@@ -11166,6 +11167,7 @@ async function buildSandboxImage(plan, deps) {
11166
11167
  }
11167
11168
  if (layer.caBundleFile) writeFileSync18(join26(ctx, layer.caBundleFile), (deps.caBundle ?? readHostCaBundle)());
11168
11169
  const code = await deps.run(["build", "--tag", layer.tag, "--file", join26(ctx, "Dockerfile"), ctx], logPath);
11170
+ if (code === BUILD_INTERRUPTED) return { kind: "interrupted", tag: plan.tag };
11169
11171
  if (code !== 0) {
11170
11172
  state[plan.repo] = { ...entry, failure: { tag: plan.tag, at: now().toISOString(), logPath } };
11171
11173
  writeSandboxState(deps.stateDir, state);
@@ -11192,9 +11194,20 @@ function sandboxFailedItem(repo, tag, layer, logPath, nowIso = (/* @__PURE__ */
11192
11194
  message: `${repo}: sandbox image ${tag} failed to build at the ${layer} layer (log: ${logPath}); sandboxes keep running the previous image. Retries automatically after the declaration changes or in an hour; \`crew sandbox build\` forces it`
11193
11195
  };
11194
11196
  }
11197
+ function failureLogIsEmpty(failure) {
11198
+ try {
11199
+ return statSync8(failure.logPath).size === 0;
11200
+ } catch {
11201
+ return true;
11202
+ }
11203
+ }
11195
11204
  async function sandboxBuildTick(repos, deps, force = false) {
11196
11205
  const nowMs = (deps.now ?? (() => /* @__PURE__ */ new Date()))().getTime();
11197
11206
  for (const r of repos) {
11207
+ if (r.unreadable) {
11208
+ deps.log(`sandbox image for ${r.name}: not building, ${r.unreadable}`);
11209
+ continue;
11210
+ }
11198
11211
  const plan = planSandbox(r.name, r.decl, r.warm, r.bridge);
11199
11212
  const state = readSandboxState(deps.stateDir)[r.name];
11200
11213
  const upToDate = state?.tags[0]?.tag === plan.tag && deps.hasImage(plan.tag);
@@ -11203,10 +11216,12 @@ async function sandboxBuildTick(repos, deps, force = false) {
11203
11216
  continue;
11204
11217
  }
11205
11218
  const present = !upToDate && deps.hasImage(plan.tag);
11206
- if (!force && !present && state?.failure?.tag === plan.tag && nowMs - Date.parse(state.failure.at) < SANDBOX_RETRY_AFTER_MS) continue;
11219
+ if (!force && !present && state?.failure?.tag === plan.tag && nowMs - Date.parse(state.failure.at) < SANDBOX_RETRY_AFTER_MS && !failureLogIsEmpty(state.failure)) continue;
11207
11220
  deps.log(`sandbox image for ${r.name}: ${present ? `found ${plan.tag} in the engine, recording it` : `building ${plan.tag}`}`);
11208
11221
  const out = await buildSandboxImage(plan, deps);
11209
- if (out.kind === "failed") {
11222
+ if (out.kind === "interrupted") {
11223
+ deps.log(`sandbox image for ${r.name}: build of ${out.tag} was interrupted; it restarts on the next pass`);
11224
+ } else if (out.kind === "failed") {
11210
11225
  deps.raise(sandboxFailedItem(r.name, out.tag, out.layer, out.logPath));
11211
11226
  deps.log(`sandbox image for ${r.name}: build failed at the ${out.layer} layer, log ${out.logPath}`);
11212
11227
  } else {
@@ -12048,6 +12063,16 @@ function sandboxName(plan, now = Date.now()) {
12048
12063
  const tag = (h.readUInt32BE(0) % 36 ** 6).toString(36).padStart(6, "0");
12049
12064
  return `crew-${tag}${now.toString(36).slice(-8).padStart(8, "0")}`;
12050
12065
  }
12066
+ function labelValue(v) {
12067
+ return v.replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 63);
12068
+ }
12069
+ function sandboxLabels(o) {
12070
+ return [
12071
+ `crew.role=${labelValue(o.role)}`,
12072
+ ...o.ticket ? [`crew.ticket=${labelValue(o.ticket)}`] : [],
12073
+ `crew.run=${labelValue(o.run)}`
12074
+ ];
12075
+ }
12051
12076
  var SandboxRunner = class {
12052
12077
  kind = "sandbox";
12053
12078
  cfg;
@@ -12090,6 +12115,7 @@ var SandboxRunner = class {
12090
12115
  }
12091
12116
  const create2 = ["sandbox", "create", "--name", name, "--detach"];
12092
12117
  if (policyFile) create2.push("--policy", policyFile);
12118
+ for (const l of sandboxLabels({ role: plan.role, ticket: plan.ticket, run: basename8(plan.streamPath).replace(/\.jsonl$/, "") })) create2.push("--label", l);
12093
12119
  const image = cfg.image ?? plan.sandboxImage;
12094
12120
  if (image) create2.push("--from", image);
12095
12121
  if (cfg.cacheVolume) {
@@ -12212,16 +12238,16 @@ function runnerOfSidecar(sc) {
12212
12238
  return sc.runner === "sandbox" ? new SandboxRunner(sc.sandboxBin ? { bin: sc.sandboxBin } : {}) : new HostRunner();
12213
12239
  }
12214
12240
  var PROBE_CREATE_TIMEOUT_MS = 12e4;
12215
- function checkSandboxRunner(cfg = {}, run3 = (b, a, t) => execFileSync8(b, a, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: t ?? 15e3 })) {
12241
+ function checkSandboxRunner(cfg = {}, run4 = (b, a, t) => execFileSync8(b, a, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: t ?? 15e3 })) {
12216
12242
  const bin = cfg.bin ?? DEFAULT_SANDBOX_CONFIG.bin;
12217
12243
  let version;
12218
12244
  try {
12219
- version = run3(bin, ["--version"]).trim();
12245
+ version = run4(bin, ["--version"]).trim();
12220
12246
  } catch (e) {
12221
12247
  return { ok: false, detail: `${bin} is not installed or not on the scheduler PATH (${e.message.split("\n")[0]})` };
12222
12248
  }
12223
12249
  try {
12224
- run3(bin, ["status"]);
12250
+ run4(bin, ["status"]);
12225
12251
  } catch (e) {
12226
12252
  const err3 = e;
12227
12253
  return {
@@ -12231,7 +12257,7 @@ function checkSandboxRunner(cfg = {}, run3 = (b, a, t) => execFileSync8(b, a, {
12231
12257
  }
12232
12258
  const probe = sandboxName({ route: "doctor", role: "dev", ticket: void 0 });
12233
12259
  try {
12234
- run3(bin, ["sandbox", "create", "--name", probe, "--detach", "--", "sleep", "60"], PROBE_CREATE_TIMEOUT_MS);
12260
+ run4(bin, ["sandbox", "create", "--name", probe, "--detach", "--", "sleep", "60"], PROBE_CREATE_TIMEOUT_MS);
12235
12261
  } catch (e) {
12236
12262
  const err3 = e;
12237
12263
  if (err3.code === "ETIMEDOUT" || err3.killed) {
@@ -12240,7 +12266,7 @@ function checkSandboxRunner(cfg = {}, run3 = (b, a, t) => execFileSync8(b, a, {
12240
12266
  return { ok: false, detail: `${version}: the gateway refused a probe sandbox named ${probe} (${(err3.stderr || err3.message).trim().split("\n").filter(Boolean).slice(0, 2).join(" / ")})` };
12241
12267
  } finally {
12242
12268
  try {
12243
- run3(bin, ["sandbox", "delete", probe]);
12269
+ run4(bin, ["sandbox", "delete", probe]);
12244
12270
  } catch {
12245
12271
  }
12246
12272
  }
@@ -12420,7 +12446,7 @@ function planAgentRun(o) {
12420
12446
  let digest;
12421
12447
  let ageSeconds;
12422
12448
  if (existsSync27(digestPath2)) {
12423
- ageSeconds = Math.floor((now() - statSync8(digestPath2).mtimeMs) / 1e3);
12449
+ ageSeconds = Math.floor((now() - statSync9(digestPath2).mtimeMs) / 1e3);
12424
12450
  if (ageSeconds <= DIGEST_MAX_AGE_SECONDS) digest = readFileSync27(digestPath2, "utf8");
12425
12451
  }
12426
12452
  const common = usesCommon ? readFileSync27(commonPath, "utf8") : "";
@@ -13029,9 +13055,9 @@ function spawnAgent(plan, emit, hintMoved) {
13029
13055
  }
13030
13056
  if (begun instanceof Promise) {
13031
13057
  return begun.then(
13032
- (run3) => {
13058
+ (run4) => {
13033
13059
  closeSync4(streamFd);
13034
- return supervise(run3);
13060
+ return supervise(run4);
13035
13061
  },
13036
13062
  (e) => {
13037
13063
  closeSync4(streamFd);
@@ -13250,7 +13276,7 @@ async function reconcileRuns(o) {
13250
13276
  }
13251
13277
 
13252
13278
  // src/live-runs.ts
13253
- import { existsSync as existsSync29, readdirSync as readdirSync10, statSync as statSync9 } from "fs";
13279
+ import { existsSync as existsSync29, readdirSync as readdirSync10, statSync as statSync10 } from "fs";
13254
13280
  import { join as join32 } from "path";
13255
13281
  function liveRuns(stateDir, isAlive = runIsAlive) {
13256
13282
  const dir = join32(stateDir, "streams");
@@ -13276,7 +13302,7 @@ function runActivity(stateDir, isAlive = runIsAlive) {
13276
13302
  const streamPath = join32(dir, name);
13277
13303
  if (!runFinished(streamPath)) continue;
13278
13304
  try {
13279
- newest = Math.max(newest, statSync9(`${streamPath}.meta.json`).mtimeMs);
13305
+ newest = Math.max(newest, statSync10(`${streamPath}.meta.json`).mtimeMs);
13280
13306
  } catch {
13281
13307
  }
13282
13308
  }
@@ -13312,27 +13338,27 @@ async function settleRunEnd(o) {
13312
13338
  emit.warn(`could not beat ship idle: ${e.message}`, { step: "agent" });
13313
13339
  }
13314
13340
  }
13315
- function describeRun(run3, route2, seatIds, worktreeOf = (d, n) => {
13341
+ function describeRun(run4, route2, seatIds, worktreeOf = (d, n) => {
13316
13342
  try {
13317
13343
  return worktreeForNumber(d, n)?.path ?? null;
13318
13344
  } catch {
13319
13345
  return null;
13320
13346
  }
13321
13347
  }) {
13322
- const ownRoute = run3.route === routeSlug(route2.route);
13323
- const repoDir = run3.repo ? reposOf(route2).find((t) => t.name === run3.repo)?.dir : void 0;
13324
- const num2 = run3.ticket?.replace(/^\D+/, "") ?? "";
13348
+ const ownRoute = run4.route === routeSlug(route2.route);
13349
+ const repoDir = run4.repo ? reposOf(route2).find((t) => t.name === run4.repo)?.dir : void 0;
13350
+ const num2 = run4.ticket?.replace(/^\D+/, "") ?? "";
13325
13351
  return {
13326
- role: run3.role,
13327
- seat: ownRoute ? seatIds[run3.role] ?? null : null,
13328
- ticket: run3.ticket,
13329
- ticketRecordId: run3.ticketRecordId,
13330
- repo: run3.repo ?? null,
13352
+ role: run4.role,
13353
+ seat: ownRoute ? seatIds[run4.role] ?? null : null,
13354
+ ticket: run4.ticket,
13355
+ ticketRecordId: run4.ticketRecordId,
13356
+ repo: run4.repo ?? null,
13331
13357
  worktree: repoDir && num2 ? worktreeOf(repoDir, num2) : null,
13332
- stream: run3.streamPath,
13333
- pid: run3.pid,
13334
- startedAt: run3.spawnedAt,
13335
- deadline: run3.deadline ?? null
13358
+ stream: run4.streamPath,
13359
+ pid: run4.pid,
13360
+ startedAt: run4.spawnedAt,
13361
+ deadline: run4.deadline ?? null
13336
13362
  };
13337
13363
  }
13338
13364
 
@@ -13372,22 +13398,22 @@ function realDeprovisionDeps(cfg, emit, crewHome, getStore) {
13372
13398
  };
13373
13399
  return {
13374
13400
  liveRuns: () => liveRuns(stateDir).map((r) => ({ role: r.role, route: r.route, pid: r.pid, ticketRecordId: r.ticketRecordId ?? void 0, streamPath: r.streamPath })),
13375
- killRun: (run3) => killRunGroup(run3.pid),
13376
- recordKill(run3) {
13377
- emit.emit(`run_killed: ${run3.role} run on ${run3.route} stopped by crew deprovision`, {
13401
+ killRun: (run4) => killRunGroup(run4.pid),
13402
+ recordKill(run4) {
13403
+ emit.emit(`run_killed: ${run4.role} run on ${run4.route} stopped by crew deprovision`, {
13378
13404
  step: "agent",
13379
- role: run3.role,
13380
- data: { event: "run_killed", reason: "deprovision", pid: run3.pid }
13405
+ role: run4.role,
13406
+ data: { event: "run_killed", reason: "deprovision", pid: run4.pid }
13381
13407
  });
13382
13408
  },
13383
- async handBack(run3) {
13384
- const route2 = routeFor(run3.route);
13385
- if (!run3.ticketRecordId || !route2) return;
13386
- const memberId = route2.resolved?.seats[run3.role];
13409
+ async handBack(run4) {
13410
+ const route2 = routeFor(run4.route);
13411
+ if (!run4.ticketRecordId || !route2) return;
13412
+ const memberId = route2.resolved?.seats[run4.role];
13387
13413
  if (!memberId) return;
13388
- const identity = await resolveSeatKey(route2, run3.role, getStore);
13414
+ const identity = await resolveSeatKey(route2, run4.role, getStore);
13389
13415
  const tracker = new Tracker(route2, cfg.ship, { apiKey: identity.apiKey });
13390
- const t = await tracker.ticket(run3.ticketRecordId);
13416
+ const t = await tracker.ticket(run4.ticketRecordId);
13391
13417
  const target = repoTargetFor(route2, t.repo_id);
13392
13418
  const num2 = String(t[tracker.contract.columns.key] ?? "").replace(/^\D+/, "");
13393
13419
  const wt = target && num2 ? worktreeForNumber(target.dir, num2) : null;
@@ -13396,7 +13422,7 @@ function realDeprovisionDeps(cfg, emit, crewHome, getStore) {
13396
13422
  if (wt) dirty = status(wt.path).length > 0;
13397
13423
  } catch {
13398
13424
  }
13399
- await tracker.postEvent(run3.ticketRecordId, interruptedComment({
13425
+ await tracker.postEvent(run4.ticketRecordId, interruptedComment({
13400
13426
  branch: wt?.branch ?? null,
13401
13427
  dirty,
13402
13428
  reason: "the host was released and wiped"
@@ -14086,12 +14112,12 @@ function isSshRemote(url) {
14086
14112
  function pushAuthHint(remoteUrl) {
14087
14113
  return isSshRemote(remoteUrl) ? "make sure an SSH key is loaded for this host (ssh-add), and that the scheduler user can reach it" : "run `gh auth login`, then `gh auth setup-git`";
14088
14114
  }
14089
- function probePushAuth(o, run3 = realGit, baseEnv = process.env) {
14115
+ function probePushAuth(o, run4 = realGit, baseEnv = process.env) {
14090
14116
  if (o.offline) return { state: "skipped", detail: "skipped (--offline)" };
14091
14117
  if (!o.remoteUrl) return { state: "skipped", detail: `no remote "${o.remote}" configured` };
14092
14118
  const env = { ...baseEnv, GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "never", GIT_SSH_COMMAND: `${baseEnv.GIT_SSH_COMMAND ?? "ssh"} -o BatchMode=yes` };
14093
14119
  try {
14094
- run3(o.dir, ["push", "--dry-run", o.remote, `HEAD:refs/heads/${PROBE_BRANCH}`], env);
14120
+ run4(o.dir, ["push", "--dry-run", o.remote, `HEAD:refs/heads/${PROBE_BRANCH}`], env);
14095
14121
  return { state: "ok" };
14096
14122
  } catch (e) {
14097
14123
  const err3 = e;
@@ -14107,7 +14133,7 @@ function probePushAuth(o, run3 = realGit, baseEnv = process.env) {
14107
14133
  };
14108
14134
  }
14109
14135
  try {
14110
- run3(o.dir, ["ls-remote", "--exit-code", o.remote, "HEAD"], env);
14136
+ run4(o.dir, ["ls-remote", "--exit-code", o.remote, "HEAD"], env);
14111
14137
  return {
14112
14138
  state: "failed",
14113
14139
  detail: `the token for forge ${f.host} is read-only (fetch works, push refused): ${detail}`,
@@ -14149,8 +14175,8 @@ function formatToolCheck(t) {
14149
14175
  return `${label}${t.need === "required" ? "NOT FOUND" : "not found"} [${t.need}] \u2014 ${t.hint}
14150
14176
  `;
14151
14177
  }
14152
- function probeCredentialHelper(command2, run3 = realHelperRun) {
14153
- const r = run3(`${command2} credential get --no-miss`, "protocol=https\nhost=crew-probe.invalid\n\n");
14178
+ function probeCredentialHelper(command2, run4 = realHelperRun) {
14179
+ const r = run4(`${command2} credential get --no-miss`, "protocol=https\nhost=crew-probe.invalid\n\n");
14154
14180
  if (r.status === 0 && !/unknown command|usage:/i.test(r.stderr)) return { state: "ok" };
14155
14181
  const why = r.stderr.trim().split("\n")[0] || `exit ${r.status}`;
14156
14182
  return { state: "failed", detail: `the git credential helper command does not run: ${why}`, hint: "reinstall crew; git cannot authenticate to a private repository until this works" };
@@ -14357,17 +14383,17 @@ var REMEDY = {
14357
14383
  timeout: "the harness did not answer in time \u2014 run it by hand to see where it stalls",
14358
14384
  "wrong-answer": "the agent answered but did not name the workspace \u2014 run it by hand to see what it said"
14359
14385
  };
14360
- function classify(spec, run3, seen) {
14386
+ function classify(spec, run4, seen) {
14361
14387
  const bin = spec.launcher ?? spec.bin;
14362
14388
  const fail2 = (failure, what) => ({ failure, detail: `${what} \u2014 ${REMEDY[failure]}` });
14363
- if (run3.spawnError) {
14364
- if (run3.spawnError.code === "ENOENT") return fail2("binary-not-found", `\`${bin}\` is not on the scheduler PATH`);
14365
- return fail2("binary-not-found", `could not start \`${bin}\` (${run3.spawnError.message})`);
14389
+ if (run4.spawnError) {
14390
+ if (run4.spawnError.code === "ENOENT") return fail2("binary-not-found", `\`${bin}\` is not on the scheduler PATH`);
14391
+ return fail2("binary-not-found", `could not start \`${bin}\` (${run4.spawnError.message})`);
14366
14392
  }
14367
- if (run3.timedOut) return fail2("timeout", "no answer within the time limit");
14393
+ if (run4.timedOut) return fail2("timeout", "no answer within the time limit");
14368
14394
  const text2 = `${seen.toolOutput}
14369
- ${run3.stderr}`;
14370
- if (REFUSED.test(seen.toolOutput) || seen.tools.some((t) => t.startsWith("mcp__")) && REFUSED.test(run3.stderr)) {
14395
+ ${run4.stderr}`;
14396
+ if (REFUSED.test(seen.toolOutput) || seen.tools.some((t) => t.startsWith("mcp__")) && REFUSED.test(run4.stderr)) {
14371
14397
  return fail2("key-refused", "the tracker returned 401/403 to the MCP call");
14372
14398
  }
14373
14399
  if (seen.mcpFailed || !seen.tools.some((t) => t.startsWith("mcp__")) && MCP_GONE.test(`${text2}
@@ -14375,13 +14401,13 @@ ${seen.texts.join("\n")}`)) {
14375
14401
  return fail2("mcp-unavailable", "the tracker MCP tool was not available to the session");
14376
14402
  }
14377
14403
  const answered = seen.texts.length > 0 || seen.finalText;
14378
- if (SIGNED_OUT_PATTERN.test(`${run3.stderr}
14404
+ if (SIGNED_OUT_PATTERN.test(`${run4.stderr}
14379
14405
  ${seen.finalText ?? ""}
14380
14406
  ${seen.texts.join("\n")}`)) {
14381
14407
  return { failure: "login-missing", detail: signedOutMessage(spec.name, authModeOf(spec)) };
14382
14408
  }
14383
- if (!answered || LOGIN.test(run3.stderr) || LOGIN.test(seen.finalText ?? "")) {
14384
- return fail2("login-missing", `\`${bin}\` exited${run3.code !== null ? ` (${run3.code})` : ""} before answering; the vendor login is probably missing`);
14409
+ if (!answered || LOGIN.test(run4.stderr) || LOGIN.test(seen.finalText ?? "")) {
14410
+ return fail2("login-missing", `\`${bin}\` exited${run4.code !== null ? ` (${run4.code})` : ""} before answering; the vendor login is probably missing`);
14385
14411
  }
14386
14412
  return fail2("wrong-answer", `the agent replied "${(seen.finalText ?? seen.texts.at(-1) ?? "").trim().slice(0, 80)}"`);
14387
14413
  }
@@ -14411,7 +14437,7 @@ async function runSelftest(i, deps = realDeps) {
14411
14437
  };
14412
14438
  const cwd = mkdtempSync2(join33(tmpdir5(), "crew-selftest-"));
14413
14439
  try {
14414
- const run3 = await deps.run({
14440
+ const run4 = await deps.run({
14415
14441
  bin: invocation.bin,
14416
14442
  args: invocation.args,
14417
14443
  cwd,
@@ -14420,14 +14446,14 @@ async function runSelftest(i, deps = realDeps) {
14420
14446
  `,
14421
14447
  timeoutMs: i.timeoutMs ?? SELFTEST_TIMEOUT_MS
14422
14448
  });
14423
- const seen = observe(spec, run3.stdout);
14449
+ const seen = observe(spec, run4.stdout);
14424
14450
  const answer = [seen.finalText ?? "", ...seen.texts].join("\n");
14425
14451
  const usage2 = { ...seen.tokens !== void 0 ? { tokens: seen.tokens } : {}, ...seen.costUsd !== void 0 ? { costUsd: seen.costUsd } : {} };
14426
- if (!run3.spawnError && !run3.timedOut && answer.toLowerCase().includes(i.workspaceName.toLowerCase())) {
14452
+ if (!run4.spawnError && !run4.timedOut && answer.toLowerCase().includes(i.workspaceName.toLowerCase())) {
14427
14453
  const auth = spec.harness === "claude" ? ` on ${describeClaudeAuth(spec)}` : "";
14428
14454
  return finish({ ok: true, workspace: i.workspaceName, detail: `read workspace "${i.workspaceName}"${auth}`, ...usage2 });
14429
14455
  }
14430
- const { failure, detail } = classify(spec, run3, seen);
14456
+ const { failure, detail } = classify(spec, run4, seen);
14431
14457
  return finish({ ok: false, failure, detail, ...usage2 });
14432
14458
  } finally {
14433
14459
  try {
@@ -14773,7 +14799,7 @@ async function signOutSessions(o) {
14773
14799
  }
14774
14800
 
14775
14801
  // src/reset.ts
14776
- import { existsSync as existsSync32, mkdirSync as mkdirSync22, readFileSync as readFileSync31, readdirSync as readdirSync12, rmSync as rmSync18, statSync as statSync10, writeFileSync as writeFileSync23 } from "fs";
14802
+ import { existsSync as existsSync32, mkdirSync as mkdirSync22, readFileSync as readFileSync31, readdirSync as readdirSync12, rmSync as rmSync18, statSync as statSync11, writeFileSync as writeFileSync23 } from "fs";
14777
14803
  import { dirname as dirname17, join as join35 } from "path";
14778
14804
  import { hostFromUrl as hostFromUrl3 } from "@tablation/client";
14779
14805
  function clonedCheckoutsFile(stateDir) {
@@ -14871,7 +14897,7 @@ function removeState(stateDir, dryRun) {
14871
14897
  const targets = [join35(stateDir, "resolved"), join35(stateDir, "keys"), clonedCheckoutsFile(stateDir), join35(stateDir, "connect-session.json"), join35(stateDir, "reload-requested"), join35(stateDir, "daemon.started")];
14872
14898
  try {
14873
14899
  for (const name of readdirSync12(stateDir)) {
14874
- if (name.startsWith(".") && statSync10(join35(stateDir, name)).isFile()) targets.push(join35(stateDir, name));
14900
+ if (name.startsWith(".") && statSync11(join35(stateDir, name)).isFile()) targets.push(join35(stateDir, name));
14875
14901
  }
14876
14902
  } catch {
14877
14903
  }
@@ -14915,21 +14941,21 @@ async function runDeprovision(o, fx, deps) {
14915
14941
  };
14916
14942
  const afterScheduler = async () => {
14917
14943
  const steps2 = [];
14918
- for (const run3 of deps.liveRuns()) {
14919
- const target = `${run3.role} run on ${run3.route} (pid ${run3.pid})`;
14944
+ for (const run4 of deps.liveRuns()) {
14945
+ const target = `${run4.role} run on ${run4.route} (pid ${run4.pid})`;
14920
14946
  if (o.dryRun) {
14921
14947
  steps2.push({ step: "run", target, action: "would-remove" });
14922
14948
  continue;
14923
14949
  }
14924
14950
  try {
14925
- await deps.killRun(run3);
14926
- deps.recordKill(run3);
14951
+ await deps.killRun(run4);
14952
+ deps.recordKill(run4);
14927
14953
  } catch (e) {
14928
14954
  steps2.push({ step: "run", target, action: "failed", detail: e.message });
14929
14955
  continue;
14930
14956
  }
14931
14957
  try {
14932
- await deps.handBack(run3);
14958
+ await deps.handBack(run4);
14933
14959
  steps2.push({ step: "run", target, action: "removed", detail: "killed" });
14934
14960
  } catch (e) {
14935
14961
  steps2.push({ step: "run", target, action: "removed", detail: `killed; could not tell its ticket (${e.message})` });
@@ -17182,6 +17208,191 @@ ${waiting.map((t) => `| ${displayKey2(t)} | ${t.status} | ${blockers(t, i)} |`).
17182
17208
  ]);
17183
17209
  }
17184
17210
 
17211
+ // src/sandbox-hygiene.ts
17212
+ import { execFile as execFile3 } from "child_process";
17213
+ import { existsSync as existsSync37, statfsSync as statfsSync2 } from "fs";
17214
+ import { promisify as promisify3 } from "util";
17215
+ var execFileP3 = promisify3(execFile3);
17216
+ var REAP_MIN_AGE_MS = 5 * 6e4;
17217
+ var LEAK_CLEAR_AFTER_MS = 60 * 6e4;
17218
+ var DISK_WARN_PERCENT = 85;
17219
+ var DISK_STOP_PERCENT = 95;
17220
+ var DISK_RESUME_PERCENT = 90;
17221
+ var HYGIENE_INTERVAL_MS = 3e4;
17222
+ var SANDBOX_LEAK_KEY = "sandbox_leak";
17223
+ var DISK_PRESSURE_KEY = "disk_pressure";
17224
+ var DISK_FULL_KEY = "disk_full";
17225
+ var SANDBOX_IN_CONTAINER = /crew-[0-9a-z]{14}/;
17226
+ function parseDockerCreatedAt(s) {
17227
+ const m = /^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})(?:\.\d+)? ([+-])(\d{2})(\d{2})/.exec(s.trim());
17228
+ if (!m) return null;
17229
+ const t = Date.parse(`${m[1]}T${m[2]}${m[3]}${m[4]}:${m[5]}`);
17230
+ return Number.isNaN(t) ? null : t;
17231
+ }
17232
+ async function reapOrphanContainers(d, minAgeMs = REAP_MIN_AGE_MS) {
17233
+ const gateway = await d.gatewaySandboxes();
17234
+ if (gateway === null) return [];
17235
+ const known = /* @__PURE__ */ new Set([...gateway, ...d.liveSandboxes()]);
17236
+ const prefix = `openshell-${d.workspace}--`;
17237
+ const out = [];
17238
+ for (const c of await d.containers()) {
17239
+ if (!c.name.startsWith(prefix)) continue;
17240
+ const sandbox = SANDBOX_IN_CONTAINER.exec(c.name)?.[0];
17241
+ if (!sandbox || known.has(sandbox)) continue;
17242
+ const ageMs = d.now() - c.createdMs;
17243
+ if (ageMs < minAgeMs) continue;
17244
+ await d.remove(c.name);
17245
+ out.push({ container: c.name, ageMs });
17246
+ }
17247
+ return out;
17248
+ }
17249
+ function usedPercentAt(path) {
17250
+ try {
17251
+ const s = statfsSync2(path);
17252
+ const used = Number(s.blocks) - Number(s.bfree);
17253
+ const total = used + Number(s.bavail);
17254
+ return total > 0 ? used / total * 100 : null;
17255
+ } catch {
17256
+ return null;
17257
+ }
17258
+ }
17259
+ function fullest(readings) {
17260
+ return readings.reduce((a, r) => !a || r.percent > a.percent ? r : a, null);
17261
+ }
17262
+ function diskVerdict(percent, stopped) {
17263
+ if (percent >= DISK_STOP_PERCENT || stopped && percent >= DISK_RESUME_PERCENT) return "stop";
17264
+ return percent >= DISK_WARN_PERCENT ? "warn" : "ok";
17265
+ }
17266
+ async function checkDisk(o, d, nowIso = (/* @__PURE__ */ new Date()).toISOString()) {
17267
+ const raise = (item) => raiseShipAttention({ state: o.state, emit: o.emit, ship: o.ship, ...o.route ? { route: o.route } : {} }, item);
17268
+ const stopped = openShipAttention(o.state).some((i) => i.key === DISK_FULL_KEY);
17269
+ let worst = fullest(await d.readings());
17270
+ if (!worst) return;
17271
+ let verdict = diskVerdict(worst.percent, stopped);
17272
+ if (verdict === "stop" && !stopped) {
17273
+ await d.reclaim();
17274
+ worst = fullest(await d.readings()) ?? worst;
17275
+ verdict = diskVerdict(worst.percent, false);
17276
+ }
17277
+ const pct = `${Math.round(worst.percent)}%`;
17278
+ if (verdict === "stop") {
17279
+ clearShipAttention(o.state, DISK_PRESSURE_KEY);
17280
+ await raise({
17281
+ kind: "disk_full",
17282
+ key: DISK_FULL_KEY,
17283
+ since: nowIso,
17284
+ message: `${worst.path} is ${pct} full \u2014 no agent run or sandbox image build starts until it is below ${DISK_RESUME_PERCENT}%. Resumes automatically once space is freed`
17285
+ });
17286
+ } else if (verdict === "warn") {
17287
+ clearShipAttention(o.state, DISK_FULL_KEY);
17288
+ await raise({
17289
+ kind: "disk_pressure",
17290
+ key: DISK_PRESSURE_KEY,
17291
+ since: nowIso,
17292
+ message: `${worst.path} is ${pct} full \u2014 runs stop at ${DISK_STOP_PERCENT}%. Resumes normal reporting once it is below ${DISK_WARN_PERCENT}%`
17293
+ });
17294
+ } else {
17295
+ clearShipAttention(o.state, DISK_FULL_KEY);
17296
+ clearShipAttention(o.state, DISK_PRESSURE_KEY);
17297
+ }
17298
+ }
17299
+ async function reportReaped(o, reaped, nowMs = Date.now()) {
17300
+ const prior = openShipAttention(o.state).find((i) => i.key === SANDBOX_LEAK_KEY);
17301
+ if (reaped.length === 0) {
17302
+ if (prior?.lastReapedAt && nowMs - Date.parse(prior.lastReapedAt) > LEAK_CLEAR_AFTER_MS) clearShipAttention(o.state, SANDBOX_LEAK_KEY);
17303
+ return;
17304
+ }
17305
+ for (const r of reaped) {
17306
+ o.emit.warn(`sandbox_reaped: removed ${r.container} (${Math.round(r.ageMs / 6e4)} min old, no live run)`, {
17307
+ data: { event: "sandbox_reaped", container: r.container, ageMs: r.ageMs }
17308
+ });
17309
+ }
17310
+ const total = (prior?.count ?? 0) + reaped.length;
17311
+ await raiseShipAttention(o, {
17312
+ kind: "sandbox_leak",
17313
+ key: SANDBOX_LEAK_KEY,
17314
+ since: new Date(nowMs).toISOString(),
17315
+ count: total,
17316
+ lastReapedAt: new Date(nowMs).toISOString(),
17317
+ message: `${total} sandbox container(s) with no live run have been removed from this ship (latest: ${reaped.length} just now) \u2014 something created them outside a run; see the sandbox_reaped events`
17318
+ });
17319
+ }
17320
+ async function run3(bin, args) {
17321
+ return (await execFileP3(bin, args, { timeout: 6e4, maxBuffer: 16 * 1024 * 1024 })).stdout;
17322
+ }
17323
+ function realReapDeps(ship) {
17324
+ const engine = ship.sandbox?.engine ?? DEFAULT_CACHE_SETTINGS.engine;
17325
+ const osBin = ship.sandbox?.bin ?? "openshell";
17326
+ return {
17327
+ workspace: ship.sandbox?.cacheWorkspace ?? DEFAULT_CACHE_SETTINGS.workspace,
17328
+ containers: async () => {
17329
+ const out = await run3(engine, ["ps", "-a", "--no-trunc", "--format", "{{.Names}} {{.CreatedAt}}"]);
17330
+ const rows = [];
17331
+ for (const line of out.split("\n")) {
17332
+ const [name, created] = line.split(" ");
17333
+ const createdMs = created ? parseDockerCreatedAt(created) : null;
17334
+ if (name && createdMs !== null) rows.push({ name, createdMs });
17335
+ }
17336
+ return rows;
17337
+ },
17338
+ gatewaySandboxes: async () => {
17339
+ try {
17340
+ return [...(await run3(osBin, ["sandbox", "list"])).matchAll(/crew-[0-9a-z]{14}/g)].map((m) => m[0]);
17341
+ } catch {
17342
+ return null;
17343
+ }
17344
+ },
17345
+ liveSandboxes: () => liveRuns(ship.stateDir).flatMap((r) => r.sandbox ? [r.sandbox] : []),
17346
+ remove: async (name) => {
17347
+ await run3(engine, ["rm", "-f", name]);
17348
+ },
17349
+ now: () => Date.now()
17350
+ };
17351
+ }
17352
+ async function realDiskReadings(ship) {
17353
+ const paths = ["/"];
17354
+ try {
17355
+ const root = (await run3(ship.sandbox?.engine ?? DEFAULT_CACHE_SETTINGS.engine, ["info", "--format", "{{.DockerRootDir}}"])).trim();
17356
+ if (root && existsSync37(root)) paths.push(root);
17357
+ } catch {
17358
+ }
17359
+ return paths.flatMap((path) => {
17360
+ const percent = usedPercentAt(path);
17361
+ return percent === null ? [] : [{ path, percent }];
17362
+ });
17363
+ }
17364
+ function makeSandboxHygiene(o) {
17365
+ const now = o.now ?? Date.now;
17366
+ let last = -Infinity;
17367
+ return async () => {
17368
+ if (now() - last < HYGIENE_INTERVAL_MS) return;
17369
+ last = now();
17370
+ const deps = realReapDeps(o.ship);
17371
+ try {
17372
+ await reportReaped(o, await reapOrphanContainers(deps), now());
17373
+ } catch (e) {
17374
+ o.emit.warn(`sandbox reaper failed: ${e instanceof Error ? e.message : String(e)}`);
17375
+ }
17376
+ try {
17377
+ await checkDisk(o, {
17378
+ readings: () => realDiskReadings(o.ship),
17379
+ reclaim: async () => {
17380
+ await reportReaped(o, await reapOrphanContainers(deps), now());
17381
+ try {
17382
+ await run3(o.ship.sandbox?.engine ?? DEFAULT_CACHE_SETTINGS.engine, ["builder", "prune", "-f"]);
17383
+ } catch {
17384
+ }
17385
+ }
17386
+ });
17387
+ } catch (e) {
17388
+ o.emit.warn(`disk check failed: ${e instanceof Error ? e.message : String(e)}`);
17389
+ }
17390
+ };
17391
+ }
17392
+ function diskFullStop(state) {
17393
+ return openShipAttention(state).find((i) => i.kind === "disk_full")?.message ?? null;
17394
+ }
17395
+
17185
17396
  // src/poll.ts
17186
17397
  import { writeFileSync as writeFileSync28 } from "fs";
17187
17398
  import { join as join40 } from "path";
@@ -17437,8 +17648,9 @@ async function decideCycle(o) {
17437
17648
  await checkRepoDisks({ state, emit, route: route2, ship });
17438
17649
  const floorStop = await checkCrewFloor({ state, emit, route: route2, ship });
17439
17650
  const itemStop = repoStopFor(openShipAttention(state), route2);
17651
+ const diskStop = diskFullStop(state);
17440
17652
  const selectionInput = {
17441
- repoStop: floorStop ? () => floorStop : itemStop,
17653
+ repoStop: floorStop ? () => floorStop : diskStop ? () => diskStop : itemStop,
17442
17654
  workModes,
17443
17655
  tickets,
17444
17656
  comments,
@@ -17683,7 +17895,7 @@ async function resolveOne(tracker, t, seat, approvedStatus, buildingStatus, affi
17683
17895
  }
17684
17896
 
17685
17897
  // src/repo-refresh.ts
17686
- import { existsSync as existsSync37, mkdirSync as mkdirSync26, readFileSync as readFileSync36, writeFileSync as writeFileSync29 } from "fs";
17898
+ import { existsSync as existsSync38, mkdirSync as mkdirSync26, readFileSync as readFileSync36, writeFileSync as writeFileSync29 } from "fs";
17687
17899
  import { dirname as dirname21 } from "path";
17688
17900
  var REFRESH_COOLDOWN_MS = 2 * 6e4;
17689
17901
  var UNSERVABLE_PASSES_BEFORE_ATTENTION = 3;
@@ -17713,7 +17925,7 @@ function applyRepoRows(resolved, rows) {
17713
17925
  }
17714
17926
  function persistRepoRows(stateDir, routeName, rows) {
17715
17927
  const path = resolvedPathFor(stateDir, routeName);
17716
- if (!existsSync37(path)) return;
17928
+ if (!existsSync38(path)) return;
17717
17929
  const raw = JSON.parse(readFileSync36(path, "utf8"));
17718
17930
  applyRepoRows(raw, rows);
17719
17931
  mkdirSync26(dirname21(path), { recursive: true });
@@ -18168,12 +18380,12 @@ var localRefSkipReported = (ticket, problem, events) => events.some((e) => e.rec
18168
18380
 
18169
18381
  // src/connect-wizard.ts
18170
18382
  import { delimiter, dirname as dirname22, join as join41 } from "path";
18171
- import { accessSync as accessSync3, constants as constants3, existsSync as existsSync38, mkdirSync as mkdirSync27, writeFileSync as writeFileSync30 } from "fs";
18383
+ import { accessSync as accessSync3, constants as constants3, existsSync as existsSync39, mkdirSync as mkdirSync27, writeFileSync as writeFileSync30 } from "fs";
18172
18384
  import { stringify as stringify3 } from "yaml";
18173
18385
  var HOST_PASSENGERS_DOCS_URL = "https://crew.tablation.dev/host-passengers";
18174
18386
  function shouldRunWizard(opts) {
18175
18387
  if (!opts.isTTY) return false;
18176
- const exists = opts.configExists ?? existsSync38;
18388
+ const exists = opts.configExists ?? existsSync39;
18177
18389
  return !configSearchPath(opts.crewHome).some((p) => exists(p));
18178
18390
  }
18179
18391
  function firstRunConfigPath() {
@@ -18367,7 +18579,7 @@ function flagWizardAnswers(f, env) {
18367
18579
  }
18368
18580
 
18369
18581
  // src/diagnostics.ts
18370
- import { execFile as execFile3 } from "child_process";
18582
+ import { execFile as execFile4 } from "child_process";
18371
18583
  var BUNDLE_BUDGET_MS = 3e4;
18372
18584
  var JOURNAL_LINES = 200;
18373
18585
  var MAX_SECTION_BYTES = 256 * 1024;
@@ -18392,7 +18604,7 @@ function redactValue(v) {
18392
18604
  return v;
18393
18605
  }
18394
18606
  var defaultExec = (bin, args, timeoutMs) => new Promise((resolve8, reject) => {
18395
- execFile3(bin, args, { timeout: timeoutMs, maxBuffer: 4 * 1024 * 1024 }, (e, stdout) => {
18607
+ execFile4(bin, args, { timeout: timeoutMs, maxBuffer: 4 * 1024 * 1024 }, (e, stdout) => {
18396
18608
  if (e && e.code === "ENOENT") return reject(new Error(`${bin} is not installed`));
18397
18609
  if (e && e.killed) return reject(new Error(`${bin} timed out`));
18398
18610
  resolve8({ stdout: String(stdout), code: typeof e?.code === "number" ? e.code : 0 });
@@ -18439,9 +18651,9 @@ async function collectDiagnostics(d) {
18439
18651
  const deadline = new Promise((resolve8) => {
18440
18652
  setTimeout(() => resolve8("timeout"), budget).unref();
18441
18653
  });
18442
- const entries = await Promise.all(Object.entries(sections).map(async ([name, run3]) => {
18654
+ const entries = await Promise.all(Object.entries(sections).map(async ([name, run4]) => {
18443
18655
  try {
18444
- const out = await Promise.race([run3(), deadline]);
18656
+ const out = await Promise.race([run4(), deadline]);
18445
18657
  if (out === "timeout") return [name, { ok: false, error: `timed out after ${Math.round(budget / 1e3)}s` }];
18446
18658
  return [name, { ok: true, data: redactValue(out) }];
18447
18659
  } catch (e) {
@@ -18452,7 +18664,7 @@ async function collectDiagnostics(d) {
18452
18664
  }
18453
18665
 
18454
18666
  // src/release-run.ts
18455
- import { readFileSync as readFileSync37, writeFileSync as writeFileSync31, existsSync as existsSync39, copyFileSync, mkdirSync as mkdirSync28, mkdtempSync as mkdtempSync3, rmSync as rmSync19 } from "fs";
18667
+ import { readFileSync as readFileSync37, writeFileSync as writeFileSync31, existsSync as existsSync40, copyFileSync, mkdirSync as mkdirSync28, mkdtempSync as mkdtempSync3, rmSync as rmSync19 } from "fs";
18456
18668
  import { dirname as dirname24, join as join43 } from "path";
18457
18669
  import { tmpdir as tmpdir6, hostname as hostname4 } from "os";
18458
18670
 
@@ -19237,7 +19449,7 @@ async function bump(o, size) {
19237
19449
  }
19238
19450
  const files = o.repo.release.versionFiles.map((f) => join43(o.cwd, f));
19239
19451
  const first = files[0];
19240
- if (!existsAt(first, existsSync39)) {
19452
+ if (!existsAt(first, existsSync40)) {
19241
19453
  o.emit.error(`no ${o.repo.release.versionFiles[0]} to read a version from`);
19242
19454
  return null;
19243
19455
  }
@@ -19279,7 +19491,7 @@ function writeChangelog(o, version, entries) {
19279
19491
  o.emit.emit(`would prepend ${entries.length} entr(ies) to ${file}`);
19280
19492
  return;
19281
19493
  }
19282
- const existing = existsAt(path, existsSync39) ? readTextAt(path, (p) => readFileSync37(p, "utf8")) : "# Changelog\n";
19494
+ const existing = existsAt(path, existsSync40) ? readTextAt(path, (p) => readFileSync37(p, "utf8")) : "# Changelog\n";
19283
19495
  writeTextAt(path, insertChangelogSection(existing, section), writeFileSync31);
19284
19496
  }
19285
19497
  async function confirm(o, expected) {
@@ -19358,15 +19570,15 @@ async function confirmLastRelease(o, decision) {
19358
19570
  if (!confirmed) o.emit.warn(`${decision.lastTag} is still not confirmed live \u2014 tickets stay verified`);
19359
19571
  return { confirmed, version };
19360
19572
  }
19361
- function closeReleaseCheckout(cwd, root, dir, branch, run3 = gitOk) {
19573
+ function closeReleaseCheckout(cwd, root, dir, branch, run4 = gitOk) {
19362
19574
  try {
19363
- run3(cwd, ["worktree", "remove", "--force", dir]);
19575
+ run4(cwd, ["worktree", "remove", "--force", dir]);
19364
19576
  } finally {
19365
19577
  try {
19366
19578
  rmSync19(root, { recursive: true, force: true });
19367
19579
  } finally {
19368
- run3(cwd, ["worktree", "prune"]);
19369
- run3(cwd, ["branch", "-D", branch]);
19580
+ run4(cwd, ["worktree", "prune"]);
19581
+ run4(cwd, ["branch", "-D", branch]);
19370
19582
  }
19371
19583
  }
19372
19584
  }
@@ -19385,7 +19597,7 @@ function openReleaseCheckout(o) {
19385
19597
  }
19386
19598
  for (const f of o.repo.worktrees.copy) {
19387
19599
  const src = join43(o.cwd, f);
19388
- if (!existsSync39(src)) continue;
19600
+ if (!existsSync40(src)) continue;
19389
19601
  mkdirSync28(dirname24(join43(dir, f)), { recursive: true });
19390
19602
  copyFileSync(src, join43(dir, f));
19391
19603
  }
@@ -20222,7 +20434,7 @@ function runForge(a, io) {
20222
20434
  }
20223
20435
 
20224
20436
  // src/mirror-contract.ts
20225
- import { existsSync as existsSync40 } from "fs";
20437
+ import { existsSync as existsSync41 } from "fs";
20226
20438
 
20227
20439
  // src/passenger-mirror.ts
20228
20440
  import { mkdirSync as mkdirSync29 } from "fs";
@@ -20263,7 +20475,7 @@ function mirrorOutcome(m) {
20263
20475
 
20264
20476
  // src/mirror-contract.ts
20265
20477
  function lacksCheckout(ship, dir) {
20266
- return ship.runner === "sandbox" && !existsSync40(dir) && !remoteOf(dir);
20478
+ return ship.runner === "sandbox" && !existsSync41(dir) && !remoteOf(dir);
20267
20479
  }
20268
20480
  function skipsHostCheckout(ship) {
20269
20481
  return ship.runner === "sandbox";
@@ -20343,11 +20555,11 @@ function explainRefusal(readable, unreadable) {
20343
20555
  }
20344
20556
 
20345
20557
  // src/release-sandbox.ts
20346
- import { execFile as execFile4 } from "child_process";
20558
+ import { execFile as execFile5 } from "child_process";
20347
20559
  import { mkdirSync as mkdirSync30, writeFileSync as writeFileSync32 } from "fs";
20348
20560
  import { dirname as dirname26 } from "path";
20349
- import { promisify as promisify3 } from "util";
20350
- var execFileP3 = promisify3(execFile4);
20561
+ import { promisify as promisify4 } from "util";
20562
+ var execFileP4 = promisify4(execFile5);
20351
20563
  var RELEASE_CLONE_DEPTH = 50;
20352
20564
  var FORGE_TOKEN_VAR = "CREW_FORGE_TOKEN";
20353
20565
  var FORGE_USER_VAR = "CREW_FORGE_USER";
@@ -20384,7 +20596,7 @@ function releaseCloneScript(o) {
20384
20596
  var endpointsOf = (g) => g.groups.flatMap((x) => x.endpoints.map((e) => `${e.host}:${e.port}`));
20385
20597
  async function openReleaseSandbox(o) {
20386
20598
  const cfg = { ...DEFAULT_SANDBOX_CONFIG, ...o.sandbox };
20387
- const run3 = o.exec ?? ((bin, args, env) => execFileP3(bin, args, { env, maxBuffer: 16 * 1024 * 1024 }));
20599
+ const run4 = o.exec ?? ((bin, args, env) => execFileP4(bin, args, { env, maxBuffer: 16 * 1024 * 1024 }));
20388
20600
  const name = sandboxName({ route: o.route, role: "release", ticket: o.repoName }, o.now?.());
20389
20601
  let policyFile = cfg.policy;
20390
20602
  let generated;
@@ -20403,6 +20615,7 @@ async function openReleaseSandbox(o) {
20403
20615
  }
20404
20616
  const create2 = ["sandbox", "create", "--name", name, "--detach"];
20405
20617
  if (policyFile) create2.push("--policy", policyFile);
20618
+ for (const l of sandboxLabels({ role: "release", run: name })) create2.push("--label", l);
20406
20619
  const image = cfg.image ?? o.image;
20407
20620
  if (image) create2.push("--from", image);
20408
20621
  if (cfg.cacheVolume) {
@@ -20415,12 +20628,12 @@ async function openReleaseSandbox(o) {
20415
20628
  const t0 = Date.now();
20416
20629
  const deleteQuietly = async () => {
20417
20630
  try {
20418
- await run3(cfg.bin, ["sandbox", "delete", name], process.env);
20631
+ await run4(cfg.bin, ["sandbox", "delete", name], process.env);
20419
20632
  } catch {
20420
20633
  }
20421
20634
  };
20422
20635
  try {
20423
- await run3(cfg.bin, create2, secrets);
20636
+ await run4(cfg.bin, create2, secrets);
20424
20637
  } catch (e) {
20425
20638
  await deleteQuietly();
20426
20639
  throw new Error(`openshell could not create the release sandbox: ${describe(e)}`);
@@ -20434,7 +20647,7 @@ async function openReleaseSandbox(o) {
20434
20647
  }
20435
20648
  const closeSandbox = async () => {
20436
20649
  try {
20437
- const { stdout } = await run3(cfg.bin, ["logs", name], process.env);
20650
+ const { stdout } = await run4(cfg.bin, ["logs", name], process.env);
20438
20651
  for (const d of parseDeniedRequests(stdout)) {
20439
20652
  const where = `${d.host}${d.port !== void 0 ? `:${d.port}` : ""}${d.binary ? ` by ${d.binary}` : ""}`;
20440
20653
  o.emit.warn(`sandbox_denied: ${where}${d.count > 1 ? ` (${d.count}x)` : ""} \u2014 blocked by the sandbox policy`, { data: { event: "sandbox_denied", sandbox: name, ...d } });
@@ -20456,7 +20669,7 @@ async function openReleaseSandbox(o) {
20456
20669
  tagPattern: o.tagPattern
20457
20670
  })}
20458
20671
  ${containerEngineStubScript()}`;
20459
- await run3(cfg.bin, ["sandbox", "exec", "-n", name, "--no-login-shell", "--", "sh", "-c", clone], process.env);
20672
+ await run4(cfg.bin, ["sandbox", "exec", "-n", name, "--no-login-shell", "--", "sh", "-c", clone], process.env);
20460
20673
  } catch (e) {
20461
20674
  await closeSandbox();
20462
20675
  throw new Error(`could not make the release clone in ${name}: ${describe(e)}`);
@@ -20557,7 +20770,7 @@ function missingReleaserWarning(repo, release, ships, now = Date.now()) {
20557
20770
  }
20558
20771
 
20559
20772
  // src/watch.ts
20560
- import { watch as watchFile, existsSync as existsSync41, statSync as statSync11, openSync as openSync5, readSync as readSync2, closeSync as closeSync5 } from "fs";
20773
+ import { watch as watchFile, existsSync as existsSync42, statSync as statSync12, openSync as openSync5, readSync as readSync2, closeSync as closeSync5 } from "fs";
20561
20774
  var E = "\x1B[";
20562
20775
  var dim = (s) => `${E}2m${s}${E}0m`;
20563
20776
  var bold = (s) => `${E}1m${s}${E}0m`;
@@ -20658,8 +20871,8 @@ function renderHeaders(states, now = Date.now()) {
20658
20871
  return states.map((s) => renderHeader(s, now)).join("");
20659
20872
  }
20660
20873
  function readFrom(file, from) {
20661
- if (!existsSync41(file)) return { events: [], offset: from };
20662
- const size = statSync11(file).size;
20874
+ if (!existsSync42(file)) return { events: [], offset: from };
20875
+ const size = statSync12(file).size;
20663
20876
  if (size < from) return readFrom(file, 0);
20664
20877
  if (size === from) return { events: [], offset: from };
20665
20878
  const fd = openSync5(file, "r");
@@ -20901,7 +21114,7 @@ function nextRoles(decision, ran) {
20901
21114
  }
20902
21115
 
20903
21116
  // src/ship-name.ts
20904
- import { existsSync as existsSync42, mkdirSync as mkdirSync31, readFileSync as readFileSync38, renameSync as renameSync5, writeFileSync as writeFileSync33 } from "fs";
21117
+ import { existsSync as existsSync43, mkdirSync as mkdirSync31, readFileSync as readFileSync38, renameSync as renameSync5, writeFileSync as writeFileSync33 } from "fs";
20905
21118
  import { dirname as dirname27 } from "path";
20906
21119
  import { parseDocument as parseDocument5 } from "yaml";
20907
21120
  var ShipNameError = class extends Error {
@@ -20963,7 +21176,7 @@ async function syncRouteName(i) {
20963
21176
  return { status: "ok", ...base, action, name: i.local };
20964
21177
  }
20965
21178
  function readSyncedName(resolvedFile) {
20966
- if (!existsSync42(resolvedFile)) return void 0;
21179
+ if (!existsSync43(resolvedFile)) return void 0;
20967
21180
  try {
20968
21181
  const v = JSON.parse(readFileSync38(resolvedFile, "utf8")).shipName;
20969
21182
  return typeof v === "string" ? v : void 0;
@@ -20972,7 +21185,7 @@ function readSyncedName(resolvedFile) {
20972
21185
  }
20973
21186
  }
20974
21187
  function writeSyncedName(resolvedFile, name) {
20975
- if (!existsSync42(resolvedFile)) return;
21188
+ if (!existsSync43(resolvedFile)) return;
20976
21189
  let raw;
20977
21190
  try {
20978
21191
  raw = JSON.parse(readFileSync38(resolvedFile, "utf8"));
@@ -21674,7 +21887,7 @@ function describeCapability(i) {
21674
21887
  }
21675
21888
 
21676
21889
  // src/agents-sync-run.ts
21677
- import { existsSync as existsSync43, mkdirSync as mkdirSync32, readFileSync as readFileSync39, writeFileSync as writeFileSync34 } from "fs";
21890
+ import { existsSync as existsSync44, mkdirSync as mkdirSync32, readFileSync as readFileSync39, writeFileSync as writeFileSync34 } from "fs";
21678
21891
  import { dirname as dirname28 } from "path";
21679
21892
  async function runAgentsSync(target, o) {
21680
21893
  const dryRun = o.dryRun ?? false;
@@ -21708,7 +21921,7 @@ async function runAgentsSync(target, o) {
21708
21921
  for (const s of skillResult?.outcomes ?? []) o.say(describeSkillSyncOutcome(s));
21709
21922
  if (!dryRun) {
21710
21923
  const resolvedPath = resolvedPathFor(o.stateDir, target.route);
21711
- const raw = existsSync43(resolvedPath) ? JSON.parse(readFileSync39(resolvedPath, "utf8")) : {};
21924
+ const raw = existsSync44(resolvedPath) ? JSON.parse(readFileSync39(resolvedPath, "utf8")) : {};
21712
21925
  raw.agentPersonas = personaResult.agentPersonas;
21713
21926
  if (skillResult) raw.agentSkills = skillResult.agentSkills;
21714
21927
  if (personaResult.releaseAgentId) raw.releaseAgentId = personaResult.releaseAgentId;
@@ -21856,21 +22069,21 @@ var POSIX_SHELL = /^(?:ba|z|da|k|a|mk)?sh$|^fish$/;
21856
22069
  function checkHookSyntax(script, shell) {
21857
22070
  const spec = resolveShell(shell);
21858
22071
  const name = basename11(spec.bin).replace(/\.exe$/i, "").toLowerCase();
21859
- let run3;
22072
+ let run4;
21860
22073
  if (POSIX_SHELL.test(name)) {
21861
- run3 = spawnSync11(spec.bin, ["-n"], { input: script, encoding: "utf8" });
22074
+ run4 = spawnSync11(spec.bin, ["-n"], { input: script, encoding: "utf8" });
21862
22075
  } else if (/^(pwsh|powershell)$/.test(name)) {
21863
22076
  const parse3 = "$e=$null;[void][System.Management.Automation.Language.Parser]::ParseInput($env:CREW_CHECK_SCRIPT,[ref]$null,[ref]$e);if($e){$e|ForEach-Object{[Console]::Error.WriteLine($_.Message)};exit 1}";
21864
- run3 = spawnSync11(spec.bin, ["-NoProfile", "-NonInteractive", "-Command", parse3], {
22077
+ run4 = spawnSync11(spec.bin, ["-NoProfile", "-NonInteractive", "-Command", parse3], {
21865
22078
  encoding: "utf8",
21866
22079
  env: { ...process.env, CREW_CHECK_SCRIPT: script }
21867
22080
  });
21868
22081
  } else {
21869
22082
  return { status: "unchecked", message: `no syntax check for ${spec.bin}` };
21870
22083
  }
21871
- if (run3.error) return { status: "unchecked", message: `cannot run ${spec.bin}: ${run3.error.message}` };
21872
- if (run3.status === 0) return { status: "ok" };
21873
- const message = `${run3.stderr ?? ""}${run3.stdout ?? ""}`.trim() || `${spec.bin} exited ${run3.status}`;
22084
+ if (run4.error) return { status: "unchecked", message: `cannot run ${spec.bin}: ${run4.error.message}` };
22085
+ if (run4.status === 0) return { status: "ok" };
22086
+ const message = `${run4.stderr ?? ""}${run4.stdout ?? ""}`.trim() || `${spec.bin} exited ${run4.status}`;
21874
22087
  return { status: "error", message };
21875
22088
  }
21876
22089
  function renderSamples(cfg, dir) {
@@ -22301,7 +22514,7 @@ async function runAgentSuggest(o) {
22301
22514
  const before = porcelain(o.dir);
22302
22515
  const timeout = AbortSignal.timeout(o.timeoutMs ?? DEFAULT_TIMEOUT_MS);
22303
22516
  const signal = o.signal ? AbortSignal.any([o.signal, timeout]) : timeout;
22304
- const run3 = await new Promise((resolve8) => {
22517
+ const run4 = await new Promise((resolve8) => {
22305
22518
  let out = "";
22306
22519
  let err3 = "";
22307
22520
  const child = spawn8(bin, args, { cwd: o.dir, env, detached: true, stdio: ["pipe", "pipe", "pipe"] });
@@ -22336,18 +22549,18 @@ async function runAgentSuggest(o) {
22336
22549
  });
22337
22550
  child.stdin.end(buildAgentPrompt(o.sniff));
22338
22551
  });
22339
- if (run3.aborted || signal.aborted) {
22552
+ if (run4.aborted || signal.aborted) {
22340
22553
  throw new AgentSuggestError(o.signal?.aborted ? "cancelled" : "timeout", o.signal?.aborted ? "cancelled" : "the toolchain did not answer in time");
22341
22554
  }
22342
22555
  const after = porcelain(o.dir);
22343
22556
  if (before !== void 0 && after !== before) {
22344
22557
  throw new AgentSuggestError("modified_checkout", "the checkout changed during --agent; inspect it with `git status` (the agent result was discarded)");
22345
22558
  }
22346
- const parsed = parseAgentStream(run3.out, o.dir);
22347
- if (run3.spawnError || run3.code !== 0 || parsed.isError) {
22348
- const reason = classifyFailure({ code: run3.code, ...run3.spawnError ? { spawnError: run3.spawnError } : {}, output: `${parsed.text}
22349
- ${run3.err}` });
22350
- throw new AgentSuggestError(reason, reason === "not_installed" ? `${bin} is not installed` : reason === "not_signed_in" ? `${o.spec.name} is not signed in` : (parsed.text || run3.err).trim().slice(0, 300) || `exited ${run3.code}`);
22559
+ const parsed = parseAgentStream(run4.out, o.dir);
22560
+ if (run4.spawnError || run4.code !== 0 || parsed.isError) {
22561
+ const reason = classifyFailure({ code: run4.code, ...run4.spawnError ? { spawnError: run4.spawnError } : {}, output: `${parsed.text}
22562
+ ${run4.err}` });
22563
+ throw new AgentSuggestError(reason, reason === "not_installed" ? `${bin} is not installed` : reason === "not_signed_in" ? `${o.spec.name} is not signed in` : (parsed.text || run4.err).trim().slice(0, 300) || `exited ${run4.code}`);
22351
22564
  }
22352
22565
  const { hooks, notes } = parseAgentHooks(parsed.text);
22353
22566
  const differsFromSniff = HOOK_KEYS2.filter((k) => hooks[k] !== void 0 && hooks[k] !== o.sniff.hooks[k]);
@@ -22423,7 +22636,7 @@ function planSampleTicket(i) {
22423
22636
  }
22424
22637
 
22425
22638
  // src/worktree-sweep.ts
22426
- import { existsSync as existsSync44, readFileSync as readFileSync41, readdirSync as readdirSync14 } from "fs";
22639
+ import { existsSync as existsSync45, readFileSync as readFileSync41, readdirSync as readdirSync14 } from "fs";
22427
22640
  import { basename as basename13, dirname as dirname30, join as join45, resolve as resolve5 } from "path";
22428
22641
  function planWorktreeSweep(target, tickets, contract) {
22429
22642
  const terminal = new Set(contract.statuses.resolved.filter((s) => s !== contract.statuses.verified));
@@ -22536,7 +22749,7 @@ async function applyWorktreeSweep(cwd, actions, dryRun, log, remote = "origin",
22536
22749
  let removed = 0;
22537
22750
  let keptBranches = 0;
22538
22751
  for (const a of actions) {
22539
- if (!dryRun && base && !a.keepBranch && existsSync44(a.path) && isHandBackMerge(a.path, base)) {
22752
+ if (!dryRun && base && !a.keepBranch && existsSync45(a.path) && isHandBackMerge(a.path, base)) {
22540
22753
  if (gitOk(a.path, ["merge", "--abort"]) !== null) {
22541
22754
  log.emit(
22542
22755
  `abandoned the hand-back merge of ${base} in ${a.path}: ${a.ticket.issue_id} deployed without it`,
@@ -22544,7 +22757,7 @@ async function applyWorktreeSweep(cwd, actions, dryRun, log, remote = "origin",
22544
22757
  );
22545
22758
  }
22546
22759
  }
22547
- if (!dryRun && existsSync44(a.path)) {
22760
+ if (!dryRun && existsSync45(a.path)) {
22548
22761
  let dirty = false;
22549
22762
  try {
22550
22763
  dirty = status(a.path).length > 0;
@@ -22555,7 +22768,7 @@ async function applyWorktreeSweep(cwd, actions, dryRun, log, remote = "origin",
22555
22768
  continue;
22556
22769
  }
22557
22770
  }
22558
- if (!dryRun && a.requirePushed && a.branch && existsSync44(a.path) && remoteConfigured(cwd, remote) && worktreeHoldsUnpushed(a.path, remote)) {
22771
+ if (!dryRun && a.requirePushed && a.branch && existsSync45(a.path) && remoteConfigured(cwd, remote) && worktreeHoldsUnpushed(a.path, remote)) {
22559
22772
  refuse2(a, "unpushed commits", `${a.branch} has commits that are not on ${remote}`);
22560
22773
  continue;
22561
22774
  }
@@ -22709,16 +22922,16 @@ function applyRemoteBranchCleanup(cwd, remote, branches2, dryRun, log) {
22709
22922
  }
22710
22923
 
22711
22924
  // src/stream-sweep.ts
22712
- import { existsSync as existsSync45, readdirSync as readdirSync15, rmSync as rmSync20, statSync as statSync12 } from "fs";
22925
+ import { existsSync as existsSync46, readdirSync as readdirSync15, rmSync as rmSync20, statSync as statSync13 } from "fs";
22713
22926
  import { join as join46 } from "path";
22714
22927
  var DAY_MS2 = 24 * 60 * 60 * 1e3;
22715
22928
  function planStreamSweep(stateDir, retentionDays, now = Date.now()) {
22716
22929
  const dir = join46(stateDir, "streams");
22717
- if (!existsSync45(dir)) return [];
22930
+ if (!existsSync46(dir)) return [];
22718
22931
  const cutoff = now - retentionDays * DAY_MS2;
22719
22932
  return readdirSync15(dir).map((name) => join46(dir, name)).filter((path) => {
22720
22933
  try {
22721
- return statSync12(path).mtimeMs < cutoff;
22934
+ return statSync13(path).mtimeMs < cutoff;
22722
22935
  } catch {
22723
22936
  return false;
22724
22937
  }
@@ -22742,11 +22955,11 @@ function applyStreamSweep(paths, dryRun, log) {
22742
22955
  return removed;
22743
22956
  }
22744
22957
  function planEventsSweep(stateDir, retentionDays, now = Date.now()) {
22745
- if (!existsSync45(stateDir)) return [];
22958
+ if (!existsSync46(stateDir)) return [];
22746
22959
  const cutoff = now - retentionDays * DAY_MS2;
22747
22960
  return readdirSync15(stateDir).filter((name) => ROTATED_EVENTS_RE.test(name)).map((name) => join46(stateDir, name)).filter((path) => {
22748
22961
  try {
22749
- return statSync12(path).mtimeMs < cutoff;
22962
+ return statSync13(path).mtimeMs < cutoff;
22750
22963
  } catch {
22751
22964
  return false;
22752
22965
  }
@@ -22754,11 +22967,11 @@ function planEventsSweep(stateDir, retentionDays, now = Date.now()) {
22754
22967
  }
22755
22968
 
22756
22969
  // src/cli.ts
22757
- import { realpathSync as realpathSync3, readFileSync as readFileSync48, existsSync as existsSync53, mkdirSync as mkdirSync40, writeFileSync as writeFileSync40, rmSync as rmSync25, unlinkSync as unlinkSync5, copyFileSync as copyFileSync2, renameSync as renameSync7, statSync as statSync16, readdirSync as readdirSync20 } from "fs";
22970
+ import { realpathSync as realpathSync3, readFileSync as readFileSync48, existsSync as existsSync54, mkdirSync as mkdirSync40, writeFileSync as writeFileSync40, rmSync as rmSync25, unlinkSync as unlinkSync5, copyFileSync as copyFileSync2, renameSync as renameSync7, statSync as statSync17, readdirSync as readdirSync20 } from "fs";
22758
22971
  import { createInterface } from "readline/promises";
22759
22972
 
22760
22973
  // src/periscope-cmd.ts
22761
- import { existsSync as existsSync46, mkdirSync as mkdirSync33, readFileSync as readFileSync42, rmSync as rmSync21, writeFileSync as writeFileSync35 } from "fs";
22974
+ import { existsSync as existsSync47, mkdirSync as mkdirSync33, readFileSync as readFileSync42, rmSync as rmSync21, writeFileSync as writeFileSync35 } from "fs";
22762
22975
  import { join as join47 } from "path";
22763
22976
  var PeriscopeError = class extends Error {
22764
22977
  };
@@ -22784,7 +22997,7 @@ function writePeriscopePrior(stateDir, ticketRecordId, prior) {
22784
22997
  function readPeriscopePrior(stateDir, ticketRecordId) {
22785
22998
  try {
22786
22999
  const p = priorPath(stateDir, ticketRecordId);
22787
- return existsSync46(p) ? JSON.parse(readFileSync42(p, "utf8")) : void 0;
23000
+ return existsSync47(p) ? JSON.parse(readFileSync42(p, "utf8")) : void 0;
22788
23001
  } catch {
22789
23002
  return void 0;
22790
23003
  }
@@ -23237,7 +23450,7 @@ ${tail2(preview.output)}`);
23237
23450
 
23238
23451
  // src/periscope-idle.ts
23239
23452
  import { execFileSync as execFileSync13 } from "child_process";
23240
- import { statSync as statSync13 } from "fs";
23453
+ import { statSync as statSync14 } from "fs";
23241
23454
  import { join as join48 } from "path";
23242
23455
  var MAX_SCANNED_FILES = 2e4;
23243
23456
  function newestWorktreeMtime(root) {
@@ -23263,7 +23476,7 @@ function newestTrackedMtime(root) {
23263
23476
  if (!rel) continue;
23264
23477
  if (++scanned > MAX_SCANNED_FILES) break;
23265
23478
  try {
23266
- const m = statSync13(join48(root, rel)).mtimeMs;
23479
+ const m = statSync14(join48(root, rel)).mtimeMs;
23267
23480
  if (newest === null || m > newest) newest = m;
23268
23481
  } catch {
23269
23482
  }
@@ -23340,7 +23553,7 @@ import { dirname as dirOf2, resolve as resolvePath } from "path";
23340
23553
 
23341
23554
  // src/ssh-keys.ts
23342
23555
  import { execFileSync as execFileSync14 } from "child_process";
23343
- import { existsSync as existsSync47, mkdirSync as mkdirSync34, readFileSync as readFileSync43, chmodSync as chmodSync3 } from "fs";
23556
+ import { existsSync as existsSync48, mkdirSync as mkdirSync34, readFileSync as readFileSync43, chmodSync as chmodSync3 } from "fs";
23344
23557
  import { dirname as dirname31, join as join49 } from "path";
23345
23558
  var SshKeyError = class extends Error {
23346
23559
  };
@@ -23350,7 +23563,7 @@ function shipSshKeyPathFor(stateDir) {
23350
23563
  function ensureShipSshKeypair(stateDir) {
23351
23564
  const privateKeyPath = shipSshKeyPathFor(stateDir);
23352
23565
  const publicKeyPath = `${privateKeyPath}.pub`;
23353
- if (!existsSync47(privateKeyPath)) {
23566
+ if (!existsSync48(privateKeyPath)) {
23354
23567
  mkdirSync34(dirname31(privateKeyPath), { recursive: true });
23355
23568
  try {
23356
23569
  execFileSync14("ssh-keygen", [
@@ -23371,7 +23584,7 @@ function ensureShipSshKeypair(stateDir) {
23371
23584
  }
23372
23585
  chmodSync3(privateKeyPath, 384);
23373
23586
  }
23374
- if (!existsSync47(publicKeyPath)) {
23587
+ if (!existsSync48(publicKeyPath)) {
23375
23588
  throw new SshKeyError(`${privateKeyPath} exists but ${publicKeyPath} does not \u2014 regenerate or restore it`);
23376
23589
  }
23377
23590
  const publicKey = readFileSync43(publicKeyPath, "utf8").trim();
@@ -23538,7 +23751,7 @@ async function unregisterEndpoint(workspaceId, info, d) {
23538
23751
  import { createServer as createHttpServer } from "http";
23539
23752
  import { spawn as spawn9 } from "child_process";
23540
23753
  import { randomBytes } from "crypto";
23541
- import { existsSync as existsSync48, mkdirSync as mkdirSync35, readFileSync as readFileSync44, writeFileSync as writeFileSync36, unlinkSync as unlinkSync4, readdirSync as readdirSync16 } from "fs";
23754
+ import { existsSync as existsSync49, mkdirSync as mkdirSync35, readFileSync as readFileSync44, writeFileSync as writeFileSync36, unlinkSync as unlinkSync4, readdirSync as readdirSync16 } from "fs";
23542
23755
  import { join as join50 } from "path";
23543
23756
 
23544
23757
  // src/secret-compare.ts
@@ -23636,7 +23849,7 @@ function syncDaemonStatePath(stateDir, workspaceId) {
23636
23849
  }
23637
23850
  function readPersistedSyncDaemon(stateDir, workspaceId) {
23638
23851
  const path = syncDaemonStatePath(stateDir, workspaceId);
23639
- if (!existsSync48(path)) return void 0;
23852
+ if (!existsSync49(path)) return void 0;
23640
23853
  try {
23641
23854
  return JSON.parse(readFileSync44(path, "utf8"));
23642
23855
  } catch {
@@ -23667,7 +23880,7 @@ function waitForExit(pid, alive, timeoutMs = 5e3) {
23667
23880
  }
23668
23881
  function readAllPersistedSyncWorkspaceIds(stateDir) {
23669
23882
  const dir = join50(stateDir, "passengers");
23670
- if (!existsSync48(dir)) return [];
23883
+ if (!existsSync49(dir)) return [];
23671
23884
  const suffix = "-sync.json";
23672
23885
  return readdirSync16(dir).filter((f) => f.endsWith(suffix)).map((f) => f.slice(0, -suffix.length));
23673
23886
  }
@@ -24187,12 +24400,12 @@ function contractFixers(dir, baseRef, tickets, locate) {
24187
24400
  }
24188
24401
 
24189
24402
  // src/daemon.ts
24190
- import { existsSync as existsSync50, mkdirSync as mkdirSync38, readFileSync as readFileSync46, readdirSync as readdirSync17, rmSync as rmSync22, statSync as statSync14, writeFileSync as writeFileSync38 } from "fs";
24403
+ import { existsSync as existsSync51, mkdirSync as mkdirSync38, readFileSync as readFileSync46, readdirSync as readdirSync17, rmSync as rmSync22, statSync as statSync15, writeFileSync as writeFileSync38 } from "fs";
24191
24404
  import { join as join53 } from "path";
24192
24405
  import { randomBytes as randomBytes2 } from "crypto";
24193
24406
 
24194
24407
  // src/noop-runs.ts
24195
- import { existsSync as existsSync49, mkdirSync as mkdirSync37, readFileSync as readFileSync45, renameSync as renameSync6, writeFileSync as writeFileSync37 } from "fs";
24408
+ import { existsSync as existsSync50, mkdirSync as mkdirSync37, readFileSync as readFileSync45, renameSync as renameSync6, writeFileSync as writeFileSync37 } from "fs";
24196
24409
  import { join as join52 } from "path";
24197
24410
  var NOOP_DELAYS_MS = [5, 15, 60].map((m) => m * 6e4);
24198
24411
  var DEFAULT_NOOP_REPEATS = 3;
@@ -24227,7 +24440,7 @@ function recordNoopRun(stateDir, recordId, repeats, now = Date.now()) {
24227
24440
  return { count, nextAt, bounce: count >= repeats };
24228
24441
  }
24229
24442
  function clearNoopRuns(stateDir, recordId) {
24230
- if (!existsSync49(noopRunsPath(stateDir))) return;
24443
+ if (!existsSync50(noopRunsPath(stateDir))) return;
24231
24444
  const state = readNoopRuns(stateDir);
24232
24445
  if (!(recordId in state)) return;
24233
24446
  delete state[recordId];
@@ -24362,7 +24575,7 @@ async function runDaemonLoop(o) {
24362
24575
  function latestMtime(path) {
24363
24576
  let stat2;
24364
24577
  try {
24365
- stat2 = statSync14(path);
24578
+ stat2 = statSync15(path);
24366
24579
  } catch {
24367
24580
  return 0;
24368
24581
  }
@@ -24379,14 +24592,14 @@ function computeTreeSignature(paths) {
24379
24592
  }
24380
24593
  function makeStaleChecker(paths, opts = {}) {
24381
24594
  const initial = computeTreeSignature(paths);
24382
- return () => computeTreeSignature(paths) !== initial || opts.reloadSentinel !== void 0 && existsSync50(opts.reloadSentinel);
24595
+ return () => computeTreeSignature(paths) !== initial || opts.reloadSentinel !== void 0 && existsSync51(opts.reloadSentinel);
24383
24596
  }
24384
24597
  function reloadSentinelFor(stateDir) {
24385
24598
  return join53(stateDir, "reload-requested");
24386
24599
  }
24387
24600
  function readReloadRequestedAt(stateDir) {
24388
24601
  try {
24389
- return statSync14(reloadSentinelFor(stateDir)).mtimeMs;
24602
+ return statSync15(reloadSentinelFor(stateDir)).mtimeMs;
24390
24603
  } catch {
24391
24604
  return null;
24392
24605
  }
@@ -24411,7 +24624,7 @@ function readDaemonStarted(stateDir) {
24411
24624
  function configChangedAfter(files, startedAt) {
24412
24625
  for (const f of files) {
24413
24626
  try {
24414
- if (statSync14(f).mtimeMs > startedAt) return f;
24627
+ if (statSync15(f).mtimeMs > startedAt) return f;
24415
24628
  } catch {
24416
24629
  }
24417
24630
  }
@@ -24483,6 +24696,13 @@ async function runOnePassUnguarded(o) {
24483
24696
  } catch (e) {
24484
24697
  emit.warn(`could not reconcile earlier agent runs: ${e.message}`, { step: "agent" });
24485
24698
  }
24699
+ if (o.sandboxHygiene) {
24700
+ try {
24701
+ await o.sandboxHygiene();
24702
+ } catch (e) {
24703
+ emit.warn(`sandbox hygiene failed: ${e instanceof Error ? e.message : String(e)}`);
24704
+ }
24705
+ }
24486
24706
  const decision = await decide(ctx);
24487
24707
  o.state.attention(o.route.route).persist(decision.attention);
24488
24708
  o.state.unroutable(o.route.route).persist(decision.unroutable);
@@ -24590,7 +24810,7 @@ async function runOnePassUnguarded(o) {
24590
24810
  settle = resolve8;
24591
24811
  });
24592
24812
  const ready = (tookTicket2) => settle(tookTicket2);
24593
- const run3 = spawn13(role, decision, ctx, { ready }).then(() => {
24813
+ const run4 = spawn13(role, decision, ctx, { ready }).then(() => {
24594
24814
  breaker.recordSuccess(role);
24595
24815
  clearShipAttention(o.state, `role_parked:${role}`);
24596
24816
  clearShipAttention(o.state, workspaceAuthKey(role));
@@ -24645,8 +24865,8 @@ async function runOnePassUnguarded(o) {
24645
24865
  });
24646
24866
  if (o.inFlight) {
24647
24867
  const set = o.inFlight;
24648
- set.add(run3);
24649
- void run3.finally(() => set.delete(run3));
24868
+ set.add(run4);
24869
+ void run4.finally(() => set.delete(run4));
24650
24870
  }
24651
24871
  const reported2 = TICKET_ROLES.has(role) ? await settled : true;
24652
24872
  const tookTicket = reported2 !== false;
@@ -25106,19 +25326,19 @@ import { createHash as createHash11 } from "crypto";
25106
25326
  import {
25107
25327
  chmodSync as chmodSync4,
25108
25328
  closeSync as closeSync6,
25109
- existsSync as existsSync51,
25329
+ existsSync as existsSync52,
25110
25330
  fstatSync,
25111
25331
  openSync as openSync6,
25112
25332
  readSync as readSync3,
25113
25333
  readdirSync as readdirSync18,
25114
25334
  rmSync as rmSync23,
25115
- statSync as statSync15,
25335
+ statSync as statSync16,
25116
25336
  watch
25117
25337
  } from "fs";
25118
25338
  import { createConnection } from "net";
25119
25339
  import { createServer as createServer2 } from "http";
25120
25340
  import { basename as basename14, dirname as dirname33, join as join54 } from "path";
25121
- import { execFile as execFile5, spawn as spawn12 } from "child_process";
25341
+ import { execFile as execFile6, spawn as spawn12 } from "child_process";
25122
25342
 
25123
25343
  // src/periscope-control.ts
25124
25344
  import { spawn as spawn11 } from "child_process";
@@ -25456,7 +25676,7 @@ function readRange(path, from, max) {
25456
25676
  }
25457
25677
  }
25458
25678
  function lastLines2(path, n) {
25459
- const st = statSync15(path);
25679
+ const st = statSync16(path);
25460
25680
  const cursorAt = (off) => encodeCursor({ dev: st.dev, ino: st.ino, off });
25461
25681
  if (n <= 0 || st.size === 0) return { lines: [], cursor: cursorAt(st.size), reset: false };
25462
25682
  let start = st.size;
@@ -25477,7 +25697,7 @@ function lastLines2(path, n) {
25477
25697
  }
25478
25698
  function readTail(live, opts) {
25479
25699
  const max = opts.maxBytes ?? MAX_TAIL_BYTES;
25480
- if (!existsSync51(live)) {
25700
+ if (!existsSync52(live)) {
25481
25701
  return { lines: [], cursor: opts.after ?? encodeCursor({ dev: 0, ino: 0, off: 0 }), reset: false };
25482
25702
  }
25483
25703
  const cur = opts.after ? decodeCursor(opts.after) : null;
@@ -25490,7 +25710,7 @@ function readTail(live, opts) {
25490
25710
  } else {
25491
25711
  const found = candidates(live, opts.rotated ?? false).find((p) => {
25492
25712
  try {
25493
- const s = statSync15(p);
25713
+ const s = statSync16(p);
25494
25714
  return s.ino === cur.ino && s.dev === cur.dev;
25495
25715
  } catch {
25496
25716
  return false;
@@ -25501,7 +25721,7 @@ function readTail(live, opts) {
25501
25721
  off = cur.off;
25502
25722
  } else reset = true;
25503
25723
  }
25504
- let size = statSync15(path).size;
25724
+ let size = statSync16(path).size;
25505
25725
  if (off > size) {
25506
25726
  off = 0;
25507
25727
  reset = true;
@@ -25509,12 +25729,12 @@ function readTail(live, opts) {
25509
25729
  if (off >= size && path !== live) {
25510
25730
  path = live;
25511
25731
  off = 0;
25512
- size = statSync15(path).size;
25732
+ size = statSync16(path).size;
25513
25733
  }
25514
25734
  const { text: text2 } = readRange(path, off, max);
25515
25735
  const cut = text2.lastIndexOf("\n");
25516
25736
  const whole = cut < 0 ? "" : text2.slice(0, cut + 1);
25517
- const st = statSync15(path);
25737
+ const st = statSync16(path);
25518
25738
  return {
25519
25739
  lines: whole.split("\n").filter((l) => l.length),
25520
25740
  cursor: encodeCursor({ dev: st.dev, ino: st.ino, off: off + Buffer.byteLength(whole) }),
@@ -25631,10 +25851,10 @@ async function route(deps, method, url, req, abort) {
25631
25851
  if (p === "/events" && get2) return tailReply(eventFileFor(deps.stateDir), url.searchParams, true, abort);
25632
25852
  if (p === "/streams" && get2) return reply2(200, { streams: liveRuns(deps.stateDir).map(describeStream) });
25633
25853
  if (p.startsWith("/streams/") && get2) {
25634
- const run3 = decodeURIComponent(p.slice("/streams/".length));
25635
- if (!RUN_NAME_RE.test(run3) || run3.includes("..") || /\.(pid|meta\.json|events\.jsonl)$/.test(run3)) return err2(400, "not a run name");
25636
- const file = join54(deps.stateDir, "streams", run3.endsWith(".jsonl") ? run3 : `${run3}.jsonl`);
25637
- if (!existsSync51(file)) return err2(404, "no such run");
25854
+ const run4 = decodeURIComponent(p.slice("/streams/".length));
25855
+ if (!RUN_NAME_RE.test(run4) || run4.includes("..") || /\.(pid|meta\.json|events\.jsonl)$/.test(run4)) return err2(400, "not a run name");
25856
+ const file = join54(deps.stateDir, "streams", run4.endsWith(".jsonl") ? run4 : `${run4}.jsonl`);
25857
+ if (!existsSync52(file)) return err2(404, "no such run");
25638
25858
  return tailReply(file, url.searchParams, false, abort);
25639
25859
  }
25640
25860
  if ((p === "/pause" || p === "/resume") && post3) {
@@ -25679,7 +25899,7 @@ function send(res, r) {
25679
25899
  res.end(body);
25680
25900
  }
25681
25901
  async function socketIsStale(path) {
25682
- if (!existsSync51(path)) return false;
25902
+ if (!existsSync52(path)) return false;
25683
25903
  return new Promise((resolve8) => {
25684
25904
  const c = createConnection(path);
25685
25905
  c.once("connect", () => {
@@ -25698,7 +25918,7 @@ async function startControlServer(deps) {
25698
25918
  return null;
25699
25919
  }
25700
25920
  if (await socketIsStale(path)) rmSync23(path, { force: true });
25701
- else if (existsSync51(path)) {
25921
+ else if (existsSync52(path)) {
25702
25922
  log(`control API not started: ${path} is in use by another process`);
25703
25923
  return null;
25704
25924
  }
@@ -25760,18 +25980,18 @@ function runDetached(commands, spawnFn = spawn12) {
25760
25980
  });
25761
25981
  child.unref();
25762
25982
  }
25763
- function schedulerHandler(control, run3 = runDetached) {
25983
+ function schedulerHandler(control, run4 = runDetached) {
25764
25984
  return (action) => {
25765
25985
  const { startCommand: start, stopCommand: stop } = control;
25766
25986
  if (!start || !stop) return { accepted: false, detail: "this host has no service manager for the daemon (cron or none)" };
25767
25987
  const commands = action === "start" ? [start] : action === "stop" ? [stop] : [stop, start];
25768
- run3(commands);
25988
+ run4(commands);
25769
25989
  return { accepted: true, detail: `${action} requested` };
25770
25990
  };
25771
25991
  }
25772
25992
  function crewJson(args, timeoutMs = 6e4) {
25773
25993
  return new Promise((resolve8) => {
25774
- execFile5(process.execPath, [process.argv[1] ?? "", ...args], { timeout: timeoutMs, maxBuffer: 16 * 1024 * 1024 }, (_e, stdout) => {
25994
+ execFile6(process.execPath, [process.argv[1] ?? "", ...args], { timeout: timeoutMs, maxBuffer: 16 * 1024 * 1024 }, (_e, stdout) => {
25775
25995
  try {
25776
25996
  const v = JSON.parse(String(stdout));
25777
25997
  resolve8(v && typeof v === "object" && !Array.isArray(v) ? v : null);
@@ -25791,7 +26011,7 @@ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/
25791
26011
 
25792
26012
  // src/periscope-endpoints.ts
25793
26013
  import { randomBytes as randomBytes3 } from "crypto";
25794
- import { chmodSync as chmodSync5, existsSync as existsSync52, mkdirSync as mkdirSync39, readdirSync as readdirSync19, readFileSync as readFileSync47, rmSync as rmSync24, writeFileSync as writeFileSync39 } from "fs";
26014
+ import { chmodSync as chmodSync5, existsSync as existsSync53, mkdirSync as mkdirSync39, readdirSync as readdirSync19, readFileSync as readFileSync47, rmSync as rmSync24, writeFileSync as writeFileSync39 } from "fs";
25795
26015
  import { join as join55 } from "path";
25796
26016
  var secretDir = (stateDir) => join55(stateDir, "periscope-mcp");
25797
26017
  var secretFile = (stateDir, id) => join55(secretDir(stateDir), `${id}.json`);
@@ -25834,7 +26054,7 @@ function removePeriscopeEndpointRecord(stateDir, ticketRecordId) {
25834
26054
  }
25835
26055
  function listPeriscopeEndpoints(stateDir) {
25836
26056
  const dir = endpointDir(stateDir);
25837
- if (!existsSync52(dir)) return [];
26057
+ if (!existsSync53(dir)) return [];
25838
26058
  const out = [];
25839
26059
  for (const name of readdirSync19(dir)) {
25840
26060
  if (!name.endsWith(".json")) continue;
@@ -26817,7 +27037,7 @@ if (command === "passenger-sync-daemon") {
26817
27037
  } else {
26818
27038
  const toleratesNoRoutes = command === "credential" || command === "forge" || command === "repos" || command === "ship" || command === "disconnect" && flag("reset") || command === "deprovision" || command === "connect" && flag("sign-out");
26819
27039
  const configless = command === "connect" && flag("sign-out") || command === "disconnect" && flag("reset") || command === "deprovision";
26820
- if (configless && !existsSync53(findConfigFile(CREW_HOME))) {
27040
+ if (configless && !existsSync54(findConfigFile(CREW_HOME))) {
26821
27041
  cfg = loadConfig(CREW_HOME, firstRunConfigPath(), { text: "ship: {}\n", allowNoRoutes: true });
26822
27042
  } else {
26823
27043
  cfg = loadConfig(CREW_HOME, void 0, toleratesNoRoutes ? { allowNoRoutes: true } : {});
@@ -27170,7 +27390,7 @@ if (command === "passenger-sync-daemon") {
27170
27390
  if (host === "linux" && hasSystemd) {
27171
27391
  const label = labelFor(CREW_HOME, "run");
27172
27392
  const staleTimer = join57(homedir11(), ".config", "systemd", "user", `${label}.timer`);
27173
- if (existsSync53(staleTimer)) {
27393
+ if (existsSync54(staleTimer)) {
27174
27394
  process.stdout.write(
27175
27395
  `removing stale run timer from before the persistent-service cutover: ${staleTimer}${dryRun ? " (dry run)" : ""}
27176
27396
  `
@@ -27199,7 +27419,7 @@ if (command === "passenger-sync-daemon") {
27199
27419
  const { settled: doctorRepos, errors: refusedRepos } = await settleRepos(reposOf(c), (t) => t.name, (t) => resolveOneRepo(c, t));
27200
27420
  for (const e of refusedRepos) problems.push(`repo ${e.repo}: ${e.detail}`);
27201
27421
  for (const r of doctorRepos) {
27202
- if (!existsSync53(r.dir)) problems.push(`repo ${r.name}: ${r.dir} is missing on disk`);
27422
+ if (!existsSync54(r.dir)) problems.push(`repo ${r.name}: ${r.dir} is missing on disk`);
27203
27423
  if (!satisfies(host, r.config.platform)) problems.push(`repo ${r.name}: requires ${r.config.platform}, this host is ${host}`);
27204
27424
  readiness.push(...validateEffective(r.config).map((p) => `repo ${r.name}: ${p}`));
27205
27425
  }
@@ -27226,7 +27446,7 @@ if (command === "passenger-sync-daemon") {
27226
27446
  }
27227
27447
  async function doctorFix(o) {
27228
27448
  const routes = await Promise.all(routesInScope(cfg.routes, named).map((c) => gatherHealth({ route: c.route, enabled: c.enabled, hasRepos: reposOf(c).length > 0 }, () => routeProblems(c))));
27229
- const unitExists = (p) => existsSync53(p);
27449
+ const unitExists = (p) => existsSync54(p);
27230
27450
  const crontab = o.host === "linux" ? spawnSync12("crontab", ["-l"], { encoding: "utf8" }).stdout ?? "" : "";
27231
27451
  const schedulerAbsent = o.host !== "windows" ? !schedulerInstalled(planInstall(cfg.ship, CREW_HOME, o.host, detectSystemd(), "run", installContext()), unitExists, crontab) : true;
27232
27452
  const plan = planFix({ routes, schedulerAbsent, host: o.host });
@@ -27298,7 +27518,7 @@ ${changed2.map((c) => ` - ${c}
27298
27518
  if (patterns.length > 0 && Object.keys(warm).length === 0 && firstReport(`warm-empty:${r.name}:${failure}`)) {
27299
27519
  emit.emit(`${r.name}: sandbox.warm declares ${patterns.join(", ")} but no file could be read from ${source}${failure ? ` (${failure})` : ""}; the image is built without warm files`);
27300
27520
  }
27301
- out.set(r.name, { name: r.name, decl: intelFlavor(r.config.hooks.intel) === "serena" ? { ...r.config.sandbox, intel: "serena" } : r.config.sandbox, warm, ...wantsCodeBridge(r.config.hooks.intel) ? { bridge: readBridgeBundle() } : {} });
27521
+ out.set(r.name, { name: r.name, ...patterns.length > 0 && failure ? { unreadable: `sandbox.warm files could not be read (${failure})` } : {}, decl: intelFlavor(r.config.hooks.intel) === "serena" ? { ...r.config.sandbox, intel: "serena" } : r.config.sandbox, warm, ...wantsCodeBridge(r.config.hooks.intel) ? { bridge: readBridgeBundle() } : {} });
27302
27522
  }
27303
27523
  }
27304
27524
  return [...out.values()];
@@ -28646,6 +28866,7 @@ ${cu.tail.trimEnd()}
28646
28866
  });
28647
28867
  if (controlServer) emit.emit(`control API listening on ${controlServer.path}`);
28648
28868
  const inFlight = /* @__PURE__ */ new Set();
28869
+ const sandboxHygienePass = cfg.ship.runner === "sandbox" ? makeSandboxHygiene({ state, emit, ship: cfg.ship }) : void 0;
28649
28870
  let sandboxBuilding = false;
28650
28871
  const stopReason = await runDaemonLoop({
28651
28872
  inFlight,
@@ -28655,6 +28876,7 @@ ${cu.tail.trimEnd()}
28655
28876
  runPass: () => runOnePass({
28656
28877
  inFlight,
28657
28878
  sandboxCache: sandboxCachePass,
28879
+ sandboxHygiene: sandboxHygienePass,
28658
28880
  route: route2,
28659
28881
  ship: cfg.ship,
28660
28882
  state,
@@ -28693,7 +28915,7 @@ ${cu.tail.trimEnd()}
28693
28915
  ),
28694
28916
  checkStale: makeStaleChecker(watchPaths, { reloadSentinel: reloadSentinelFor(cfg.ship.stateDir) }),
28695
28917
  onPass: (result) => {
28696
- if (!sandboxBuilding) {
28918
+ if (!sandboxBuilding && !diskFullStop(state)) {
28697
28919
  sandboxBuilding = true;
28698
28920
  void sandboxReposOf(cfg.routes.filter((r) => r.enabled)).then(withShipSandbox).then((repos) => repos.length ? sandboxBuildTick(repos, sandboxTickDeps(emit, route2)) : null).catch((err3) => emit.warn(`sandbox image build tick failed: ${err3 instanceof Error ? err3.message : String(err3)}`)).finally(() => {
28699
28921
  sandboxBuilding = false;
@@ -28801,9 +29023,9 @@ ${cu.tail.trimEnd()}
28801
29023
  `);
28802
29024
  process.exit(2);
28803
29025
  }
28804
- let run3;
29026
+ let run4;
28805
29027
  try {
28806
- run3 = await runAgentsSync(target, {
29028
+ run4 = await runAgentsSync(target, {
28807
29029
  userAgent: cfg.ship.userAgent,
28808
29030
  stateDir: cfg.ship.stateDir,
28809
29031
  dryRun,
@@ -28821,7 +29043,7 @@ ${cu.tail.trimEnd()}
28821
29043
  }
28822
29044
  throw e;
28823
29045
  }
28824
- const { personaResult, skillResult } = run3;
29046
+ const { personaResult, skillResult } = run4;
28825
29047
  if (flag("revoke-seat-keys")) {
28826
29048
  for (const o of await revokeSeatKeys(target, { userAgent: cfg.ship.userAgent, dryRun, shipName: cfg.ship.name })) {
28827
29049
  process.stdout.write(`${describeRevokeOutcome(o)}
@@ -28842,7 +29064,7 @@ ${cu.tail.trimEnd()}
28842
29064
  }
28843
29065
  }
28844
29066
  }
28845
- if (run3.diverged) process.exitCode = 1;
29067
+ if (run4.diverged) process.exitCode = 1;
28846
29068
  break;
28847
29069
  }
28848
29070
  case "skills": {
@@ -28884,7 +29106,7 @@ ${cu.tail.trimEnd()}
28884
29106
  `);
28885
29107
  if (!dryRun) {
28886
29108
  const resolvedPath = resolvedPathFor(cfg.ship.stateDir, target.route);
28887
- const raw = existsSync53(resolvedPath) ? JSON.parse(readFileSync48(resolvedPath, "utf8")) : {};
29109
+ const raw = existsSync54(resolvedPath) ? JSON.parse(readFileSync48(resolvedPath, "utf8")) : {};
28888
29110
  raw.agentSkills = result.agentSkills;
28889
29111
  mkdirSync40(dirOf2(resolvedPath), { recursive: true });
28890
29112
  writeFileSync40(resolvedPath, `${JSON.stringify(raw, null, 2)}
@@ -28989,8 +29211,8 @@ ${cu.tail.trimEnd()}
28989
29211
  try {
28990
29212
  const a = parseHooksArgs(positional.slice(2), routeNamesOf(configText));
28991
29213
  const dir = repoDirOf(configText, dirname35(cfg.configFile), a.route, a.name);
28992
- if (!existsSync53(dir)) throw new ReposError(`${dir} does not exist on disk`);
28993
- const files = { exists: (r) => existsSync53(resolvePath(dir, r)), list: (r) => {
29214
+ if (!existsSync54(dir)) throw new ReposError(`${dir} does not exist on disk`);
29215
+ const files = { exists: (r) => existsSync54(resolvePath(dir, r)), list: (r) => {
28994
29216
  try {
28995
29217
  return readdirSync20(resolvePath(dir, r));
28996
29218
  } catch {
@@ -29108,7 +29330,7 @@ ${cu.tail.trimEnd()}
29108
29330
  if (sub === "list" && !routeName) usage2();
29109
29331
  if (sub === "add") {
29110
29332
  try {
29111
- const a = parseAddArgs(positional.slice(2), routeNamesOf(configText), (p) => existsSync53(resolvePath(p.replace(/^~(?=\/|$)/, homedir11()))));
29333
+ const a = parseAddArgs(positional.slice(2), routeNamesOf(configText), (p) => existsSync54(resolvePath(p.replace(/^~(?=\/|$)/, homedir11()))));
29112
29334
  routeName = a.route;
29113
29335
  addPath = a.path;
29114
29336
  addName = a.name;
@@ -29138,7 +29360,7 @@ ${cu.tail.trimEnd()}
29138
29360
  const resolvedFile = resolvedPathFor(cfg.ship.stateDir, routeName);
29139
29361
  if (sub === "list" || sub === "add") {
29140
29362
  const liveRoute = cfg.routes.find((r) => r.route === routeName);
29141
- if (liveRoute?.resolved?.reposModelId && existsSync53(resolvedFile) && !dryRun) {
29363
+ if (liveRoute?.resolved?.reposModelId && existsSync54(resolvedFile) && !dryRun) {
29142
29364
  try {
29143
29365
  await hydrateApiKeys([liveRoute]);
29144
29366
  persistRepoRows(cfg.ship.stateDir, liveRoute.route, await new Tracker(liveRoute, cfg.ship).repoRowsForMap());
@@ -29147,7 +29369,7 @@ ${cu.tail.trimEnd()}
29147
29369
  }
29148
29370
  }
29149
29371
  let resolvedRemotes;
29150
- if (existsSync53(resolvedFile)) {
29372
+ if (existsSync54(resolvedFile)) {
29151
29373
  try {
29152
29374
  resolvedRemotes = JSON.parse(readFileSync48(resolvedFile, "utf8"));
29153
29375
  } catch {
@@ -29156,7 +29378,7 @@ ${cu.tail.trimEnd()}
29156
29378
  const originOf = (dir) => gitOk(dir, ["remote", "get-url", "origin"]) ?? void 0;
29157
29379
  const text2 = configText;
29158
29380
  const base = dirname35(cfg.configFile);
29159
- const isCheckout = (d) => existsSync53(`${d}/.git`);
29381
+ const isCheckout = (d) => existsSync54(`${d}/.git`);
29160
29382
  try {
29161
29383
  if (sub === "list") {
29162
29384
  if (flag("json")) {
@@ -29166,7 +29388,7 @@ ${cu.tail.trimEnd()}
29166
29388
  base,
29167
29389
  resolved: resolvedRemotes,
29168
29390
  originOf,
29169
- exists: (d) => existsSync53(d),
29391
+ exists: (d) => existsSync54(d),
29170
29392
  isCheckout,
29171
29393
  repoHasHooks: (d) => REPO_CONFIG_FILENAMES.some((f) => {
29172
29394
  try {
@@ -29188,7 +29410,7 @@ ${cu.tail.trimEnd()}
29188
29410
  for (const r of repos) {
29189
29411
  const origin2 = originOf(r.dir);
29190
29412
  const row = matchRepoName(origin2, resolvedRemotes);
29191
- const note = !existsSync53(r.dir) ? "missing on disk" : row ? `Repos row: ${row}` : `no Repos row matches ${normalizeRemote(origin2) ?? "this checkout (no origin remote)"}`;
29413
+ const note = !existsSync54(r.dir) ? "missing on disk" : row ? `Repos row: ${row}` : `no Repos row matches ${normalizeRemote(origin2) ?? "this checkout (no origin remote)"}`;
29192
29414
  process.stdout.write(`${r.name} ${r.dir} ${note}
29193
29415
  `);
29194
29416
  }
@@ -29200,9 +29422,9 @@ ${cu.tail.trimEnd()}
29200
29422
  ` : `${human}
29201
29423
  `);
29202
29424
  const plan2 = planRepoClone({ text: text2, base, route: routeName, name: addName, resolved: resolvedRemotes, dir: value("dir"), isCheckout });
29203
- if (existsSync53(plan2.target) && (existsSync53(`${plan2.target}/.git`) || readdirSync20(plan2.target).length > 0)) {
29425
+ if (existsSync54(plan2.target) && (existsSync54(`${plan2.target}/.git`) || readdirSync20(plan2.target).length > 0)) {
29204
29426
  throw new ReposError(
29205
- existsSync53(`${plan2.target}/.git`) ? `${plan2.target} is already a checkout \u2014 attach it with \`crew repos add ${routeName} ${plan2.name} ${plan2.target}\`` : `${plan2.target} exists and is not empty \u2014 pass --dir to clone somewhere else`
29427
+ existsSync54(`${plan2.target}/.git`) ? `${plan2.target} is already a checkout \u2014 attach it with \`crew repos add ${routeName} ${plan2.name} ${plan2.target}\`` : `${plan2.target} exists and is not empty \u2014 pass --dir to clone somewhere else`
29206
29428
  );
29207
29429
  }
29208
29430
  if (dryRun) {
@@ -29227,7 +29449,7 @@ ${cu.tail.trimEnd()}
29227
29449
  break;
29228
29450
  }
29229
29451
  const target = resolvePath(addPath.replace(/^~(?=\/|$)/, homedir11()));
29230
- const top = existsSync53(target) ? gitOk(target, ["rev-parse", "--show-toplevel"]) : null;
29452
+ const top = existsSync54(target) ? gitOk(target, ["rev-parse", "--show-toplevel"]) : null;
29231
29453
  if (!top) throw new ReposError(`${target} is not a git checkout`);
29232
29454
  const origin = originOf(top);
29233
29455
  const plan = planRepoAdd({
@@ -29279,7 +29501,7 @@ ${cu.tail.trimEnd()}
29279
29501
  const created = await rowTracker.createRepoRow(rowPayload);
29280
29502
  process.stdout.write(`created Repos row ${String(rowPayload.name)} (${String(rowPayload.remote)}) ${created.id}
29281
29503
  `);
29282
- if (existsSync53(resolvedFile)) {
29504
+ if (existsSync54(resolvedFile)) {
29283
29505
  const raw = JSON.parse(readFileSync48(resolvedFile, "utf8"));
29284
29506
  raw.repoNames = { ...raw.repoNames, [created.id]: String(rowPayload.name) };
29285
29507
  raw.repoRemotes = { ...raw.repoRemotes, [created.id]: String(rowPayload.remote) };
@@ -29705,7 +29927,7 @@ Signed in as ${result.identity.email} \u2014 minted an API key in workspace "${r
29705
29927
  }
29706
29928
  }
29707
29929
  let previous;
29708
- const hadPreviousFile = existsSync53(resolvedPath);
29930
+ const hadPreviousFile = existsSync54(resolvedPath);
29709
29931
  if (hadPreviousFile) {
29710
29932
  try {
29711
29933
  previous = JSON.parse(readFileSync48(resolvedPath, "utf8"));
@@ -30021,7 +30243,7 @@ Signed in as ${result.identity.email} \u2014 minted an API key in workspace "${r
30021
30243
  if (syncRoute?.resolved) {
30022
30244
  try {
30023
30245
  process.stderr.write("\n");
30024
- const run3 = await runAgentsSync(syncRoute, {
30246
+ const run4 = await runAgentsSync(syncRoute, {
30025
30247
  userAgent: cfg.ship.userAgent,
30026
30248
  stateDir: cfg.ship.stateDir,
30027
30249
  say: (l) => process.stderr.write(` ${l}
@@ -30036,19 +30258,19 @@ Signed in as ${result.identity.email} \u2014 minted an API key in workspace "${r
30036
30258
  if (p.state === "forbidden") process.stderr.write(` ${describeSeatForbidden(p.role, p.tables)}
30037
30259
  `);
30038
30260
  }
30039
- if (run3.readOnly) {
30040
- const missing = run3.personaResult.outcomes.some((p) => p.action === "missing");
30261
+ if (run4.readOnly) {
30262
+ const missing = run4.personaResult.outcomes.some((p) => p.action === "missing");
30041
30263
  process.stderr.write(missing ? " A workspace admin has to open the Crew app or run `crew agents sync` once before this ship's seats can run.\n" : " Seats are linked to the workspace's existing personas.\n");
30042
30264
  }
30043
- connectEvents.emit("agents_synced", run3.readOnly ? "agents linked (read-only key)" : "agents synced", {
30265
+ connectEvents.emit("agents_synced", run4.readOnly ? "agents linked (read-only key)" : "agents synced", {
30044
30266
  route: route3,
30045
- admin: !run3.readOnly,
30046
- personas: run3.personaResult.outcomes,
30047
- skills: run3.skillResult?.outcomes ?? [],
30048
- diverged: run3.diverged
30267
+ admin: !run4.readOnly,
30268
+ personas: run4.personaResult.outcomes,
30269
+ skills: run4.skillResult?.outcomes ?? [],
30270
+ diverged: run4.diverged
30049
30271
  });
30050
30272
  for (const m of minted) connectEvents.emit("seat_key", describeMintOutcome(m), { route: route3, ...m });
30051
- if (run3.diverged) process.exitCode = 1;
30273
+ if (run4.diverged) process.exitCode = 1;
30052
30274
  } catch (e) {
30053
30275
  if (e instanceof AgentsSyncError || e instanceof SkillSyncError) skip(e.message);
30054
30276
  else throw e;
@@ -30604,7 +30826,7 @@ Signed in as ${result.identity.email} \u2014 minted an API key in workspace "${r
30604
30826
  prepare: async (path) => {
30605
30827
  for (const f of repoWt.config.worktrees.copy) {
30606
30828
  const src = join57(repoWt.dir, f);
30607
- if (!existsSync53(src) || existsSync53(join57(path, f))) continue;
30829
+ if (!existsSync54(src) || existsSync54(join57(path, f))) continue;
30608
30830
  mkdirSync40(dirOf2(join57(path, f)), { recursive: true });
30609
30831
  copyFileSync2(src, join57(path, f));
30610
30832
  }
@@ -30827,7 +31049,7 @@ Signed in as ${result.identity.email} \u2014 minted an API key in workspace "${r
30827
31049
  const shellR = hit && resolveShell(hit.repo.config.shell ?? cfg.ship.shell);
30828
31050
  const resumed = await runPeriscopeResume({
30829
31051
  find: async () => hit && { row: hit.row, tag: hit.tag },
30830
- worktreeExists: (p) => existsSync53(p),
31052
+ worktreeExists: (p) => existsSync54(p),
30831
31053
  prepareDropFile,
30832
31054
  startProxy: (wt, url, n) => launchProxy(crewInvocation(CREW_HOME), wt, url, Number(n), { host: hit.row.host || "localhost", inject: hit.repo.config.periscope?.inspector !== "repo" }),
30833
31055
  caps: periscopeCaps(cfg.ship),
@@ -30924,7 +31146,7 @@ ${where.join("\n")}`);
30924
31146
  prepare: async (path) => {
30925
31147
  for (const f of repoP.config.worktrees.copy) {
30926
31148
  const src = join57(repoP.dir, f);
30927
- if (!existsSync53(src)) continue;
31149
+ if (!existsSync54(src)) continue;
30928
31150
  mkdirSync40(dirOf2(join57(path, f)), { recursive: true });
30929
31151
  copyFileSync2(src, join57(path, f));
30930
31152
  }
@@ -31427,7 +31649,7 @@ ${where.join("\n")}`);
31427
31649
  }
31428
31650
  if (row) {
31429
31651
  await tracker.deleteRepoRow(row.id);
31430
- if (existsSync53(resolvedFile)) {
31652
+ if (existsSync54(resolvedFile)) {
31431
31653
  const raw = JSON.parse(readFileSync48(resolvedFile, "utf8"));
31432
31654
  if (raw.repoNames) delete raw.repoNames[row.id];
31433
31655
  if (raw.repoRemotes) delete raw.repoRemotes[row.id];
@@ -31435,13 +31657,13 @@ ${where.join("\n")}`);
31435
31657
  `);
31436
31658
  }
31437
31659
  }
31438
- if (existsSync53(join57(dir, ".git")) && basename16(dir) === SAMPLE_REPO) rmSync25(dir, { recursive: true, force: true });
31660
+ if (existsSync54(join57(dir, ".git")) && basename16(dir) === SAMPLE_REPO) rmSync25(dir, { recursive: true, force: true });
31439
31661
  say("removed", { dir, closed }, `removed the sample repo${closed.length ? `, closed ${closed.join(", ")}` : ""}`);
31440
31662
  break;
31441
31663
  }
31442
31664
  const projectId = route2.resolved.areaId ?? resolveRepoProject(await tracker.projectRows(), value("project"));
31443
- const fresh = !existsSync53(join57(dir, ".git"));
31444
- if (existsSync53(dir) && fresh && readdirSync20(dir).length > 0) fail2(`${dir} exists and is not a git checkout \u2014 move it aside`);
31665
+ const fresh = !existsSync54(join57(dir, ".git"));
31666
+ if (existsSync54(dir) && fresh && readdirSync20(dir).length > 0) fail2(`${dir} exists and is not a git checkout \u2014 move it aside`);
31445
31667
  if (dryRun) {
31446
31668
  say("dry-run", { dir, newCheckout: fresh, repoRow: row?.id ?? null }, `would ${fresh ? "create" : "reuse"} ${dir}${row ? "" : ", create the Repos row"}, and file one ${tracker.contract.statuses.approved} ticket`);
31447
31669
  break;
@@ -31467,7 +31689,7 @@ ${where.join("\n")}`);
31467
31689
  spec: { platform: "unix", releaseMode: "integrate", ciProvider: "none" }
31468
31690
  });
31469
31691
  repoId = (await tracker.createRepoRow(payload)).id;
31470
- if (existsSync53(resolvedFile)) {
31692
+ if (existsSync54(resolvedFile)) {
31471
31693
  const raw = JSON.parse(readFileSync48(resolvedFile, "utf8"));
31472
31694
  raw.repoNames = { ...raw.repoNames, [repoId]: SAMPLE_REPO };
31473
31695
  raw.repoRemotes = { ...raw.repoRemotes, [repoId]: SAMPLE_REMOTE };
@@ -31823,7 +32045,7 @@ watermark: ${state.watermark()}
31823
32045
  }
31824
32046
  for (const r of repos) {
31825
32047
  const remote = r.config.branch.remote;
31826
- if (existsSync53(r.dir)) {
32048
+ if (existsSync54(r.dir)) {
31827
32049
  pushAuth.push({
31828
32050
  route: c.route,
31829
32051
  repo: r.name,
@@ -31896,7 +32118,7 @@ watermark: ${state.watermark()}
31896
32118
  }
31897
32119
  }
31898
32120
  for (const message of roleCapWarnings(cfg.ship)) problems.push({ severity: "note", kind: "role_cap_above_ship_cap", message });
31899
- const runtimeDir = runtimeDirWarning(process.platform, process.getuid?.() ?? null, existsSync53, userInfo2().username);
32121
+ const runtimeDir = runtimeDirWarning(process.platform, process.getuid?.() ?? null, existsSync54, userInfo2().username);
31900
32122
  if (runtimeDir) problems.push({ severity: "attention", kind: "runtime_dir_missing", message: runtimeDir });
31901
32123
  if (!flag("offline")) {
31902
32124
  const shipKind = await doctorShipKind(route2, cfg.ship);
@@ -31961,7 +32183,7 @@ routes: ${cfg.routes.map((c) => c.route).join(", ")}
31961
32183
  }
31962
32184
  try {
31963
32185
  const evFile = eventFileFor(cfg.ship.stateDir);
31964
- const evSize = existsSync53(evFile) ? statSync16(evFile).size : 0;
32186
+ const evSize = existsSync54(evFile) ? statSync17(evFile).size : 0;
31965
32187
  process.stdout.write(
31966
32188
  evSize > cfg.ship.eventsRotateBytes * 4 ? `events log: WARN ${evFile} is ${Math.round(evSize / 1048576)} MB (> 4x eventsRotateBytes); run \`crew reap\` to rotate it
31967
32189
  ` : "events log: ok\n"
@@ -32001,7 +32223,7 @@ routes: ${cfg.routes.map((c) => c.route).join(", ")}
32001
32223
  if (host === "linux" && detectSystemd()) {
32002
32224
  const ctl = planDaemonControl(CREW_HOME, host, true);
32003
32225
  const unitPlan = planInstall(cfg.ship, CREW_HOME, host, true, "run", installContext());
32004
- if (ctl.statusCommand && unitPlan.unitPaths.some((p) => existsSync53(p))) {
32226
+ if (ctl.statusCommand && unitPlan.unitPaths.some((p) => existsSync54(p))) {
32005
32227
  const st = spawnSync12(ctl.statusCommand[0], ctl.statusCommand.slice(1), { cwd: CREW_HOME, encoding: "utf8" });
32006
32228
  if (!st.error && st.status !== 0) {
32007
32229
  process.stdout.write("daemon unit: WARN installed but not running \u2014 no work is picked up; run `crew reload` (or `crew daemon start`), and `crew install` if the unit still says Restart=on-failure\n");
@@ -32020,7 +32242,7 @@ routes: ${cfg.routes.map((c) => c.route).join(", ")}
32020
32242
  const changed2 = configChangedAfter(daemonConfigPaths(cfg), daemonStartedAt);
32021
32243
  if (changed2) {
32022
32244
  process.stdout.write(
32023
- `daemon config: WARN ${changed2} changed at ${new Date(statSync16(changed2).mtimeMs).toISOString()} but the daemon started at ${new Date(daemonStartedAt).toISOString()} \u2014 run \`crew reload\`
32245
+ `daemon config: WARN ${changed2} changed at ${new Date(statSync17(changed2).mtimeMs).toISOString()} but the daemon started at ${new Date(daemonStartedAt).toISOString()} \u2014 run \`crew reload\`
32024
32246
  `
32025
32247
  );
32026
32248
  }