@tablation/crew 0.132.2 → 0.133.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/cli.js +495 -247
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -2827,6 +2827,9 @@ function tablationEndpoint(url) {
2827
2827
  return { host, port };
2828
2828
  }
2829
2829
  var CREW_BIN = "/opt/crew/bin";
2830
+ var CREW_PNPM_STORE = "/opt/crew/pnpm-store";
2831
+ var CREW_PNPM_HOME = "/opt/crew/pnpm";
2832
+ var CREW_CACHE = "/opt/crew/cache";
2830
2833
  var TOOL_BINARIES = ["/usr/bin/curl", `${CREW_BIN}/node`, "/usr/bin/node", "/usr/local/bin/node", "/usr/bin/npm", "/usr/local/bin/npm", "/usr/local/bin/pnpm", "/usr/bin/corepack", "/usr/local/bin/corepack"];
2831
2834
  var GIT_BINARIES = ["/usr/bin/git", "/usr/lib/git-core/git-remote-http", "/usr/lib/git-core/git-remote-https"];
2832
2835
  function policyGroups(input) {
@@ -2873,7 +2876,8 @@ function generateSandboxPolicy(input) {
2873
2876
  filesystem_policy: {
2874
2877
  include_workdir: true,
2875
2878
  read_only: ["/usr", "/lib", "/proc", "/dev/urandom", "/app", "/etc", "/var/log", "/opt/crew", mirror],
2876
- read_write: ["/sandbox", "/tmp", "/dev/null", work]
2879
+ // The pnpm store is writable though /opt/crew is not; /opt/crew/bin (the binaries a run executes) stays read-only.
2880
+ read_write: ["/sandbox", "/tmp", "/dev/null", work, CREW_PNPM_STORE, CREW_PNPM_HOME, CREW_CACHE]
2877
2881
  },
2878
2882
  // A host that cannot enforce fails the run instead of running unconfined.
2879
2883
  landlock: { compatibility: "hard_requirement" },
@@ -6432,6 +6436,16 @@ function repoFindings(o) {
6432
6436
  for (const g of o.sandboxGaps ?? []) {
6433
6437
  problems.push({ severity: "attention", kind: "hook_missing", ...at, hook: g.hook, command: g.command, message: g.message, remedy: g.remedy });
6434
6438
  }
6439
+ if (o.sandboxStoreProblem !== void 0) {
6440
+ if (o.sandboxStoreProblem === null) passed++;
6441
+ else problems.push({
6442
+ severity: "attention",
6443
+ kind: "sandbox_store_unwritable",
6444
+ ...at,
6445
+ message: `${o.route}/${o.repo}: the pnpm store in its sandbox image cannot be written, so every offline \`pnpm install\` in a run fails (${o.sandboxStoreProblem})`,
6446
+ remedy: `rebuild the image with \`crew sandbox build ${o.repo}\`; the store at /opt/crew/pnpm-store must be owned by the sandbox user`
6447
+ });
6448
+ }
6435
6449
  for (const hook2 of o.sandboxGaps ? [] : HOOK_NAMES2) {
6436
6450
  const script = o.hooks[hook2];
6437
6451
  const command2 = script ? hookCommand(script) : null;
@@ -6511,7 +6525,7 @@ import { join as join31 } from "path";
6511
6525
 
6512
6526
  // src/agent.ts
6513
6527
  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";
6528
+ 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
6529
  import { StringDecoder } from "string_decoder";
6516
6530
  import { finished } from "stream/promises";
6517
6531
  import { join as join30, dirname as dirname15, basename as basename9 } from "path";
@@ -10362,14 +10376,14 @@ async function findTicketRecord(target, t, ref) {
10362
10376
  );
10363
10377
  return rows.length === 1 ? rows[0].id : void 0;
10364
10378
  }
10365
- function counterIncrements(run3, cols, have) {
10379
+ function counterIncrements(run4, cols, have) {
10366
10380
  const figures = [
10367
10381
  [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]
10382
+ [cols.tokensIn, run4.tokensIn],
10383
+ [cols.tokensOut, run4.tokensOut],
10384
+ [cols.cacheReadTokens, run4.cacheReadTokens],
10385
+ [cols.cacheWriteTokens, run4.cacheWriteTokens],
10386
+ [cols.costUsd, run4.costUsd]
10373
10387
  ];
10374
10388
  const out = {};
10375
10389
  for (const [column, value2] of figures) {
@@ -10448,42 +10462,42 @@ async function post(target, path, body) {
10448
10462
  if (!res.ok) throw new AgentLogHttpError(`${path}: ${res.status} ${res.statusText}`, res.status);
10449
10463
  return await res.json();
10450
10464
  }
10451
- async function reportAgentRun(target, run3) {
10465
+ async function reportAgentRun(target, run4) {
10452
10466
  let ticketRecordId;
10453
- if (target.tickets && run3.ticketReference) {
10467
+ if (target.tickets && run4.ticketReference) {
10454
10468
  try {
10455
- ticketRecordId = await findTicketRecord(target, target.tickets, run3.ticketReference);
10469
+ ticketRecordId = await findTicketRecord(target, target.tickets, run4.ticketReference);
10456
10470
  } catch {
10457
10471
  }
10458
10472
  }
10459
10473
  const body = {
10460
10474
  agentId: target.agentId,
10461
- ticketReference: run3.ticketReference,
10462
- outcome: run3.outcome,
10463
- startedAt: run3.startedAt,
10464
- finishedAt: run3.finishedAt,
10475
+ ticketReference: run4.ticketReference,
10476
+ outcome: run4.outcome,
10477
+ startedAt: run4.startedAt,
10478
+ finishedAt: run4.finishedAt,
10465
10479
  source: "client",
10466
10480
  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
10481
+ model: run4.model,
10482
+ tokensIn: run4.tokensIn,
10483
+ tokensOut: run4.tokensOut,
10484
+ cacheReadTokens: run4.cacheReadTokens,
10485
+ cacheWriteTokens: run4.cacheWriteTokens,
10486
+ costUsd: run4.costUsd,
10487
+ numTurns: run4.numTurns,
10488
+ prefixTokens: run4.prefixTokens,
10489
+ promptVersion: run4.promptVersion,
10490
+ promptSha: run4.promptSha
10477
10491
  };
10478
- const { runId, ...legacyBody } = { ...body, runId: run3.runId };
10492
+ const { runId, ...legacyBody } = { ...body, runId: run4.runId };
10479
10493
  const workItem = target.tickets && ticketRecordId ? { workItemTable: target.tickets.issuesModelId, workItemRecordId: ticketRecordId } : {};
10480
10494
  let entry;
10481
10495
  try {
10482
- entry = await post(target, "/agents/log", { ...body, ...runId ? { runId } : {}, ...workItem, harness: run3.harness, provider: run3.provider });
10496
+ entry = await post(target, "/agents/log", { ...body, ...runId ? { runId } : {}, ...workItem, harness: run4.harness, provider: run4.provider });
10483
10497
  } catch (e) {
10484
10498
  if (!(e instanceof AgentLogHttpError)) throw new AgentLogUnreachableError(e.message);
10485
10499
  if (e.status >= 500) throw new AgentLogUnreachableError(e.message);
10486
- if (e.status !== 400 || !run3.harness && !run3.provider && !ticketRecordId && !runId) {
10500
+ if (e.status !== 400 || !run4.harness && !run4.provider && !ticketRecordId && !runId) {
10487
10501
  e.row = true;
10488
10502
  throw e;
10489
10503
  }
@@ -10494,7 +10508,7 @@ async function reportAgentRun(target, run3) {
10494
10508
  throw e2;
10495
10509
  }
10496
10510
  }
10497
- for (const cycle of run3.cycles) {
10511
+ for (const cycle of run4.cycles) {
10498
10512
  await post(target, `/agents/log/${entry.id}/cycles`, {
10499
10513
  cycleIndex: cycle.cycleIndex,
10500
10514
  occurredAt: cycle.occurredAt,
@@ -10502,20 +10516,20 @@ async function reportAgentRun(target, run3) {
10502
10516
  ...cycle.role ? { role: cycle.role } : {}
10503
10517
  });
10504
10518
  }
10505
- if (run3.beforeFirstEdit) await writeBeforeFirstEdit(target, entry.id, run3.beforeFirstEdit);
10519
+ if (run4.beforeFirstEdit) await writeBeforeFirstEdit(target, entry.id, run4.beforeFirstEdit);
10506
10520
  if (target.tickets && ticketRecordId) {
10507
10521
  const bounces = await countAcceptanceBounces(target, target.tickets.issuesModelId, ticketRecordId);
10508
10522
  if (bounces !== null) await writeHandoffBounces(target, entry.id, bounces);
10509
10523
  }
10510
10524
  let counterWarning;
10511
- let counted = run3;
10525
+ let counted = run4;
10512
10526
  if (runId && target.tickets && ticketRecordId) {
10513
10527
  try {
10514
10528
  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 };
10529
+ if (totals) counted = { ...run4, tokensIn: totals.tokensIn, tokensOut: totals.tokensOut, cacheReadTokens: totals.cacheReadTokens, cacheWriteTokens: totals.cacheWriteTokens, costUsd: totals.costUsd };
10530
+ else counted = { ...run4, ...run4.harnessTotals };
10517
10531
  } catch (e) {
10518
- counterWarning = `could not sum run ${runId}'s inference rows for ${run3.ticketReference}: ${e.message}`;
10532
+ counterWarning = `could not sum run ${runId}'s inference rows for ${run4.ticketReference}: ${e.message}`;
10519
10533
  }
10520
10534
  }
10521
10535
  const counters = target.tickets && ticketRecordId ? await addRunToTicket(target, target.tickets, ticketRecordId, counted) : void 0;
@@ -10532,20 +10546,20 @@ async function writeCounters(target, w) {
10532
10546
  if (Object.keys(body).length === 0) return;
10533
10547
  await request(target, "PATCH", `/data-models/${w.issuesModelId}/records/${w.recordId}`, body);
10534
10548
  }
10535
- async function addRunToTicket(target, t, recordId, run3) {
10549
+ async function addRunToTicket(target, t, recordId, run4) {
10536
10550
  const write = {
10537
10551
  issuesModelId: t.issuesModelId,
10538
10552
  recordId,
10539
- ticketReference: run3.ticketReference,
10553
+ ticketReference: run4.ticketReference,
10540
10554
  counters: t.counters,
10541
- body: counterIncrements(run3, t.counters, new Set(Object.values(t.counters)))
10555
+ body: counterIncrements(run4, t.counters, new Set(Object.values(t.counters)))
10542
10556
  };
10543
10557
  try {
10544
10558
  await writeCounters(target, write);
10545
10559
  return {};
10546
10560
  } catch (e) {
10547
10561
  return {
10548
- warning: `could not add run spend to ${run3.ticketReference}: ${e.message}`,
10562
+ warning: `could not add run spend to ${run4.ticketReference}: ${e.message}`,
10549
10563
  ...isRetryable(e) ? { retry: write } : {}
10550
10564
  };
10551
10565
  }
@@ -10878,7 +10892,7 @@ var HandoffTranscriptTracker = class {
10878
10892
  import { createHash as createHash4 } from "crypto";
10879
10893
  import { spawn as spawn3 } from "child_process";
10880
10894
  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";
10895
+ 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
10896
  import { dirname as dirname13, join as join26 } from "path";
10883
10897
  import { fileURLToPath } from "url";
10884
10898
  import { tmpdir as tmpdir3 } from "os";
@@ -11114,6 +11128,7 @@ function sandboxImageStatus(state, plan) {
11114
11128
  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
11129
  return { status: "ok", detail: `${current.tag} built ${current.builtAt}, claude ${current.claude ?? "unknown"}` };
11116
11130
  }
11131
+ var BUILD_INTERRUPTED = -1;
11117
11132
  var spawnBuildRunner = (engine = "docker") => (args, logPath) => new Promise((resolve8) => {
11118
11133
  const child = spawn3(engine, args, { stdio: ["ignore", "pipe", "pipe"] });
11119
11134
  const chunks = [];
@@ -11126,7 +11141,7 @@ ${Buffer.concat(chunks).toString("utf8")}${extra}`, { flag: "a" });
11126
11141
  };
11127
11142
  child.on("error", (e) => done(127, `${e.message}
11128
11143
  `));
11129
- child.on("close", (code) => done(code ?? 1));
11144
+ child.on("close", (code) => done(code ?? BUILD_INTERRUPTED));
11130
11145
  });
11131
11146
  var engineHasImage = (engine = "docker", exec = realExec) => (tag) => {
11132
11147
  try {
@@ -11166,6 +11181,7 @@ async function buildSandboxImage(plan, deps) {
11166
11181
  }
11167
11182
  if (layer.caBundleFile) writeFileSync18(join26(ctx, layer.caBundleFile), (deps.caBundle ?? readHostCaBundle)());
11168
11183
  const code = await deps.run(["build", "--tag", layer.tag, "--file", join26(ctx, "Dockerfile"), ctx], logPath);
11184
+ if (code === BUILD_INTERRUPTED) return { kind: "interrupted", tag: plan.tag };
11169
11185
  if (code !== 0) {
11170
11186
  state[plan.repo] = { ...entry, failure: { tag: plan.tag, at: now().toISOString(), logPath } };
11171
11187
  writeSandboxState(deps.stateDir, state);
@@ -11192,9 +11208,20 @@ function sandboxFailedItem(repo, tag, layer, logPath, nowIso = (/* @__PURE__ */
11192
11208
  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
11209
  };
11194
11210
  }
11211
+ function failureLogIsEmpty(failure) {
11212
+ try {
11213
+ return statSync8(failure.logPath).size === 0;
11214
+ } catch {
11215
+ return true;
11216
+ }
11217
+ }
11195
11218
  async function sandboxBuildTick(repos, deps, force = false) {
11196
11219
  const nowMs = (deps.now ?? (() => /* @__PURE__ */ new Date()))().getTime();
11197
11220
  for (const r of repos) {
11221
+ if (r.unreadable) {
11222
+ deps.log(`sandbox image for ${r.name}: not building, ${r.unreadable}`);
11223
+ continue;
11224
+ }
11198
11225
  const plan = planSandbox(r.name, r.decl, r.warm, r.bridge);
11199
11226
  const state = readSandboxState(deps.stateDir)[r.name];
11200
11227
  const upToDate = state?.tags[0]?.tag === plan.tag && deps.hasImage(plan.tag);
@@ -11203,10 +11230,12 @@ async function sandboxBuildTick(repos, deps, force = false) {
11203
11230
  continue;
11204
11231
  }
11205
11232
  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;
11233
+ if (!force && !present && state?.failure?.tag === plan.tag && nowMs - Date.parse(state.failure.at) < SANDBOX_RETRY_AFTER_MS && !failureLogIsEmpty(state.failure)) continue;
11207
11234
  deps.log(`sandbox image for ${r.name}: ${present ? `found ${plan.tag} in the engine, recording it` : `building ${plan.tag}`}`);
11208
11235
  const out = await buildSandboxImage(plan, deps);
11209
- if (out.kind === "failed") {
11236
+ if (out.kind === "interrupted") {
11237
+ deps.log(`sandbox image for ${r.name}: build of ${out.tag} was interrupted; it restarts on the next pass`);
11238
+ } else if (out.kind === "failed") {
11210
11239
  deps.raise(sandboxFailedItem(r.name, out.tag, out.layer, out.logPath));
11211
11240
  deps.log(`sandbox image for ${r.name}: build failed at the ${out.layer} layer, log ${out.logPath}`);
11212
11241
  } else {
@@ -12048,6 +12077,16 @@ function sandboxName(plan, now = Date.now()) {
12048
12077
  const tag = (h.readUInt32BE(0) % 36 ** 6).toString(36).padStart(6, "0");
12049
12078
  return `crew-${tag}${now.toString(36).slice(-8).padStart(8, "0")}`;
12050
12079
  }
12080
+ function labelValue(v) {
12081
+ return v.replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 63);
12082
+ }
12083
+ function sandboxLabels(o) {
12084
+ return [
12085
+ `crew.role=${labelValue(o.role)}`,
12086
+ ...o.ticket ? [`crew.ticket=${labelValue(o.ticket)}`] : [],
12087
+ `crew.run=${labelValue(o.run)}`
12088
+ ];
12089
+ }
12051
12090
  var SandboxRunner = class {
12052
12091
  kind = "sandbox";
12053
12092
  cfg;
@@ -12090,6 +12129,7 @@ var SandboxRunner = class {
12090
12129
  }
12091
12130
  const create2 = ["sandbox", "create", "--name", name, "--detach"];
12092
12131
  if (policyFile) create2.push("--policy", policyFile);
12132
+ for (const l of sandboxLabels({ role: plan.role, ticket: plan.ticket, run: basename8(plan.streamPath).replace(/\.jsonl$/, "") })) create2.push("--label", l);
12093
12133
  const image = cfg.image ?? plan.sandboxImage;
12094
12134
  if (image) create2.push("--from", image);
12095
12135
  if (cfg.cacheVolume) {
@@ -12212,16 +12252,16 @@ function runnerOfSidecar(sc) {
12212
12252
  return sc.runner === "sandbox" ? new SandboxRunner(sc.sandboxBin ? { bin: sc.sandboxBin } : {}) : new HostRunner();
12213
12253
  }
12214
12254
  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 })) {
12255
+ function checkSandboxRunner(cfg = {}, run4 = (b, a, t) => execFileSync8(b, a, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: t ?? 15e3 })) {
12216
12256
  const bin = cfg.bin ?? DEFAULT_SANDBOX_CONFIG.bin;
12217
12257
  let version;
12218
12258
  try {
12219
- version = run3(bin, ["--version"]).trim();
12259
+ version = run4(bin, ["--version"]).trim();
12220
12260
  } catch (e) {
12221
12261
  return { ok: false, detail: `${bin} is not installed or not on the scheduler PATH (${e.message.split("\n")[0]})` };
12222
12262
  }
12223
12263
  try {
12224
- run3(bin, ["status"]);
12264
+ run4(bin, ["status"]);
12225
12265
  } catch (e) {
12226
12266
  const err3 = e;
12227
12267
  return {
@@ -12231,7 +12271,7 @@ function checkSandboxRunner(cfg = {}, run3 = (b, a, t) => execFileSync8(b, a, {
12231
12271
  }
12232
12272
  const probe = sandboxName({ route: "doctor", role: "dev", ticket: void 0 });
12233
12273
  try {
12234
- run3(bin, ["sandbox", "create", "--name", probe, "--detach", "--", "sleep", "60"], PROBE_CREATE_TIMEOUT_MS);
12274
+ run4(bin, ["sandbox", "create", "--name", probe, "--detach", "--", "sleep", "60"], PROBE_CREATE_TIMEOUT_MS);
12235
12275
  } catch (e) {
12236
12276
  const err3 = e;
12237
12277
  if (err3.code === "ETIMEDOUT" || err3.killed) {
@@ -12240,7 +12280,7 @@ function checkSandboxRunner(cfg = {}, run3 = (b, a, t) => execFileSync8(b, a, {
12240
12280
  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
12281
  } finally {
12242
12282
  try {
12243
- run3(bin, ["sandbox", "delete", probe]);
12283
+ run4(bin, ["sandbox", "delete", probe]);
12244
12284
  } catch {
12245
12285
  }
12246
12286
  }
@@ -12420,7 +12460,7 @@ function planAgentRun(o) {
12420
12460
  let digest;
12421
12461
  let ageSeconds;
12422
12462
  if (existsSync27(digestPath2)) {
12423
- ageSeconds = Math.floor((now() - statSync8(digestPath2).mtimeMs) / 1e3);
12463
+ ageSeconds = Math.floor((now() - statSync9(digestPath2).mtimeMs) / 1e3);
12424
12464
  if (ageSeconds <= DIGEST_MAX_AGE_SECONDS) digest = readFileSync27(digestPath2, "utf8");
12425
12465
  }
12426
12466
  const common = usesCommon ? readFileSync27(commonPath, "utf8") : "";
@@ -13029,9 +13069,9 @@ function spawnAgent(plan, emit, hintMoved) {
13029
13069
  }
13030
13070
  if (begun instanceof Promise) {
13031
13071
  return begun.then(
13032
- (run3) => {
13072
+ (run4) => {
13033
13073
  closeSync4(streamFd);
13034
- return supervise(run3);
13074
+ return supervise(run4);
13035
13075
  },
13036
13076
  (e) => {
13037
13077
  closeSync4(streamFd);
@@ -13250,7 +13290,7 @@ async function reconcileRuns(o) {
13250
13290
  }
13251
13291
 
13252
13292
  // src/live-runs.ts
13253
- import { existsSync as existsSync29, readdirSync as readdirSync10, statSync as statSync9 } from "fs";
13293
+ import { existsSync as existsSync29, readdirSync as readdirSync10, statSync as statSync10 } from "fs";
13254
13294
  import { join as join32 } from "path";
13255
13295
  function liveRuns(stateDir, isAlive = runIsAlive) {
13256
13296
  const dir = join32(stateDir, "streams");
@@ -13276,7 +13316,7 @@ function runActivity(stateDir, isAlive = runIsAlive) {
13276
13316
  const streamPath = join32(dir, name);
13277
13317
  if (!runFinished(streamPath)) continue;
13278
13318
  try {
13279
- newest = Math.max(newest, statSync9(`${streamPath}.meta.json`).mtimeMs);
13319
+ newest = Math.max(newest, statSync10(`${streamPath}.meta.json`).mtimeMs);
13280
13320
  } catch {
13281
13321
  }
13282
13322
  }
@@ -13312,27 +13352,27 @@ async function settleRunEnd(o) {
13312
13352
  emit.warn(`could not beat ship idle: ${e.message}`, { step: "agent" });
13313
13353
  }
13314
13354
  }
13315
- function describeRun(run3, route2, seatIds, worktreeOf = (d, n) => {
13355
+ function describeRun(run4, route2, seatIds, worktreeOf = (d, n) => {
13316
13356
  try {
13317
13357
  return worktreeForNumber(d, n)?.path ?? null;
13318
13358
  } catch {
13319
13359
  return null;
13320
13360
  }
13321
13361
  }) {
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+/, "") ?? "";
13362
+ const ownRoute = run4.route === routeSlug(route2.route);
13363
+ const repoDir = run4.repo ? reposOf(route2).find((t) => t.name === run4.repo)?.dir : void 0;
13364
+ const num2 = run4.ticket?.replace(/^\D+/, "") ?? "";
13325
13365
  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,
13366
+ role: run4.role,
13367
+ seat: ownRoute ? seatIds[run4.role] ?? null : null,
13368
+ ticket: run4.ticket,
13369
+ ticketRecordId: run4.ticketRecordId,
13370
+ repo: run4.repo ?? null,
13331
13371
  worktree: repoDir && num2 ? worktreeOf(repoDir, num2) : null,
13332
- stream: run3.streamPath,
13333
- pid: run3.pid,
13334
- startedAt: run3.spawnedAt,
13335
- deadline: run3.deadline ?? null
13372
+ stream: run4.streamPath,
13373
+ pid: run4.pid,
13374
+ startedAt: run4.spawnedAt,
13375
+ deadline: run4.deadline ?? null
13336
13376
  };
13337
13377
  }
13338
13378
 
@@ -13372,22 +13412,22 @@ function realDeprovisionDeps(cfg, emit, crewHome, getStore) {
13372
13412
  };
13373
13413
  return {
13374
13414
  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`, {
13415
+ killRun: (run4) => killRunGroup(run4.pid),
13416
+ recordKill(run4) {
13417
+ emit.emit(`run_killed: ${run4.role} run on ${run4.route} stopped by crew deprovision`, {
13378
13418
  step: "agent",
13379
- role: run3.role,
13380
- data: { event: "run_killed", reason: "deprovision", pid: run3.pid }
13419
+ role: run4.role,
13420
+ data: { event: "run_killed", reason: "deprovision", pid: run4.pid }
13381
13421
  });
13382
13422
  },
13383
- async handBack(run3) {
13384
- const route2 = routeFor(run3.route);
13385
- if (!run3.ticketRecordId || !route2) return;
13386
- const memberId = route2.resolved?.seats[run3.role];
13423
+ async handBack(run4) {
13424
+ const route2 = routeFor(run4.route);
13425
+ if (!run4.ticketRecordId || !route2) return;
13426
+ const memberId = route2.resolved?.seats[run4.role];
13387
13427
  if (!memberId) return;
13388
- const identity = await resolveSeatKey(route2, run3.role, getStore);
13428
+ const identity = await resolveSeatKey(route2, run4.role, getStore);
13389
13429
  const tracker = new Tracker(route2, cfg.ship, { apiKey: identity.apiKey });
13390
- const t = await tracker.ticket(run3.ticketRecordId);
13430
+ const t = await tracker.ticket(run4.ticketRecordId);
13391
13431
  const target = repoTargetFor(route2, t.repo_id);
13392
13432
  const num2 = String(t[tracker.contract.columns.key] ?? "").replace(/^\D+/, "");
13393
13433
  const wt = target && num2 ? worktreeForNumber(target.dir, num2) : null;
@@ -13396,7 +13436,7 @@ function realDeprovisionDeps(cfg, emit, crewHome, getStore) {
13396
13436
  if (wt) dirty = status(wt.path).length > 0;
13397
13437
  } catch {
13398
13438
  }
13399
- await tracker.postEvent(run3.ticketRecordId, interruptedComment({
13439
+ await tracker.postEvent(run4.ticketRecordId, interruptedComment({
13400
13440
  branch: wt?.branch ?? null,
13401
13441
  dirty,
13402
13442
  reason: "the host was released and wiped"
@@ -14073,6 +14113,14 @@ function sandboxHookGaps(o) {
14073
14113
  }
14074
14114
  return gaps;
14075
14115
  }
14116
+ var imageStoreProblem = (engine = "docker", exec = realExec) => (image) => {
14117
+ try {
14118
+ exec(engine, ["run", "--rm", "--entrypoint", "sh", image, "-c", 'd=/opt/crew/pnpm-store; test -d $d && t=$(mktemp -p $d) && rm -f "$t"'], { timeoutMs: 6e4 });
14119
+ return null;
14120
+ } catch (e) {
14121
+ return e.message.split("\n")[0] || "write test failed";
14122
+ }
14123
+ };
14076
14124
 
14077
14125
  // src/doctor-checks.ts
14078
14126
  import { execFileSync as execFileSync10, spawnSync as spawnSync8 } from "child_process";
@@ -14086,12 +14134,12 @@ function isSshRemote(url) {
14086
14134
  function pushAuthHint(remoteUrl) {
14087
14135
  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
14136
  }
14089
- function probePushAuth(o, run3 = realGit, baseEnv = process.env) {
14137
+ function probePushAuth(o, run4 = realGit, baseEnv = process.env) {
14090
14138
  if (o.offline) return { state: "skipped", detail: "skipped (--offline)" };
14091
14139
  if (!o.remoteUrl) return { state: "skipped", detail: `no remote "${o.remote}" configured` };
14092
14140
  const env = { ...baseEnv, GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "never", GIT_SSH_COMMAND: `${baseEnv.GIT_SSH_COMMAND ?? "ssh"} -o BatchMode=yes` };
14093
14141
  try {
14094
- run3(o.dir, ["push", "--dry-run", o.remote, `HEAD:refs/heads/${PROBE_BRANCH}`], env);
14142
+ run4(o.dir, ["push", "--dry-run", o.remote, `HEAD:refs/heads/${PROBE_BRANCH}`], env);
14095
14143
  return { state: "ok" };
14096
14144
  } catch (e) {
14097
14145
  const err3 = e;
@@ -14107,7 +14155,7 @@ function probePushAuth(o, run3 = realGit, baseEnv = process.env) {
14107
14155
  };
14108
14156
  }
14109
14157
  try {
14110
- run3(o.dir, ["ls-remote", "--exit-code", o.remote, "HEAD"], env);
14158
+ run4(o.dir, ["ls-remote", "--exit-code", o.remote, "HEAD"], env);
14111
14159
  return {
14112
14160
  state: "failed",
14113
14161
  detail: `the token for forge ${f.host} is read-only (fetch works, push refused): ${detail}`,
@@ -14149,8 +14197,8 @@ function formatToolCheck(t) {
14149
14197
  return `${label}${t.need === "required" ? "NOT FOUND" : "not found"} [${t.need}] \u2014 ${t.hint}
14150
14198
  `;
14151
14199
  }
14152
- function probeCredentialHelper(command2, run3 = realHelperRun) {
14153
- const r = run3(`${command2} credential get --no-miss`, "protocol=https\nhost=crew-probe.invalid\n\n");
14200
+ function probeCredentialHelper(command2, run4 = realHelperRun) {
14201
+ const r = run4(`${command2} credential get --no-miss`, "protocol=https\nhost=crew-probe.invalid\n\n");
14154
14202
  if (r.status === 0 && !/unknown command|usage:/i.test(r.stderr)) return { state: "ok" };
14155
14203
  const why = r.stderr.trim().split("\n")[0] || `exit ${r.status}`;
14156
14204
  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 +14405,17 @@ var REMEDY = {
14357
14405
  timeout: "the harness did not answer in time \u2014 run it by hand to see where it stalls",
14358
14406
  "wrong-answer": "the agent answered but did not name the workspace \u2014 run it by hand to see what it said"
14359
14407
  };
14360
- function classify(spec, run3, seen) {
14408
+ function classify(spec, run4, seen) {
14361
14409
  const bin = spec.launcher ?? spec.bin;
14362
14410
  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})`);
14411
+ if (run4.spawnError) {
14412
+ if (run4.spawnError.code === "ENOENT") return fail2("binary-not-found", `\`${bin}\` is not on the scheduler PATH`);
14413
+ return fail2("binary-not-found", `could not start \`${bin}\` (${run4.spawnError.message})`);
14366
14414
  }
14367
- if (run3.timedOut) return fail2("timeout", "no answer within the time limit");
14415
+ if (run4.timedOut) return fail2("timeout", "no answer within the time limit");
14368
14416
  const text2 = `${seen.toolOutput}
14369
- ${run3.stderr}`;
14370
- if (REFUSED.test(seen.toolOutput) || seen.tools.some((t) => t.startsWith("mcp__")) && REFUSED.test(run3.stderr)) {
14417
+ ${run4.stderr}`;
14418
+ if (REFUSED.test(seen.toolOutput) || seen.tools.some((t) => t.startsWith("mcp__")) && REFUSED.test(run4.stderr)) {
14371
14419
  return fail2("key-refused", "the tracker returned 401/403 to the MCP call");
14372
14420
  }
14373
14421
  if (seen.mcpFailed || !seen.tools.some((t) => t.startsWith("mcp__")) && MCP_GONE.test(`${text2}
@@ -14375,13 +14423,13 @@ ${seen.texts.join("\n")}`)) {
14375
14423
  return fail2("mcp-unavailable", "the tracker MCP tool was not available to the session");
14376
14424
  }
14377
14425
  const answered = seen.texts.length > 0 || seen.finalText;
14378
- if (SIGNED_OUT_PATTERN.test(`${run3.stderr}
14426
+ if (SIGNED_OUT_PATTERN.test(`${run4.stderr}
14379
14427
  ${seen.finalText ?? ""}
14380
14428
  ${seen.texts.join("\n")}`)) {
14381
14429
  return { failure: "login-missing", detail: signedOutMessage(spec.name, authModeOf(spec)) };
14382
14430
  }
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`);
14431
+ if (!answered || LOGIN.test(run4.stderr) || LOGIN.test(seen.finalText ?? "")) {
14432
+ return fail2("login-missing", `\`${bin}\` exited${run4.code !== null ? ` (${run4.code})` : ""} before answering; the vendor login is probably missing`);
14385
14433
  }
14386
14434
  return fail2("wrong-answer", `the agent replied "${(seen.finalText ?? seen.texts.at(-1) ?? "").trim().slice(0, 80)}"`);
14387
14435
  }
@@ -14411,7 +14459,7 @@ async function runSelftest(i, deps = realDeps) {
14411
14459
  };
14412
14460
  const cwd = mkdtempSync2(join33(tmpdir5(), "crew-selftest-"));
14413
14461
  try {
14414
- const run3 = await deps.run({
14462
+ const run4 = await deps.run({
14415
14463
  bin: invocation.bin,
14416
14464
  args: invocation.args,
14417
14465
  cwd,
@@ -14420,14 +14468,14 @@ async function runSelftest(i, deps = realDeps) {
14420
14468
  `,
14421
14469
  timeoutMs: i.timeoutMs ?? SELFTEST_TIMEOUT_MS
14422
14470
  });
14423
- const seen = observe(spec, run3.stdout);
14471
+ const seen = observe(spec, run4.stdout);
14424
14472
  const answer = [seen.finalText ?? "", ...seen.texts].join("\n");
14425
14473
  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())) {
14474
+ if (!run4.spawnError && !run4.timedOut && answer.toLowerCase().includes(i.workspaceName.toLowerCase())) {
14427
14475
  const auth = spec.harness === "claude" ? ` on ${describeClaudeAuth(spec)}` : "";
14428
14476
  return finish({ ok: true, workspace: i.workspaceName, detail: `read workspace "${i.workspaceName}"${auth}`, ...usage2 });
14429
14477
  }
14430
- const { failure, detail } = classify(spec, run3, seen);
14478
+ const { failure, detail } = classify(spec, run4, seen);
14431
14479
  return finish({ ok: false, failure, detail, ...usage2 });
14432
14480
  } finally {
14433
14481
  try {
@@ -14773,7 +14821,7 @@ async function signOutSessions(o) {
14773
14821
  }
14774
14822
 
14775
14823
  // 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";
14824
+ 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
14825
  import { dirname as dirname17, join as join35 } from "path";
14778
14826
  import { hostFromUrl as hostFromUrl3 } from "@tablation/client";
14779
14827
  function clonedCheckoutsFile(stateDir) {
@@ -14871,7 +14919,7 @@ function removeState(stateDir, dryRun) {
14871
14919
  const targets = [join35(stateDir, "resolved"), join35(stateDir, "keys"), clonedCheckoutsFile(stateDir), join35(stateDir, "connect-session.json"), join35(stateDir, "reload-requested"), join35(stateDir, "daemon.started")];
14872
14920
  try {
14873
14921
  for (const name of readdirSync12(stateDir)) {
14874
- if (name.startsWith(".") && statSync10(join35(stateDir, name)).isFile()) targets.push(join35(stateDir, name));
14922
+ if (name.startsWith(".") && statSync11(join35(stateDir, name)).isFile()) targets.push(join35(stateDir, name));
14875
14923
  }
14876
14924
  } catch {
14877
14925
  }
@@ -14915,21 +14963,21 @@ async function runDeprovision(o, fx, deps) {
14915
14963
  };
14916
14964
  const afterScheduler = async () => {
14917
14965
  const steps2 = [];
14918
- for (const run3 of deps.liveRuns()) {
14919
- const target = `${run3.role} run on ${run3.route} (pid ${run3.pid})`;
14966
+ for (const run4 of deps.liveRuns()) {
14967
+ const target = `${run4.role} run on ${run4.route} (pid ${run4.pid})`;
14920
14968
  if (o.dryRun) {
14921
14969
  steps2.push({ step: "run", target, action: "would-remove" });
14922
14970
  continue;
14923
14971
  }
14924
14972
  try {
14925
- await deps.killRun(run3);
14926
- deps.recordKill(run3);
14973
+ await deps.killRun(run4);
14974
+ deps.recordKill(run4);
14927
14975
  } catch (e) {
14928
14976
  steps2.push({ step: "run", target, action: "failed", detail: e.message });
14929
14977
  continue;
14930
14978
  }
14931
14979
  try {
14932
- await deps.handBack(run3);
14980
+ await deps.handBack(run4);
14933
14981
  steps2.push({ step: "run", target, action: "removed", detail: "killed" });
14934
14982
  } catch (e) {
14935
14983
  steps2.push({ step: "run", target, action: "removed", detail: `killed; could not tell its ticket (${e.message})` });
@@ -17182,6 +17230,191 @@ ${waiting.map((t) => `| ${displayKey2(t)} | ${t.status} | ${blockers(t, i)} |`).
17182
17230
  ]);
17183
17231
  }
17184
17232
 
17233
+ // src/sandbox-hygiene.ts
17234
+ import { execFile as execFile3 } from "child_process";
17235
+ import { existsSync as existsSync37, statfsSync as statfsSync2 } from "fs";
17236
+ import { promisify as promisify3 } from "util";
17237
+ var execFileP3 = promisify3(execFile3);
17238
+ var REAP_MIN_AGE_MS = 5 * 6e4;
17239
+ var LEAK_CLEAR_AFTER_MS = 60 * 6e4;
17240
+ var DISK_WARN_PERCENT = 85;
17241
+ var DISK_STOP_PERCENT = 95;
17242
+ var DISK_RESUME_PERCENT = 90;
17243
+ var HYGIENE_INTERVAL_MS = 3e4;
17244
+ var SANDBOX_LEAK_KEY = "sandbox_leak";
17245
+ var DISK_PRESSURE_KEY = "disk_pressure";
17246
+ var DISK_FULL_KEY = "disk_full";
17247
+ var SANDBOX_IN_CONTAINER = /crew-[0-9a-z]{14}/;
17248
+ function parseDockerCreatedAt(s) {
17249
+ const m = /^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})(?:\.\d+)? ([+-])(\d{2})(\d{2})/.exec(s.trim());
17250
+ if (!m) return null;
17251
+ const t = Date.parse(`${m[1]}T${m[2]}${m[3]}${m[4]}:${m[5]}`);
17252
+ return Number.isNaN(t) ? null : t;
17253
+ }
17254
+ async function reapOrphanContainers(d, minAgeMs = REAP_MIN_AGE_MS) {
17255
+ const gateway = await d.gatewaySandboxes();
17256
+ if (gateway === null) return [];
17257
+ const known = /* @__PURE__ */ new Set([...gateway, ...d.liveSandboxes()]);
17258
+ const prefix = `openshell-${d.workspace}--`;
17259
+ const out = [];
17260
+ for (const c of await d.containers()) {
17261
+ if (!c.name.startsWith(prefix)) continue;
17262
+ const sandbox = SANDBOX_IN_CONTAINER.exec(c.name)?.[0];
17263
+ if (!sandbox || known.has(sandbox)) continue;
17264
+ const ageMs = d.now() - c.createdMs;
17265
+ if (ageMs < minAgeMs) continue;
17266
+ await d.remove(c.name);
17267
+ out.push({ container: c.name, ageMs });
17268
+ }
17269
+ return out;
17270
+ }
17271
+ function usedPercentAt(path) {
17272
+ try {
17273
+ const s = statfsSync2(path);
17274
+ const used = Number(s.blocks) - Number(s.bfree);
17275
+ const total = used + Number(s.bavail);
17276
+ return total > 0 ? used / total * 100 : null;
17277
+ } catch {
17278
+ return null;
17279
+ }
17280
+ }
17281
+ function fullest(readings) {
17282
+ return readings.reduce((a, r) => !a || r.percent > a.percent ? r : a, null);
17283
+ }
17284
+ function diskVerdict(percent, stopped) {
17285
+ if (percent >= DISK_STOP_PERCENT || stopped && percent >= DISK_RESUME_PERCENT) return "stop";
17286
+ return percent >= DISK_WARN_PERCENT ? "warn" : "ok";
17287
+ }
17288
+ async function checkDisk(o, d, nowIso = (/* @__PURE__ */ new Date()).toISOString()) {
17289
+ const raise = (item) => raiseShipAttention({ state: o.state, emit: o.emit, ship: o.ship, ...o.route ? { route: o.route } : {} }, item);
17290
+ const stopped = openShipAttention(o.state).some((i) => i.key === DISK_FULL_KEY);
17291
+ let worst = fullest(await d.readings());
17292
+ if (!worst) return;
17293
+ let verdict = diskVerdict(worst.percent, stopped);
17294
+ if (verdict === "stop" && !stopped) {
17295
+ await d.reclaim();
17296
+ worst = fullest(await d.readings()) ?? worst;
17297
+ verdict = diskVerdict(worst.percent, false);
17298
+ }
17299
+ const pct = `${Math.round(worst.percent)}%`;
17300
+ if (verdict === "stop") {
17301
+ clearShipAttention(o.state, DISK_PRESSURE_KEY);
17302
+ await raise({
17303
+ kind: "disk_full",
17304
+ key: DISK_FULL_KEY,
17305
+ since: nowIso,
17306
+ 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`
17307
+ });
17308
+ } else if (verdict === "warn") {
17309
+ clearShipAttention(o.state, DISK_FULL_KEY);
17310
+ await raise({
17311
+ kind: "disk_pressure",
17312
+ key: DISK_PRESSURE_KEY,
17313
+ since: nowIso,
17314
+ message: `${worst.path} is ${pct} full \u2014 runs stop at ${DISK_STOP_PERCENT}%. Resumes normal reporting once it is below ${DISK_WARN_PERCENT}%`
17315
+ });
17316
+ } else {
17317
+ clearShipAttention(o.state, DISK_FULL_KEY);
17318
+ clearShipAttention(o.state, DISK_PRESSURE_KEY);
17319
+ }
17320
+ }
17321
+ async function reportReaped(o, reaped, nowMs = Date.now()) {
17322
+ const prior = openShipAttention(o.state).find((i) => i.key === SANDBOX_LEAK_KEY);
17323
+ if (reaped.length === 0) {
17324
+ if (prior?.lastReapedAt && nowMs - Date.parse(prior.lastReapedAt) > LEAK_CLEAR_AFTER_MS) clearShipAttention(o.state, SANDBOX_LEAK_KEY);
17325
+ return;
17326
+ }
17327
+ for (const r of reaped) {
17328
+ o.emit.warn(`sandbox_reaped: removed ${r.container} (${Math.round(r.ageMs / 6e4)} min old, no live run)`, {
17329
+ data: { event: "sandbox_reaped", container: r.container, ageMs: r.ageMs }
17330
+ });
17331
+ }
17332
+ const total = (prior?.count ?? 0) + reaped.length;
17333
+ await raiseShipAttention(o, {
17334
+ kind: "sandbox_leak",
17335
+ key: SANDBOX_LEAK_KEY,
17336
+ since: new Date(nowMs).toISOString(),
17337
+ count: total,
17338
+ lastReapedAt: new Date(nowMs).toISOString(),
17339
+ 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`
17340
+ });
17341
+ }
17342
+ async function run3(bin, args) {
17343
+ return (await execFileP3(bin, args, { timeout: 6e4, maxBuffer: 16 * 1024 * 1024 })).stdout;
17344
+ }
17345
+ function realReapDeps(ship) {
17346
+ const engine = ship.sandbox?.engine ?? DEFAULT_CACHE_SETTINGS.engine;
17347
+ const osBin = ship.sandbox?.bin ?? "openshell";
17348
+ return {
17349
+ workspace: ship.sandbox?.cacheWorkspace ?? DEFAULT_CACHE_SETTINGS.workspace,
17350
+ containers: async () => {
17351
+ const out = await run3(engine, ["ps", "-a", "--no-trunc", "--format", "{{.Names}} {{.CreatedAt}}"]);
17352
+ const rows = [];
17353
+ for (const line of out.split("\n")) {
17354
+ const [name, created] = line.split(" ");
17355
+ const createdMs = created ? parseDockerCreatedAt(created) : null;
17356
+ if (name && createdMs !== null) rows.push({ name, createdMs });
17357
+ }
17358
+ return rows;
17359
+ },
17360
+ gatewaySandboxes: async () => {
17361
+ try {
17362
+ return [...(await run3(osBin, ["sandbox", "list"])).matchAll(/crew-[0-9a-z]{14}/g)].map((m) => m[0]);
17363
+ } catch {
17364
+ return null;
17365
+ }
17366
+ },
17367
+ liveSandboxes: () => liveRuns(ship.stateDir).flatMap((r) => r.sandbox ? [r.sandbox] : []),
17368
+ remove: async (name) => {
17369
+ await run3(engine, ["rm", "-f", name]);
17370
+ },
17371
+ now: () => Date.now()
17372
+ };
17373
+ }
17374
+ async function realDiskReadings(ship) {
17375
+ const paths = ["/"];
17376
+ try {
17377
+ const root = (await run3(ship.sandbox?.engine ?? DEFAULT_CACHE_SETTINGS.engine, ["info", "--format", "{{.DockerRootDir}}"])).trim();
17378
+ if (root && existsSync37(root)) paths.push(root);
17379
+ } catch {
17380
+ }
17381
+ return paths.flatMap((path) => {
17382
+ const percent = usedPercentAt(path);
17383
+ return percent === null ? [] : [{ path, percent }];
17384
+ });
17385
+ }
17386
+ function makeSandboxHygiene(o) {
17387
+ const now = o.now ?? Date.now;
17388
+ let last = -Infinity;
17389
+ return async () => {
17390
+ if (now() - last < HYGIENE_INTERVAL_MS) return;
17391
+ last = now();
17392
+ const deps = realReapDeps(o.ship);
17393
+ try {
17394
+ await reportReaped(o, await reapOrphanContainers(deps), now());
17395
+ } catch (e) {
17396
+ o.emit.warn(`sandbox reaper failed: ${e instanceof Error ? e.message : String(e)}`);
17397
+ }
17398
+ try {
17399
+ await checkDisk(o, {
17400
+ readings: () => realDiskReadings(o.ship),
17401
+ reclaim: async () => {
17402
+ await reportReaped(o, await reapOrphanContainers(deps), now());
17403
+ try {
17404
+ await run3(o.ship.sandbox?.engine ?? DEFAULT_CACHE_SETTINGS.engine, ["builder", "prune", "-f"]);
17405
+ } catch {
17406
+ }
17407
+ }
17408
+ });
17409
+ } catch (e) {
17410
+ o.emit.warn(`disk check failed: ${e instanceof Error ? e.message : String(e)}`);
17411
+ }
17412
+ };
17413
+ }
17414
+ function diskFullStop(state) {
17415
+ return openShipAttention(state).find((i) => i.kind === "disk_full")?.message ?? null;
17416
+ }
17417
+
17185
17418
  // src/poll.ts
17186
17419
  import { writeFileSync as writeFileSync28 } from "fs";
17187
17420
  import { join as join40 } from "path";
@@ -17437,8 +17670,9 @@ async function decideCycle(o) {
17437
17670
  await checkRepoDisks({ state, emit, route: route2, ship });
17438
17671
  const floorStop = await checkCrewFloor({ state, emit, route: route2, ship });
17439
17672
  const itemStop = repoStopFor(openShipAttention(state), route2);
17673
+ const diskStop = diskFullStop(state);
17440
17674
  const selectionInput = {
17441
- repoStop: floorStop ? () => floorStop : itemStop,
17675
+ repoStop: floorStop ? () => floorStop : diskStop ? () => diskStop : itemStop,
17442
17676
  workModes,
17443
17677
  tickets,
17444
17678
  comments,
@@ -17683,7 +17917,7 @@ async function resolveOne(tracker, t, seat, approvedStatus, buildingStatus, affi
17683
17917
  }
17684
17918
 
17685
17919
  // src/repo-refresh.ts
17686
- import { existsSync as existsSync37, mkdirSync as mkdirSync26, readFileSync as readFileSync36, writeFileSync as writeFileSync29 } from "fs";
17920
+ import { existsSync as existsSync38, mkdirSync as mkdirSync26, readFileSync as readFileSync36, writeFileSync as writeFileSync29 } from "fs";
17687
17921
  import { dirname as dirname21 } from "path";
17688
17922
  var REFRESH_COOLDOWN_MS = 2 * 6e4;
17689
17923
  var UNSERVABLE_PASSES_BEFORE_ATTENTION = 3;
@@ -17713,7 +17947,7 @@ function applyRepoRows(resolved, rows) {
17713
17947
  }
17714
17948
  function persistRepoRows(stateDir, routeName, rows) {
17715
17949
  const path = resolvedPathFor(stateDir, routeName);
17716
- if (!existsSync37(path)) return;
17950
+ if (!existsSync38(path)) return;
17717
17951
  const raw = JSON.parse(readFileSync36(path, "utf8"));
17718
17952
  applyRepoRows(raw, rows);
17719
17953
  mkdirSync26(dirname21(path), { recursive: true });
@@ -18168,12 +18402,12 @@ var localRefSkipReported = (ticket, problem, events) => events.some((e) => e.rec
18168
18402
 
18169
18403
  // src/connect-wizard.ts
18170
18404
  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";
18405
+ import { accessSync as accessSync3, constants as constants3, existsSync as existsSync39, mkdirSync as mkdirSync27, writeFileSync as writeFileSync30 } from "fs";
18172
18406
  import { stringify as stringify3 } from "yaml";
18173
18407
  var HOST_PASSENGERS_DOCS_URL = "https://crew.tablation.dev/host-passengers";
18174
18408
  function shouldRunWizard(opts) {
18175
18409
  if (!opts.isTTY) return false;
18176
- const exists = opts.configExists ?? existsSync38;
18410
+ const exists = opts.configExists ?? existsSync39;
18177
18411
  return !configSearchPath(opts.crewHome).some((p) => exists(p));
18178
18412
  }
18179
18413
  function firstRunConfigPath() {
@@ -18367,7 +18601,7 @@ function flagWizardAnswers(f, env) {
18367
18601
  }
18368
18602
 
18369
18603
  // src/diagnostics.ts
18370
- import { execFile as execFile3 } from "child_process";
18604
+ import { execFile as execFile4 } from "child_process";
18371
18605
  var BUNDLE_BUDGET_MS = 3e4;
18372
18606
  var JOURNAL_LINES = 200;
18373
18607
  var MAX_SECTION_BYTES = 256 * 1024;
@@ -18392,7 +18626,7 @@ function redactValue(v) {
18392
18626
  return v;
18393
18627
  }
18394
18628
  var defaultExec = (bin, args, timeoutMs) => new Promise((resolve8, reject) => {
18395
- execFile3(bin, args, { timeout: timeoutMs, maxBuffer: 4 * 1024 * 1024 }, (e, stdout) => {
18629
+ execFile4(bin, args, { timeout: timeoutMs, maxBuffer: 4 * 1024 * 1024 }, (e, stdout) => {
18396
18630
  if (e && e.code === "ENOENT") return reject(new Error(`${bin} is not installed`));
18397
18631
  if (e && e.killed) return reject(new Error(`${bin} timed out`));
18398
18632
  resolve8({ stdout: String(stdout), code: typeof e?.code === "number" ? e.code : 0 });
@@ -18439,9 +18673,9 @@ async function collectDiagnostics(d) {
18439
18673
  const deadline = new Promise((resolve8) => {
18440
18674
  setTimeout(() => resolve8("timeout"), budget).unref();
18441
18675
  });
18442
- const entries = await Promise.all(Object.entries(sections).map(async ([name, run3]) => {
18676
+ const entries = await Promise.all(Object.entries(sections).map(async ([name, run4]) => {
18443
18677
  try {
18444
- const out = await Promise.race([run3(), deadline]);
18678
+ const out = await Promise.race([run4(), deadline]);
18445
18679
  if (out === "timeout") return [name, { ok: false, error: `timed out after ${Math.round(budget / 1e3)}s` }];
18446
18680
  return [name, { ok: true, data: redactValue(out) }];
18447
18681
  } catch (e) {
@@ -18452,7 +18686,7 @@ async function collectDiagnostics(d) {
18452
18686
  }
18453
18687
 
18454
18688
  // 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";
18689
+ import { readFileSync as readFileSync37, writeFileSync as writeFileSync31, existsSync as existsSync40, copyFileSync, mkdirSync as mkdirSync28, mkdtempSync as mkdtempSync3, rmSync as rmSync19 } from "fs";
18456
18690
  import { dirname as dirname24, join as join43 } from "path";
18457
18691
  import { tmpdir as tmpdir6, hostname as hostname4 } from "os";
18458
18692
 
@@ -19237,7 +19471,7 @@ async function bump(o, size) {
19237
19471
  }
19238
19472
  const files = o.repo.release.versionFiles.map((f) => join43(o.cwd, f));
19239
19473
  const first = files[0];
19240
- if (!existsAt(first, existsSync39)) {
19474
+ if (!existsAt(first, existsSync40)) {
19241
19475
  o.emit.error(`no ${o.repo.release.versionFiles[0]} to read a version from`);
19242
19476
  return null;
19243
19477
  }
@@ -19279,7 +19513,7 @@ function writeChangelog(o, version, entries) {
19279
19513
  o.emit.emit(`would prepend ${entries.length} entr(ies) to ${file}`);
19280
19514
  return;
19281
19515
  }
19282
- const existing = existsAt(path, existsSync39) ? readTextAt(path, (p) => readFileSync37(p, "utf8")) : "# Changelog\n";
19516
+ const existing = existsAt(path, existsSync40) ? readTextAt(path, (p) => readFileSync37(p, "utf8")) : "# Changelog\n";
19283
19517
  writeTextAt(path, insertChangelogSection(existing, section), writeFileSync31);
19284
19518
  }
19285
19519
  async function confirm(o, expected) {
@@ -19358,15 +19592,15 @@ async function confirmLastRelease(o, decision) {
19358
19592
  if (!confirmed) o.emit.warn(`${decision.lastTag} is still not confirmed live \u2014 tickets stay verified`);
19359
19593
  return { confirmed, version };
19360
19594
  }
19361
- function closeReleaseCheckout(cwd, root, dir, branch, run3 = gitOk) {
19595
+ function closeReleaseCheckout(cwd, root, dir, branch, run4 = gitOk) {
19362
19596
  try {
19363
- run3(cwd, ["worktree", "remove", "--force", dir]);
19597
+ run4(cwd, ["worktree", "remove", "--force", dir]);
19364
19598
  } finally {
19365
19599
  try {
19366
19600
  rmSync19(root, { recursive: true, force: true });
19367
19601
  } finally {
19368
- run3(cwd, ["worktree", "prune"]);
19369
- run3(cwd, ["branch", "-D", branch]);
19602
+ run4(cwd, ["worktree", "prune"]);
19603
+ run4(cwd, ["branch", "-D", branch]);
19370
19604
  }
19371
19605
  }
19372
19606
  }
@@ -19385,7 +19619,7 @@ function openReleaseCheckout(o) {
19385
19619
  }
19386
19620
  for (const f of o.repo.worktrees.copy) {
19387
19621
  const src = join43(o.cwd, f);
19388
- if (!existsSync39(src)) continue;
19622
+ if (!existsSync40(src)) continue;
19389
19623
  mkdirSync28(dirname24(join43(dir, f)), { recursive: true });
19390
19624
  copyFileSync(src, join43(dir, f));
19391
19625
  }
@@ -20222,7 +20456,7 @@ function runForge(a, io) {
20222
20456
  }
20223
20457
 
20224
20458
  // src/mirror-contract.ts
20225
- import { existsSync as existsSync40 } from "fs";
20459
+ import { existsSync as existsSync41 } from "fs";
20226
20460
 
20227
20461
  // src/passenger-mirror.ts
20228
20462
  import { mkdirSync as mkdirSync29 } from "fs";
@@ -20263,7 +20497,7 @@ function mirrorOutcome(m) {
20263
20497
 
20264
20498
  // src/mirror-contract.ts
20265
20499
  function lacksCheckout(ship, dir) {
20266
- return ship.runner === "sandbox" && !existsSync40(dir) && !remoteOf(dir);
20500
+ return ship.runner === "sandbox" && !existsSync41(dir) && !remoteOf(dir);
20267
20501
  }
20268
20502
  function skipsHostCheckout(ship) {
20269
20503
  return ship.runner === "sandbox";
@@ -20343,11 +20577,11 @@ function explainRefusal(readable, unreadable) {
20343
20577
  }
20344
20578
 
20345
20579
  // src/release-sandbox.ts
20346
- import { execFile as execFile4 } from "child_process";
20580
+ import { execFile as execFile5 } from "child_process";
20347
20581
  import { mkdirSync as mkdirSync30, writeFileSync as writeFileSync32 } from "fs";
20348
20582
  import { dirname as dirname26 } from "path";
20349
- import { promisify as promisify3 } from "util";
20350
- var execFileP3 = promisify3(execFile4);
20583
+ import { promisify as promisify4 } from "util";
20584
+ var execFileP4 = promisify4(execFile5);
20351
20585
  var RELEASE_CLONE_DEPTH = 50;
20352
20586
  var FORGE_TOKEN_VAR = "CREW_FORGE_TOKEN";
20353
20587
  var FORGE_USER_VAR = "CREW_FORGE_USER";
@@ -20384,7 +20618,7 @@ function releaseCloneScript(o) {
20384
20618
  var endpointsOf = (g) => g.groups.flatMap((x) => x.endpoints.map((e) => `${e.host}:${e.port}`));
20385
20619
  async function openReleaseSandbox(o) {
20386
20620
  const cfg = { ...DEFAULT_SANDBOX_CONFIG, ...o.sandbox };
20387
- const run3 = o.exec ?? ((bin, args, env) => execFileP3(bin, args, { env, maxBuffer: 16 * 1024 * 1024 }));
20621
+ const run4 = o.exec ?? ((bin, args, env) => execFileP4(bin, args, { env, maxBuffer: 16 * 1024 * 1024 }));
20388
20622
  const name = sandboxName({ route: o.route, role: "release", ticket: o.repoName }, o.now?.());
20389
20623
  let policyFile = cfg.policy;
20390
20624
  let generated;
@@ -20403,6 +20637,7 @@ async function openReleaseSandbox(o) {
20403
20637
  }
20404
20638
  const create2 = ["sandbox", "create", "--name", name, "--detach"];
20405
20639
  if (policyFile) create2.push("--policy", policyFile);
20640
+ for (const l of sandboxLabels({ role: "release", run: name })) create2.push("--label", l);
20406
20641
  const image = cfg.image ?? o.image;
20407
20642
  if (image) create2.push("--from", image);
20408
20643
  if (cfg.cacheVolume) {
@@ -20415,12 +20650,12 @@ async function openReleaseSandbox(o) {
20415
20650
  const t0 = Date.now();
20416
20651
  const deleteQuietly = async () => {
20417
20652
  try {
20418
- await run3(cfg.bin, ["sandbox", "delete", name], process.env);
20653
+ await run4(cfg.bin, ["sandbox", "delete", name], process.env);
20419
20654
  } catch {
20420
20655
  }
20421
20656
  };
20422
20657
  try {
20423
- await run3(cfg.bin, create2, secrets);
20658
+ await run4(cfg.bin, create2, secrets);
20424
20659
  } catch (e) {
20425
20660
  await deleteQuietly();
20426
20661
  throw new Error(`openshell could not create the release sandbox: ${describe(e)}`);
@@ -20434,7 +20669,7 @@ async function openReleaseSandbox(o) {
20434
20669
  }
20435
20670
  const closeSandbox = async () => {
20436
20671
  try {
20437
- const { stdout } = await run3(cfg.bin, ["logs", name], process.env);
20672
+ const { stdout } = await run4(cfg.bin, ["logs", name], process.env);
20438
20673
  for (const d of parseDeniedRequests(stdout)) {
20439
20674
  const where = `${d.host}${d.port !== void 0 ? `:${d.port}` : ""}${d.binary ? ` by ${d.binary}` : ""}`;
20440
20675
  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 +20691,7 @@ async function openReleaseSandbox(o) {
20456
20691
  tagPattern: o.tagPattern
20457
20692
  })}
20458
20693
  ${containerEngineStubScript()}`;
20459
- await run3(cfg.bin, ["sandbox", "exec", "-n", name, "--no-login-shell", "--", "sh", "-c", clone], process.env);
20694
+ await run4(cfg.bin, ["sandbox", "exec", "-n", name, "--no-login-shell", "--", "sh", "-c", clone], process.env);
20460
20695
  } catch (e) {
20461
20696
  await closeSandbox();
20462
20697
  throw new Error(`could not make the release clone in ${name}: ${describe(e)}`);
@@ -20557,7 +20792,7 @@ function missingReleaserWarning(repo, release, ships, now = Date.now()) {
20557
20792
  }
20558
20793
 
20559
20794
  // 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";
20795
+ import { watch as watchFile, existsSync as existsSync42, statSync as statSync12, openSync as openSync5, readSync as readSync2, closeSync as closeSync5 } from "fs";
20561
20796
  var E = "\x1B[";
20562
20797
  var dim = (s) => `${E}2m${s}${E}0m`;
20563
20798
  var bold = (s) => `${E}1m${s}${E}0m`;
@@ -20658,8 +20893,8 @@ function renderHeaders(states, now = Date.now()) {
20658
20893
  return states.map((s) => renderHeader(s, now)).join("");
20659
20894
  }
20660
20895
  function readFrom(file, from) {
20661
- if (!existsSync41(file)) return { events: [], offset: from };
20662
- const size = statSync11(file).size;
20896
+ if (!existsSync42(file)) return { events: [], offset: from };
20897
+ const size = statSync12(file).size;
20663
20898
  if (size < from) return readFrom(file, 0);
20664
20899
  if (size === from) return { events: [], offset: from };
20665
20900
  const fd = openSync5(file, "r");
@@ -20901,7 +21136,7 @@ function nextRoles(decision, ran) {
20901
21136
  }
20902
21137
 
20903
21138
  // src/ship-name.ts
20904
- import { existsSync as existsSync42, mkdirSync as mkdirSync31, readFileSync as readFileSync38, renameSync as renameSync5, writeFileSync as writeFileSync33 } from "fs";
21139
+ import { existsSync as existsSync43, mkdirSync as mkdirSync31, readFileSync as readFileSync38, renameSync as renameSync5, writeFileSync as writeFileSync33 } from "fs";
20905
21140
  import { dirname as dirname27 } from "path";
20906
21141
  import { parseDocument as parseDocument5 } from "yaml";
20907
21142
  var ShipNameError = class extends Error {
@@ -20963,7 +21198,7 @@ async function syncRouteName(i) {
20963
21198
  return { status: "ok", ...base, action, name: i.local };
20964
21199
  }
20965
21200
  function readSyncedName(resolvedFile) {
20966
- if (!existsSync42(resolvedFile)) return void 0;
21201
+ if (!existsSync43(resolvedFile)) return void 0;
20967
21202
  try {
20968
21203
  const v = JSON.parse(readFileSync38(resolvedFile, "utf8")).shipName;
20969
21204
  return typeof v === "string" ? v : void 0;
@@ -20972,7 +21207,7 @@ function readSyncedName(resolvedFile) {
20972
21207
  }
20973
21208
  }
20974
21209
  function writeSyncedName(resolvedFile, name) {
20975
- if (!existsSync42(resolvedFile)) return;
21210
+ if (!existsSync43(resolvedFile)) return;
20976
21211
  let raw;
20977
21212
  try {
20978
21213
  raw = JSON.parse(readFileSync38(resolvedFile, "utf8"));
@@ -21674,7 +21909,7 @@ function describeCapability(i) {
21674
21909
  }
21675
21910
 
21676
21911
  // src/agents-sync-run.ts
21677
- import { existsSync as existsSync43, mkdirSync as mkdirSync32, readFileSync as readFileSync39, writeFileSync as writeFileSync34 } from "fs";
21912
+ import { existsSync as existsSync44, mkdirSync as mkdirSync32, readFileSync as readFileSync39, writeFileSync as writeFileSync34 } from "fs";
21678
21913
  import { dirname as dirname28 } from "path";
21679
21914
  async function runAgentsSync(target, o) {
21680
21915
  const dryRun = o.dryRun ?? false;
@@ -21708,7 +21943,7 @@ async function runAgentsSync(target, o) {
21708
21943
  for (const s of skillResult?.outcomes ?? []) o.say(describeSkillSyncOutcome(s));
21709
21944
  if (!dryRun) {
21710
21945
  const resolvedPath = resolvedPathFor(o.stateDir, target.route);
21711
- const raw = existsSync43(resolvedPath) ? JSON.parse(readFileSync39(resolvedPath, "utf8")) : {};
21946
+ const raw = existsSync44(resolvedPath) ? JSON.parse(readFileSync39(resolvedPath, "utf8")) : {};
21712
21947
  raw.agentPersonas = personaResult.agentPersonas;
21713
21948
  if (skillResult) raw.agentSkills = skillResult.agentSkills;
21714
21949
  if (personaResult.releaseAgentId) raw.releaseAgentId = personaResult.releaseAgentId;
@@ -21856,21 +22091,21 @@ var POSIX_SHELL = /^(?:ba|z|da|k|a|mk)?sh$|^fish$/;
21856
22091
  function checkHookSyntax(script, shell) {
21857
22092
  const spec = resolveShell(shell);
21858
22093
  const name = basename11(spec.bin).replace(/\.exe$/i, "").toLowerCase();
21859
- let run3;
22094
+ let run4;
21860
22095
  if (POSIX_SHELL.test(name)) {
21861
- run3 = spawnSync11(spec.bin, ["-n"], { input: script, encoding: "utf8" });
22096
+ run4 = spawnSync11(spec.bin, ["-n"], { input: script, encoding: "utf8" });
21862
22097
  } else if (/^(pwsh|powershell)$/.test(name)) {
21863
22098
  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], {
22099
+ run4 = spawnSync11(spec.bin, ["-NoProfile", "-NonInteractive", "-Command", parse3], {
21865
22100
  encoding: "utf8",
21866
22101
  env: { ...process.env, CREW_CHECK_SCRIPT: script }
21867
22102
  });
21868
22103
  } else {
21869
22104
  return { status: "unchecked", message: `no syntax check for ${spec.bin}` };
21870
22105
  }
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}`;
22106
+ if (run4.error) return { status: "unchecked", message: `cannot run ${spec.bin}: ${run4.error.message}` };
22107
+ if (run4.status === 0) return { status: "ok" };
22108
+ const message = `${run4.stderr ?? ""}${run4.stdout ?? ""}`.trim() || `${spec.bin} exited ${run4.status}`;
21874
22109
  return { status: "error", message };
21875
22110
  }
21876
22111
  function renderSamples(cfg, dir) {
@@ -22301,7 +22536,7 @@ async function runAgentSuggest(o) {
22301
22536
  const before = porcelain(o.dir);
22302
22537
  const timeout = AbortSignal.timeout(o.timeoutMs ?? DEFAULT_TIMEOUT_MS);
22303
22538
  const signal = o.signal ? AbortSignal.any([o.signal, timeout]) : timeout;
22304
- const run3 = await new Promise((resolve8) => {
22539
+ const run4 = await new Promise((resolve8) => {
22305
22540
  let out = "";
22306
22541
  let err3 = "";
22307
22542
  const child = spawn8(bin, args, { cwd: o.dir, env, detached: true, stdio: ["pipe", "pipe", "pipe"] });
@@ -22336,18 +22571,18 @@ async function runAgentSuggest(o) {
22336
22571
  });
22337
22572
  child.stdin.end(buildAgentPrompt(o.sniff));
22338
22573
  });
22339
- if (run3.aborted || signal.aborted) {
22574
+ if (run4.aborted || signal.aborted) {
22340
22575
  throw new AgentSuggestError(o.signal?.aborted ? "cancelled" : "timeout", o.signal?.aborted ? "cancelled" : "the toolchain did not answer in time");
22341
22576
  }
22342
22577
  const after = porcelain(o.dir);
22343
22578
  if (before !== void 0 && after !== before) {
22344
22579
  throw new AgentSuggestError("modified_checkout", "the checkout changed during --agent; inspect it with `git status` (the agent result was discarded)");
22345
22580
  }
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}`);
22581
+ const parsed = parseAgentStream(run4.out, o.dir);
22582
+ if (run4.spawnError || run4.code !== 0 || parsed.isError) {
22583
+ const reason = classifyFailure({ code: run4.code, ...run4.spawnError ? { spawnError: run4.spawnError } : {}, output: `${parsed.text}
22584
+ ${run4.err}` });
22585
+ 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
22586
  }
22352
22587
  const { hooks, notes } = parseAgentHooks(parsed.text);
22353
22588
  const differsFromSniff = HOOK_KEYS2.filter((k) => hooks[k] !== void 0 && hooks[k] !== o.sniff.hooks[k]);
@@ -22423,7 +22658,7 @@ function planSampleTicket(i) {
22423
22658
  }
22424
22659
 
22425
22660
  // src/worktree-sweep.ts
22426
- import { existsSync as existsSync44, readFileSync as readFileSync41, readdirSync as readdirSync14 } from "fs";
22661
+ import { existsSync as existsSync45, readFileSync as readFileSync41, readdirSync as readdirSync14 } from "fs";
22427
22662
  import { basename as basename13, dirname as dirname30, join as join45, resolve as resolve5 } from "path";
22428
22663
  function planWorktreeSweep(target, tickets, contract) {
22429
22664
  const terminal = new Set(contract.statuses.resolved.filter((s) => s !== contract.statuses.verified));
@@ -22536,7 +22771,7 @@ async function applyWorktreeSweep(cwd, actions, dryRun, log, remote = "origin",
22536
22771
  let removed = 0;
22537
22772
  let keptBranches = 0;
22538
22773
  for (const a of actions) {
22539
- if (!dryRun && base && !a.keepBranch && existsSync44(a.path) && isHandBackMerge(a.path, base)) {
22774
+ if (!dryRun && base && !a.keepBranch && existsSync45(a.path) && isHandBackMerge(a.path, base)) {
22540
22775
  if (gitOk(a.path, ["merge", "--abort"]) !== null) {
22541
22776
  log.emit(
22542
22777
  `abandoned the hand-back merge of ${base} in ${a.path}: ${a.ticket.issue_id} deployed without it`,
@@ -22544,7 +22779,7 @@ async function applyWorktreeSweep(cwd, actions, dryRun, log, remote = "origin",
22544
22779
  );
22545
22780
  }
22546
22781
  }
22547
- if (!dryRun && existsSync44(a.path)) {
22782
+ if (!dryRun && existsSync45(a.path)) {
22548
22783
  let dirty = false;
22549
22784
  try {
22550
22785
  dirty = status(a.path).length > 0;
@@ -22555,7 +22790,7 @@ async function applyWorktreeSweep(cwd, actions, dryRun, log, remote = "origin",
22555
22790
  continue;
22556
22791
  }
22557
22792
  }
22558
- if (!dryRun && a.requirePushed && a.branch && existsSync44(a.path) && remoteConfigured(cwd, remote) && worktreeHoldsUnpushed(a.path, remote)) {
22793
+ if (!dryRun && a.requirePushed && a.branch && existsSync45(a.path) && remoteConfigured(cwd, remote) && worktreeHoldsUnpushed(a.path, remote)) {
22559
22794
  refuse2(a, "unpushed commits", `${a.branch} has commits that are not on ${remote}`);
22560
22795
  continue;
22561
22796
  }
@@ -22709,16 +22944,16 @@ function applyRemoteBranchCleanup(cwd, remote, branches2, dryRun, log) {
22709
22944
  }
22710
22945
 
22711
22946
  // src/stream-sweep.ts
22712
- import { existsSync as existsSync45, readdirSync as readdirSync15, rmSync as rmSync20, statSync as statSync12 } from "fs";
22947
+ import { existsSync as existsSync46, readdirSync as readdirSync15, rmSync as rmSync20, statSync as statSync13 } from "fs";
22713
22948
  import { join as join46 } from "path";
22714
22949
  var DAY_MS2 = 24 * 60 * 60 * 1e3;
22715
22950
  function planStreamSweep(stateDir, retentionDays, now = Date.now()) {
22716
22951
  const dir = join46(stateDir, "streams");
22717
- if (!existsSync45(dir)) return [];
22952
+ if (!existsSync46(dir)) return [];
22718
22953
  const cutoff = now - retentionDays * DAY_MS2;
22719
22954
  return readdirSync15(dir).map((name) => join46(dir, name)).filter((path) => {
22720
22955
  try {
22721
- return statSync12(path).mtimeMs < cutoff;
22956
+ return statSync13(path).mtimeMs < cutoff;
22722
22957
  } catch {
22723
22958
  return false;
22724
22959
  }
@@ -22742,11 +22977,11 @@ function applyStreamSweep(paths, dryRun, log) {
22742
22977
  return removed;
22743
22978
  }
22744
22979
  function planEventsSweep(stateDir, retentionDays, now = Date.now()) {
22745
- if (!existsSync45(stateDir)) return [];
22980
+ if (!existsSync46(stateDir)) return [];
22746
22981
  const cutoff = now - retentionDays * DAY_MS2;
22747
22982
  return readdirSync15(stateDir).filter((name) => ROTATED_EVENTS_RE.test(name)).map((name) => join46(stateDir, name)).filter((path) => {
22748
22983
  try {
22749
- return statSync12(path).mtimeMs < cutoff;
22984
+ return statSync13(path).mtimeMs < cutoff;
22750
22985
  } catch {
22751
22986
  return false;
22752
22987
  }
@@ -22754,11 +22989,11 @@ function planEventsSweep(stateDir, retentionDays, now = Date.now()) {
22754
22989
  }
22755
22990
 
22756
22991
  // 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";
22992
+ 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
22993
  import { createInterface } from "readline/promises";
22759
22994
 
22760
22995
  // src/periscope-cmd.ts
22761
- import { existsSync as existsSync46, mkdirSync as mkdirSync33, readFileSync as readFileSync42, rmSync as rmSync21, writeFileSync as writeFileSync35 } from "fs";
22996
+ import { existsSync as existsSync47, mkdirSync as mkdirSync33, readFileSync as readFileSync42, rmSync as rmSync21, writeFileSync as writeFileSync35 } from "fs";
22762
22997
  import { join as join47 } from "path";
22763
22998
  var PeriscopeError = class extends Error {
22764
22999
  };
@@ -22784,7 +23019,7 @@ function writePeriscopePrior(stateDir, ticketRecordId, prior) {
22784
23019
  function readPeriscopePrior(stateDir, ticketRecordId) {
22785
23020
  try {
22786
23021
  const p = priorPath(stateDir, ticketRecordId);
22787
- return existsSync46(p) ? JSON.parse(readFileSync42(p, "utf8")) : void 0;
23022
+ return existsSync47(p) ? JSON.parse(readFileSync42(p, "utf8")) : void 0;
22788
23023
  } catch {
22789
23024
  return void 0;
22790
23025
  }
@@ -23237,7 +23472,7 @@ ${tail2(preview.output)}`);
23237
23472
 
23238
23473
  // src/periscope-idle.ts
23239
23474
  import { execFileSync as execFileSync13 } from "child_process";
23240
- import { statSync as statSync13 } from "fs";
23475
+ import { statSync as statSync14 } from "fs";
23241
23476
  import { join as join48 } from "path";
23242
23477
  var MAX_SCANNED_FILES = 2e4;
23243
23478
  function newestWorktreeMtime(root) {
@@ -23263,7 +23498,7 @@ function newestTrackedMtime(root) {
23263
23498
  if (!rel) continue;
23264
23499
  if (++scanned > MAX_SCANNED_FILES) break;
23265
23500
  try {
23266
- const m = statSync13(join48(root, rel)).mtimeMs;
23501
+ const m = statSync14(join48(root, rel)).mtimeMs;
23267
23502
  if (newest === null || m > newest) newest = m;
23268
23503
  } catch {
23269
23504
  }
@@ -23340,7 +23575,7 @@ import { dirname as dirOf2, resolve as resolvePath } from "path";
23340
23575
 
23341
23576
  // src/ssh-keys.ts
23342
23577
  import { execFileSync as execFileSync14 } from "child_process";
23343
- import { existsSync as existsSync47, mkdirSync as mkdirSync34, readFileSync as readFileSync43, chmodSync as chmodSync3 } from "fs";
23578
+ import { existsSync as existsSync48, mkdirSync as mkdirSync34, readFileSync as readFileSync43, chmodSync as chmodSync3 } from "fs";
23344
23579
  import { dirname as dirname31, join as join49 } from "path";
23345
23580
  var SshKeyError = class extends Error {
23346
23581
  };
@@ -23350,7 +23585,7 @@ function shipSshKeyPathFor(stateDir) {
23350
23585
  function ensureShipSshKeypair(stateDir) {
23351
23586
  const privateKeyPath = shipSshKeyPathFor(stateDir);
23352
23587
  const publicKeyPath = `${privateKeyPath}.pub`;
23353
- if (!existsSync47(privateKeyPath)) {
23588
+ if (!existsSync48(privateKeyPath)) {
23354
23589
  mkdirSync34(dirname31(privateKeyPath), { recursive: true });
23355
23590
  try {
23356
23591
  execFileSync14("ssh-keygen", [
@@ -23371,7 +23606,7 @@ function ensureShipSshKeypair(stateDir) {
23371
23606
  }
23372
23607
  chmodSync3(privateKeyPath, 384);
23373
23608
  }
23374
- if (!existsSync47(publicKeyPath)) {
23609
+ if (!existsSync48(publicKeyPath)) {
23375
23610
  throw new SshKeyError(`${privateKeyPath} exists but ${publicKeyPath} does not \u2014 regenerate or restore it`);
23376
23611
  }
23377
23612
  const publicKey = readFileSync43(publicKeyPath, "utf8").trim();
@@ -23538,7 +23773,7 @@ async function unregisterEndpoint(workspaceId, info, d) {
23538
23773
  import { createServer as createHttpServer } from "http";
23539
23774
  import { spawn as spawn9 } from "child_process";
23540
23775
  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";
23776
+ import { existsSync as existsSync49, mkdirSync as mkdirSync35, readFileSync as readFileSync44, writeFileSync as writeFileSync36, unlinkSync as unlinkSync4, readdirSync as readdirSync16 } from "fs";
23542
23777
  import { join as join50 } from "path";
23543
23778
 
23544
23779
  // src/secret-compare.ts
@@ -23636,7 +23871,7 @@ function syncDaemonStatePath(stateDir, workspaceId) {
23636
23871
  }
23637
23872
  function readPersistedSyncDaemon(stateDir, workspaceId) {
23638
23873
  const path = syncDaemonStatePath(stateDir, workspaceId);
23639
- if (!existsSync48(path)) return void 0;
23874
+ if (!existsSync49(path)) return void 0;
23640
23875
  try {
23641
23876
  return JSON.parse(readFileSync44(path, "utf8"));
23642
23877
  } catch {
@@ -23667,7 +23902,7 @@ function waitForExit(pid, alive, timeoutMs = 5e3) {
23667
23902
  }
23668
23903
  function readAllPersistedSyncWorkspaceIds(stateDir) {
23669
23904
  const dir = join50(stateDir, "passengers");
23670
- if (!existsSync48(dir)) return [];
23905
+ if (!existsSync49(dir)) return [];
23671
23906
  const suffix = "-sync.json";
23672
23907
  return readdirSync16(dir).filter((f) => f.endsWith(suffix)).map((f) => f.slice(0, -suffix.length));
23673
23908
  }
@@ -24187,12 +24422,12 @@ function contractFixers(dir, baseRef, tickets, locate) {
24187
24422
  }
24188
24423
 
24189
24424
  // 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";
24425
+ 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
24426
  import { join as join53 } from "path";
24192
24427
  import { randomBytes as randomBytes2 } from "crypto";
24193
24428
 
24194
24429
  // src/noop-runs.ts
24195
- import { existsSync as existsSync49, mkdirSync as mkdirSync37, readFileSync as readFileSync45, renameSync as renameSync6, writeFileSync as writeFileSync37 } from "fs";
24430
+ import { existsSync as existsSync50, mkdirSync as mkdirSync37, readFileSync as readFileSync45, renameSync as renameSync6, writeFileSync as writeFileSync37 } from "fs";
24196
24431
  import { join as join52 } from "path";
24197
24432
  var NOOP_DELAYS_MS = [5, 15, 60].map((m) => m * 6e4);
24198
24433
  var DEFAULT_NOOP_REPEATS = 3;
@@ -24227,7 +24462,7 @@ function recordNoopRun(stateDir, recordId, repeats, now = Date.now()) {
24227
24462
  return { count, nextAt, bounce: count >= repeats };
24228
24463
  }
24229
24464
  function clearNoopRuns(stateDir, recordId) {
24230
- if (!existsSync49(noopRunsPath(stateDir))) return;
24465
+ if (!existsSync50(noopRunsPath(stateDir))) return;
24231
24466
  const state = readNoopRuns(stateDir);
24232
24467
  if (!(recordId in state)) return;
24233
24468
  delete state[recordId];
@@ -24362,7 +24597,7 @@ async function runDaemonLoop(o) {
24362
24597
  function latestMtime(path) {
24363
24598
  let stat2;
24364
24599
  try {
24365
- stat2 = statSync14(path);
24600
+ stat2 = statSync15(path);
24366
24601
  } catch {
24367
24602
  return 0;
24368
24603
  }
@@ -24379,14 +24614,14 @@ function computeTreeSignature(paths) {
24379
24614
  }
24380
24615
  function makeStaleChecker(paths, opts = {}) {
24381
24616
  const initial = computeTreeSignature(paths);
24382
- return () => computeTreeSignature(paths) !== initial || opts.reloadSentinel !== void 0 && existsSync50(opts.reloadSentinel);
24617
+ return () => computeTreeSignature(paths) !== initial || opts.reloadSentinel !== void 0 && existsSync51(opts.reloadSentinel);
24383
24618
  }
24384
24619
  function reloadSentinelFor(stateDir) {
24385
24620
  return join53(stateDir, "reload-requested");
24386
24621
  }
24387
24622
  function readReloadRequestedAt(stateDir) {
24388
24623
  try {
24389
- return statSync14(reloadSentinelFor(stateDir)).mtimeMs;
24624
+ return statSync15(reloadSentinelFor(stateDir)).mtimeMs;
24390
24625
  } catch {
24391
24626
  return null;
24392
24627
  }
@@ -24411,7 +24646,7 @@ function readDaemonStarted(stateDir) {
24411
24646
  function configChangedAfter(files, startedAt) {
24412
24647
  for (const f of files) {
24413
24648
  try {
24414
- if (statSync14(f).mtimeMs > startedAt) return f;
24649
+ if (statSync15(f).mtimeMs > startedAt) return f;
24415
24650
  } catch {
24416
24651
  }
24417
24652
  }
@@ -24483,6 +24718,13 @@ async function runOnePassUnguarded(o) {
24483
24718
  } catch (e) {
24484
24719
  emit.warn(`could not reconcile earlier agent runs: ${e.message}`, { step: "agent" });
24485
24720
  }
24721
+ if (o.sandboxHygiene) {
24722
+ try {
24723
+ await o.sandboxHygiene();
24724
+ } catch (e) {
24725
+ emit.warn(`sandbox hygiene failed: ${e instanceof Error ? e.message : String(e)}`);
24726
+ }
24727
+ }
24486
24728
  const decision = await decide(ctx);
24487
24729
  o.state.attention(o.route.route).persist(decision.attention);
24488
24730
  o.state.unroutable(o.route.route).persist(decision.unroutable);
@@ -24590,7 +24832,7 @@ async function runOnePassUnguarded(o) {
24590
24832
  settle = resolve8;
24591
24833
  });
24592
24834
  const ready = (tookTicket2) => settle(tookTicket2);
24593
- const run3 = spawn13(role, decision, ctx, { ready }).then(() => {
24835
+ const run4 = spawn13(role, decision, ctx, { ready }).then(() => {
24594
24836
  breaker.recordSuccess(role);
24595
24837
  clearShipAttention(o.state, `role_parked:${role}`);
24596
24838
  clearShipAttention(o.state, workspaceAuthKey(role));
@@ -24645,8 +24887,8 @@ async function runOnePassUnguarded(o) {
24645
24887
  });
24646
24888
  if (o.inFlight) {
24647
24889
  const set = o.inFlight;
24648
- set.add(run3);
24649
- void run3.finally(() => set.delete(run3));
24890
+ set.add(run4);
24891
+ void run4.finally(() => set.delete(run4));
24650
24892
  }
24651
24893
  const reported2 = TICKET_ROLES.has(role) ? await settled : true;
24652
24894
  const tookTicket = reported2 !== false;
@@ -25106,19 +25348,19 @@ import { createHash as createHash11 } from "crypto";
25106
25348
  import {
25107
25349
  chmodSync as chmodSync4,
25108
25350
  closeSync as closeSync6,
25109
- existsSync as existsSync51,
25351
+ existsSync as existsSync52,
25110
25352
  fstatSync,
25111
25353
  openSync as openSync6,
25112
25354
  readSync as readSync3,
25113
25355
  readdirSync as readdirSync18,
25114
25356
  rmSync as rmSync23,
25115
- statSync as statSync15,
25357
+ statSync as statSync16,
25116
25358
  watch
25117
25359
  } from "fs";
25118
25360
  import { createConnection } from "net";
25119
25361
  import { createServer as createServer2 } from "http";
25120
25362
  import { basename as basename14, dirname as dirname33, join as join54 } from "path";
25121
- import { execFile as execFile5, spawn as spawn12 } from "child_process";
25363
+ import { execFile as execFile6, spawn as spawn12 } from "child_process";
25122
25364
 
25123
25365
  // src/periscope-control.ts
25124
25366
  import { spawn as spawn11 } from "child_process";
@@ -25456,7 +25698,7 @@ function readRange(path, from, max) {
25456
25698
  }
25457
25699
  }
25458
25700
  function lastLines2(path, n) {
25459
- const st = statSync15(path);
25701
+ const st = statSync16(path);
25460
25702
  const cursorAt = (off) => encodeCursor({ dev: st.dev, ino: st.ino, off });
25461
25703
  if (n <= 0 || st.size === 0) return { lines: [], cursor: cursorAt(st.size), reset: false };
25462
25704
  let start = st.size;
@@ -25477,7 +25719,7 @@ function lastLines2(path, n) {
25477
25719
  }
25478
25720
  function readTail(live, opts) {
25479
25721
  const max = opts.maxBytes ?? MAX_TAIL_BYTES;
25480
- if (!existsSync51(live)) {
25722
+ if (!existsSync52(live)) {
25481
25723
  return { lines: [], cursor: opts.after ?? encodeCursor({ dev: 0, ino: 0, off: 0 }), reset: false };
25482
25724
  }
25483
25725
  const cur = opts.after ? decodeCursor(opts.after) : null;
@@ -25490,7 +25732,7 @@ function readTail(live, opts) {
25490
25732
  } else {
25491
25733
  const found = candidates(live, opts.rotated ?? false).find((p) => {
25492
25734
  try {
25493
- const s = statSync15(p);
25735
+ const s = statSync16(p);
25494
25736
  return s.ino === cur.ino && s.dev === cur.dev;
25495
25737
  } catch {
25496
25738
  return false;
@@ -25501,7 +25743,7 @@ function readTail(live, opts) {
25501
25743
  off = cur.off;
25502
25744
  } else reset = true;
25503
25745
  }
25504
- let size = statSync15(path).size;
25746
+ let size = statSync16(path).size;
25505
25747
  if (off > size) {
25506
25748
  off = 0;
25507
25749
  reset = true;
@@ -25509,12 +25751,12 @@ function readTail(live, opts) {
25509
25751
  if (off >= size && path !== live) {
25510
25752
  path = live;
25511
25753
  off = 0;
25512
- size = statSync15(path).size;
25754
+ size = statSync16(path).size;
25513
25755
  }
25514
25756
  const { text: text2 } = readRange(path, off, max);
25515
25757
  const cut = text2.lastIndexOf("\n");
25516
25758
  const whole = cut < 0 ? "" : text2.slice(0, cut + 1);
25517
- const st = statSync15(path);
25759
+ const st = statSync16(path);
25518
25760
  return {
25519
25761
  lines: whole.split("\n").filter((l) => l.length),
25520
25762
  cursor: encodeCursor({ dev: st.dev, ino: st.ino, off: off + Buffer.byteLength(whole) }),
@@ -25631,10 +25873,10 @@ async function route(deps, method, url, req, abort) {
25631
25873
  if (p === "/events" && get2) return tailReply(eventFileFor(deps.stateDir), url.searchParams, true, abort);
25632
25874
  if (p === "/streams" && get2) return reply2(200, { streams: liveRuns(deps.stateDir).map(describeStream) });
25633
25875
  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");
25876
+ const run4 = decodeURIComponent(p.slice("/streams/".length));
25877
+ if (!RUN_NAME_RE.test(run4) || run4.includes("..") || /\.(pid|meta\.json|events\.jsonl)$/.test(run4)) return err2(400, "not a run name");
25878
+ const file = join54(deps.stateDir, "streams", run4.endsWith(".jsonl") ? run4 : `${run4}.jsonl`);
25879
+ if (!existsSync52(file)) return err2(404, "no such run");
25638
25880
  return tailReply(file, url.searchParams, false, abort);
25639
25881
  }
25640
25882
  if ((p === "/pause" || p === "/resume") && post3) {
@@ -25679,7 +25921,7 @@ function send(res, r) {
25679
25921
  res.end(body);
25680
25922
  }
25681
25923
  async function socketIsStale(path) {
25682
- if (!existsSync51(path)) return false;
25924
+ if (!existsSync52(path)) return false;
25683
25925
  return new Promise((resolve8) => {
25684
25926
  const c = createConnection(path);
25685
25927
  c.once("connect", () => {
@@ -25698,7 +25940,7 @@ async function startControlServer(deps) {
25698
25940
  return null;
25699
25941
  }
25700
25942
  if (await socketIsStale(path)) rmSync23(path, { force: true });
25701
- else if (existsSync51(path)) {
25943
+ else if (existsSync52(path)) {
25702
25944
  log(`control API not started: ${path} is in use by another process`);
25703
25945
  return null;
25704
25946
  }
@@ -25760,18 +26002,18 @@ function runDetached(commands, spawnFn = spawn12) {
25760
26002
  });
25761
26003
  child.unref();
25762
26004
  }
25763
- function schedulerHandler(control, run3 = runDetached) {
26005
+ function schedulerHandler(control, run4 = runDetached) {
25764
26006
  return (action) => {
25765
26007
  const { startCommand: start, stopCommand: stop } = control;
25766
26008
  if (!start || !stop) return { accepted: false, detail: "this host has no service manager for the daemon (cron or none)" };
25767
26009
  const commands = action === "start" ? [start] : action === "stop" ? [stop] : [stop, start];
25768
- run3(commands);
26010
+ run4(commands);
25769
26011
  return { accepted: true, detail: `${action} requested` };
25770
26012
  };
25771
26013
  }
25772
26014
  function crewJson(args, timeoutMs = 6e4) {
25773
26015
  return new Promise((resolve8) => {
25774
- execFile5(process.execPath, [process.argv[1] ?? "", ...args], { timeout: timeoutMs, maxBuffer: 16 * 1024 * 1024 }, (_e, stdout) => {
26016
+ execFile6(process.execPath, [process.argv[1] ?? "", ...args], { timeout: timeoutMs, maxBuffer: 16 * 1024 * 1024 }, (_e, stdout) => {
25775
26017
  try {
25776
26018
  const v = JSON.parse(String(stdout));
25777
26019
  resolve8(v && typeof v === "object" && !Array.isArray(v) ? v : null);
@@ -25791,7 +26033,7 @@ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/
25791
26033
 
25792
26034
  // src/periscope-endpoints.ts
25793
26035
  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";
26036
+ 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
26037
  import { join as join55 } from "path";
25796
26038
  var secretDir = (stateDir) => join55(stateDir, "periscope-mcp");
25797
26039
  var secretFile = (stateDir, id) => join55(secretDir(stateDir), `${id}.json`);
@@ -25834,7 +26076,7 @@ function removePeriscopeEndpointRecord(stateDir, ticketRecordId) {
25834
26076
  }
25835
26077
  function listPeriscopeEndpoints(stateDir) {
25836
26078
  const dir = endpointDir(stateDir);
25837
- if (!existsSync52(dir)) return [];
26079
+ if (!existsSync53(dir)) return [];
25838
26080
  const out = [];
25839
26081
  for (const name of readdirSync19(dir)) {
25840
26082
  if (!name.endsWith(".json")) continue;
@@ -26817,7 +27059,7 @@ if (command === "passenger-sync-daemon") {
26817
27059
  } else {
26818
27060
  const toleratesNoRoutes = command === "credential" || command === "forge" || command === "repos" || command === "ship" || command === "disconnect" && flag("reset") || command === "deprovision" || command === "connect" && flag("sign-out");
26819
27061
  const configless = command === "connect" && flag("sign-out") || command === "disconnect" && flag("reset") || command === "deprovision";
26820
- if (configless && !existsSync53(findConfigFile(CREW_HOME))) {
27062
+ if (configless && !existsSync54(findConfigFile(CREW_HOME))) {
26821
27063
  cfg = loadConfig(CREW_HOME, firstRunConfigPath(), { text: "ship: {}\n", allowNoRoutes: true });
26822
27064
  } else {
26823
27065
  cfg = loadConfig(CREW_HOME, void 0, toleratesNoRoutes ? { allowNoRoutes: true } : {});
@@ -27170,7 +27412,7 @@ if (command === "passenger-sync-daemon") {
27170
27412
  if (host === "linux" && hasSystemd) {
27171
27413
  const label = labelFor(CREW_HOME, "run");
27172
27414
  const staleTimer = join57(homedir11(), ".config", "systemd", "user", `${label}.timer`);
27173
- if (existsSync53(staleTimer)) {
27415
+ if (existsSync54(staleTimer)) {
27174
27416
  process.stdout.write(
27175
27417
  `removing stale run timer from before the persistent-service cutover: ${staleTimer}${dryRun ? " (dry run)" : ""}
27176
27418
  `
@@ -27199,7 +27441,7 @@ if (command === "passenger-sync-daemon") {
27199
27441
  const { settled: doctorRepos, errors: refusedRepos } = await settleRepos(reposOf(c), (t) => t.name, (t) => resolveOneRepo(c, t));
27200
27442
  for (const e of refusedRepos) problems.push(`repo ${e.repo}: ${e.detail}`);
27201
27443
  for (const r of doctorRepos) {
27202
- if (!existsSync53(r.dir)) problems.push(`repo ${r.name}: ${r.dir} is missing on disk`);
27444
+ if (!existsSync54(r.dir)) problems.push(`repo ${r.name}: ${r.dir} is missing on disk`);
27203
27445
  if (!satisfies(host, r.config.platform)) problems.push(`repo ${r.name}: requires ${r.config.platform}, this host is ${host}`);
27204
27446
  readiness.push(...validateEffective(r.config).map((p) => `repo ${r.name}: ${p}`));
27205
27447
  }
@@ -27226,7 +27468,7 @@ if (command === "passenger-sync-daemon") {
27226
27468
  }
27227
27469
  async function doctorFix(o) {
27228
27470
  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);
27471
+ const unitExists = (p) => existsSync54(p);
27230
27472
  const crontab = o.host === "linux" ? spawnSync12("crontab", ["-l"], { encoding: "utf8" }).stdout ?? "" : "";
27231
27473
  const schedulerAbsent = o.host !== "windows" ? !schedulerInstalled(planInstall(cfg.ship, CREW_HOME, o.host, detectSystemd(), "run", installContext()), unitExists, crontab) : true;
27232
27474
  const plan = planFix({ routes, schedulerAbsent, host: o.host });
@@ -27298,7 +27540,7 @@ ${changed2.map((c) => ` - ${c}
27298
27540
  if (patterns.length > 0 && Object.keys(warm).length === 0 && firstReport(`warm-empty:${r.name}:${failure}`)) {
27299
27541
  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
27542
  }
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() } : {} });
27543
+ 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
27544
  }
27303
27545
  }
27304
27546
  return [...out.values()];
@@ -28646,6 +28888,7 @@ ${cu.tail.trimEnd()}
28646
28888
  });
28647
28889
  if (controlServer) emit.emit(`control API listening on ${controlServer.path}`);
28648
28890
  const inFlight = /* @__PURE__ */ new Set();
28891
+ const sandboxHygienePass = cfg.ship.runner === "sandbox" ? makeSandboxHygiene({ state, emit, ship: cfg.ship }) : void 0;
28649
28892
  let sandboxBuilding = false;
28650
28893
  const stopReason = await runDaemonLoop({
28651
28894
  inFlight,
@@ -28655,6 +28898,7 @@ ${cu.tail.trimEnd()}
28655
28898
  runPass: () => runOnePass({
28656
28899
  inFlight,
28657
28900
  sandboxCache: sandboxCachePass,
28901
+ sandboxHygiene: sandboxHygienePass,
28658
28902
  route: route2,
28659
28903
  ship: cfg.ship,
28660
28904
  state,
@@ -28693,7 +28937,7 @@ ${cu.tail.trimEnd()}
28693
28937
  ),
28694
28938
  checkStale: makeStaleChecker(watchPaths, { reloadSentinel: reloadSentinelFor(cfg.ship.stateDir) }),
28695
28939
  onPass: (result) => {
28696
- if (!sandboxBuilding) {
28940
+ if (!sandboxBuilding && !diskFullStop(state)) {
28697
28941
  sandboxBuilding = true;
28698
28942
  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
28943
  sandboxBuilding = false;
@@ -28801,9 +29045,9 @@ ${cu.tail.trimEnd()}
28801
29045
  `);
28802
29046
  process.exit(2);
28803
29047
  }
28804
- let run3;
29048
+ let run4;
28805
29049
  try {
28806
- run3 = await runAgentsSync(target, {
29050
+ run4 = await runAgentsSync(target, {
28807
29051
  userAgent: cfg.ship.userAgent,
28808
29052
  stateDir: cfg.ship.stateDir,
28809
29053
  dryRun,
@@ -28821,7 +29065,7 @@ ${cu.tail.trimEnd()}
28821
29065
  }
28822
29066
  throw e;
28823
29067
  }
28824
- const { personaResult, skillResult } = run3;
29068
+ const { personaResult, skillResult } = run4;
28825
29069
  if (flag("revoke-seat-keys")) {
28826
29070
  for (const o of await revokeSeatKeys(target, { userAgent: cfg.ship.userAgent, dryRun, shipName: cfg.ship.name })) {
28827
29071
  process.stdout.write(`${describeRevokeOutcome(o)}
@@ -28842,7 +29086,7 @@ ${cu.tail.trimEnd()}
28842
29086
  }
28843
29087
  }
28844
29088
  }
28845
- if (run3.diverged) process.exitCode = 1;
29089
+ if (run4.diverged) process.exitCode = 1;
28846
29090
  break;
28847
29091
  }
28848
29092
  case "skills": {
@@ -28884,7 +29128,7 @@ ${cu.tail.trimEnd()}
28884
29128
  `);
28885
29129
  if (!dryRun) {
28886
29130
  const resolvedPath = resolvedPathFor(cfg.ship.stateDir, target.route);
28887
- const raw = existsSync53(resolvedPath) ? JSON.parse(readFileSync48(resolvedPath, "utf8")) : {};
29131
+ const raw = existsSync54(resolvedPath) ? JSON.parse(readFileSync48(resolvedPath, "utf8")) : {};
28888
29132
  raw.agentSkills = result.agentSkills;
28889
29133
  mkdirSync40(dirOf2(resolvedPath), { recursive: true });
28890
29134
  writeFileSync40(resolvedPath, `${JSON.stringify(raw, null, 2)}
@@ -28989,8 +29233,8 @@ ${cu.tail.trimEnd()}
28989
29233
  try {
28990
29234
  const a = parseHooksArgs(positional.slice(2), routeNamesOf(configText));
28991
29235
  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) => {
29236
+ if (!existsSync54(dir)) throw new ReposError(`${dir} does not exist on disk`);
29237
+ const files = { exists: (r) => existsSync54(resolvePath(dir, r)), list: (r) => {
28994
29238
  try {
28995
29239
  return readdirSync20(resolvePath(dir, r));
28996
29240
  } catch {
@@ -29108,7 +29352,7 @@ ${cu.tail.trimEnd()}
29108
29352
  if (sub === "list" && !routeName) usage2();
29109
29353
  if (sub === "add") {
29110
29354
  try {
29111
- const a = parseAddArgs(positional.slice(2), routeNamesOf(configText), (p) => existsSync53(resolvePath(p.replace(/^~(?=\/|$)/, homedir11()))));
29355
+ const a = parseAddArgs(positional.slice(2), routeNamesOf(configText), (p) => existsSync54(resolvePath(p.replace(/^~(?=\/|$)/, homedir11()))));
29112
29356
  routeName = a.route;
29113
29357
  addPath = a.path;
29114
29358
  addName = a.name;
@@ -29138,7 +29382,7 @@ ${cu.tail.trimEnd()}
29138
29382
  const resolvedFile = resolvedPathFor(cfg.ship.stateDir, routeName);
29139
29383
  if (sub === "list" || sub === "add") {
29140
29384
  const liveRoute = cfg.routes.find((r) => r.route === routeName);
29141
- if (liveRoute?.resolved?.reposModelId && existsSync53(resolvedFile) && !dryRun) {
29385
+ if (liveRoute?.resolved?.reposModelId && existsSync54(resolvedFile) && !dryRun) {
29142
29386
  try {
29143
29387
  await hydrateApiKeys([liveRoute]);
29144
29388
  persistRepoRows(cfg.ship.stateDir, liveRoute.route, await new Tracker(liveRoute, cfg.ship).repoRowsForMap());
@@ -29147,7 +29391,7 @@ ${cu.tail.trimEnd()}
29147
29391
  }
29148
29392
  }
29149
29393
  let resolvedRemotes;
29150
- if (existsSync53(resolvedFile)) {
29394
+ if (existsSync54(resolvedFile)) {
29151
29395
  try {
29152
29396
  resolvedRemotes = JSON.parse(readFileSync48(resolvedFile, "utf8"));
29153
29397
  } catch {
@@ -29156,7 +29400,7 @@ ${cu.tail.trimEnd()}
29156
29400
  const originOf = (dir) => gitOk(dir, ["remote", "get-url", "origin"]) ?? void 0;
29157
29401
  const text2 = configText;
29158
29402
  const base = dirname35(cfg.configFile);
29159
- const isCheckout = (d) => existsSync53(`${d}/.git`);
29403
+ const isCheckout = (d) => existsSync54(`${d}/.git`);
29160
29404
  try {
29161
29405
  if (sub === "list") {
29162
29406
  if (flag("json")) {
@@ -29166,7 +29410,7 @@ ${cu.tail.trimEnd()}
29166
29410
  base,
29167
29411
  resolved: resolvedRemotes,
29168
29412
  originOf,
29169
- exists: (d) => existsSync53(d),
29413
+ exists: (d) => existsSync54(d),
29170
29414
  isCheckout,
29171
29415
  repoHasHooks: (d) => REPO_CONFIG_FILENAMES.some((f) => {
29172
29416
  try {
@@ -29188,7 +29432,7 @@ ${cu.tail.trimEnd()}
29188
29432
  for (const r of repos) {
29189
29433
  const origin2 = originOf(r.dir);
29190
29434
  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)"}`;
29435
+ const note = !existsSync54(r.dir) ? "missing on disk" : row ? `Repos row: ${row}` : `no Repos row matches ${normalizeRemote(origin2) ?? "this checkout (no origin remote)"}`;
29192
29436
  process.stdout.write(`${r.name} ${r.dir} ${note}
29193
29437
  `);
29194
29438
  }
@@ -29200,9 +29444,9 @@ ${cu.tail.trimEnd()}
29200
29444
  ` : `${human}
29201
29445
  `);
29202
29446
  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)) {
29447
+ if (existsSync54(plan2.target) && (existsSync54(`${plan2.target}/.git`) || readdirSync20(plan2.target).length > 0)) {
29204
29448
  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`
29449
+ 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
29450
  );
29207
29451
  }
29208
29452
  if (dryRun) {
@@ -29227,7 +29471,7 @@ ${cu.tail.trimEnd()}
29227
29471
  break;
29228
29472
  }
29229
29473
  const target = resolvePath(addPath.replace(/^~(?=\/|$)/, homedir11()));
29230
- const top = existsSync53(target) ? gitOk(target, ["rev-parse", "--show-toplevel"]) : null;
29474
+ const top = existsSync54(target) ? gitOk(target, ["rev-parse", "--show-toplevel"]) : null;
29231
29475
  if (!top) throw new ReposError(`${target} is not a git checkout`);
29232
29476
  const origin = originOf(top);
29233
29477
  const plan = planRepoAdd({
@@ -29279,7 +29523,7 @@ ${cu.tail.trimEnd()}
29279
29523
  const created = await rowTracker.createRepoRow(rowPayload);
29280
29524
  process.stdout.write(`created Repos row ${String(rowPayload.name)} (${String(rowPayload.remote)}) ${created.id}
29281
29525
  `);
29282
- if (existsSync53(resolvedFile)) {
29526
+ if (existsSync54(resolvedFile)) {
29283
29527
  const raw = JSON.parse(readFileSync48(resolvedFile, "utf8"));
29284
29528
  raw.repoNames = { ...raw.repoNames, [created.id]: String(rowPayload.name) };
29285
29529
  raw.repoRemotes = { ...raw.repoRemotes, [created.id]: String(rowPayload.remote) };
@@ -29705,7 +29949,7 @@ Signed in as ${result.identity.email} \u2014 minted an API key in workspace "${r
29705
29949
  }
29706
29950
  }
29707
29951
  let previous;
29708
- const hadPreviousFile = existsSync53(resolvedPath);
29952
+ const hadPreviousFile = existsSync54(resolvedPath);
29709
29953
  if (hadPreviousFile) {
29710
29954
  try {
29711
29955
  previous = JSON.parse(readFileSync48(resolvedPath, "utf8"));
@@ -30021,7 +30265,7 @@ Signed in as ${result.identity.email} \u2014 minted an API key in workspace "${r
30021
30265
  if (syncRoute?.resolved) {
30022
30266
  try {
30023
30267
  process.stderr.write("\n");
30024
- const run3 = await runAgentsSync(syncRoute, {
30268
+ const run4 = await runAgentsSync(syncRoute, {
30025
30269
  userAgent: cfg.ship.userAgent,
30026
30270
  stateDir: cfg.ship.stateDir,
30027
30271
  say: (l) => process.stderr.write(` ${l}
@@ -30036,19 +30280,19 @@ Signed in as ${result.identity.email} \u2014 minted an API key in workspace "${r
30036
30280
  if (p.state === "forbidden") process.stderr.write(` ${describeSeatForbidden(p.role, p.tables)}
30037
30281
  `);
30038
30282
  }
30039
- if (run3.readOnly) {
30040
- const missing = run3.personaResult.outcomes.some((p) => p.action === "missing");
30283
+ if (run4.readOnly) {
30284
+ const missing = run4.personaResult.outcomes.some((p) => p.action === "missing");
30041
30285
  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
30286
  }
30043
- connectEvents.emit("agents_synced", run3.readOnly ? "agents linked (read-only key)" : "agents synced", {
30287
+ connectEvents.emit("agents_synced", run4.readOnly ? "agents linked (read-only key)" : "agents synced", {
30044
30288
  route: route3,
30045
- admin: !run3.readOnly,
30046
- personas: run3.personaResult.outcomes,
30047
- skills: run3.skillResult?.outcomes ?? [],
30048
- diverged: run3.diverged
30289
+ admin: !run4.readOnly,
30290
+ personas: run4.personaResult.outcomes,
30291
+ skills: run4.skillResult?.outcomes ?? [],
30292
+ diverged: run4.diverged
30049
30293
  });
30050
30294
  for (const m of minted) connectEvents.emit("seat_key", describeMintOutcome(m), { route: route3, ...m });
30051
- if (run3.diverged) process.exitCode = 1;
30295
+ if (run4.diverged) process.exitCode = 1;
30052
30296
  } catch (e) {
30053
30297
  if (e instanceof AgentsSyncError || e instanceof SkillSyncError) skip(e.message);
30054
30298
  else throw e;
@@ -30604,7 +30848,7 @@ Signed in as ${result.identity.email} \u2014 minted an API key in workspace "${r
30604
30848
  prepare: async (path) => {
30605
30849
  for (const f of repoWt.config.worktrees.copy) {
30606
30850
  const src = join57(repoWt.dir, f);
30607
- if (!existsSync53(src) || existsSync53(join57(path, f))) continue;
30851
+ if (!existsSync54(src) || existsSync54(join57(path, f))) continue;
30608
30852
  mkdirSync40(dirOf2(join57(path, f)), { recursive: true });
30609
30853
  copyFileSync2(src, join57(path, f));
30610
30854
  }
@@ -30827,7 +31071,7 @@ Signed in as ${result.identity.email} \u2014 minted an API key in workspace "${r
30827
31071
  const shellR = hit && resolveShell(hit.repo.config.shell ?? cfg.ship.shell);
30828
31072
  const resumed = await runPeriscopeResume({
30829
31073
  find: async () => hit && { row: hit.row, tag: hit.tag },
30830
- worktreeExists: (p) => existsSync53(p),
31074
+ worktreeExists: (p) => existsSync54(p),
30831
31075
  prepareDropFile,
30832
31076
  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
31077
  caps: periscopeCaps(cfg.ship),
@@ -30924,7 +31168,7 @@ ${where.join("\n")}`);
30924
31168
  prepare: async (path) => {
30925
31169
  for (const f of repoP.config.worktrees.copy) {
30926
31170
  const src = join57(repoP.dir, f);
30927
- if (!existsSync53(src)) continue;
31171
+ if (!existsSync54(src)) continue;
30928
31172
  mkdirSync40(dirOf2(join57(path, f)), { recursive: true });
30929
31173
  copyFileSync2(src, join57(path, f));
30930
31174
  }
@@ -31427,7 +31671,7 @@ ${where.join("\n")}`);
31427
31671
  }
31428
31672
  if (row) {
31429
31673
  await tracker.deleteRepoRow(row.id);
31430
- if (existsSync53(resolvedFile)) {
31674
+ if (existsSync54(resolvedFile)) {
31431
31675
  const raw = JSON.parse(readFileSync48(resolvedFile, "utf8"));
31432
31676
  if (raw.repoNames) delete raw.repoNames[row.id];
31433
31677
  if (raw.repoRemotes) delete raw.repoRemotes[row.id];
@@ -31435,13 +31679,13 @@ ${where.join("\n")}`);
31435
31679
  `);
31436
31680
  }
31437
31681
  }
31438
- if (existsSync53(join57(dir, ".git")) && basename16(dir) === SAMPLE_REPO) rmSync25(dir, { recursive: true, force: true });
31682
+ if (existsSync54(join57(dir, ".git")) && basename16(dir) === SAMPLE_REPO) rmSync25(dir, { recursive: true, force: true });
31439
31683
  say("removed", { dir, closed }, `removed the sample repo${closed.length ? `, closed ${closed.join(", ")}` : ""}`);
31440
31684
  break;
31441
31685
  }
31442
31686
  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`);
31687
+ const fresh = !existsSync54(join57(dir, ".git"));
31688
+ if (existsSync54(dir) && fresh && readdirSync20(dir).length > 0) fail2(`${dir} exists and is not a git checkout \u2014 move it aside`);
31445
31689
  if (dryRun) {
31446
31690
  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
31691
  break;
@@ -31467,7 +31711,7 @@ ${where.join("\n")}`);
31467
31711
  spec: { platform: "unix", releaseMode: "integrate", ciProvider: "none" }
31468
31712
  });
31469
31713
  repoId = (await tracker.createRepoRow(payload)).id;
31470
- if (existsSync53(resolvedFile)) {
31714
+ if (existsSync54(resolvedFile)) {
31471
31715
  const raw = JSON.parse(readFileSync48(resolvedFile, "utf8"));
31472
31716
  raw.repoNames = { ...raw.repoNames, [repoId]: SAMPLE_REPO };
31473
31717
  raw.repoRemotes = { ...raw.repoRemotes, [repoId]: SAMPLE_REMOTE };
@@ -31823,7 +32067,7 @@ watermark: ${state.watermark()}
31823
32067
  }
31824
32068
  for (const r of repos) {
31825
32069
  const remote = r.config.branch.remote;
31826
- if (existsSync53(r.dir)) {
32070
+ if (existsSync54(r.dir)) {
31827
32071
  pushAuth.push({
31828
32072
  route: c.route,
31829
32073
  repo: r.name,
@@ -31871,6 +32115,10 @@ watermark: ${state.watermark()}
31871
32115
  image: sandboxImageForRun(readSandboxState(cfg.ship.stateDir), r.name, Boolean(r.config.sandbox)),
31872
32116
  hasBinary: imageHasBinary()
31873
32117
  }) : void 0,
32118
+ sandboxStoreProblem: cfg.ship.runner === "sandbox" ? (() => {
32119
+ const image = sandboxImageForRun(readSandboxState(cfg.ship.stateDir), r.name, Boolean(r.config.sandbox));
32120
+ return image ? imageStoreProblem()(image) : void 0;
32121
+ })() : void 0,
31874
32122
  mapFile: mapFilePath(r.config.hooks.map) ? inspectMapFile(r.dir, mapFilePath(r.config.hooks.map)) : void 0,
31875
32123
  intelSyntax: r.config.hooks.intel && !intelFlavor(r.config.hooks.intel) ? checkHookSyntax(r.config.hooks.intel, r.config.shell) : void 0,
31876
32124
  intelFlavor: intelFlavor(r.config.hooks.intel) ? { name: intelFlavor(r.config.hooks.intel), missing: [
@@ -31896,7 +32144,7 @@ watermark: ${state.watermark()}
31896
32144
  }
31897
32145
  }
31898
32146
  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);
32147
+ const runtimeDir = runtimeDirWarning(process.platform, process.getuid?.() ?? null, existsSync54, userInfo2().username);
31900
32148
  if (runtimeDir) problems.push({ severity: "attention", kind: "runtime_dir_missing", message: runtimeDir });
31901
32149
  if (!flag("offline")) {
31902
32150
  const shipKind = await doctorShipKind(route2, cfg.ship);
@@ -31961,7 +32209,7 @@ routes: ${cfg.routes.map((c) => c.route).join(", ")}
31961
32209
  }
31962
32210
  try {
31963
32211
  const evFile = eventFileFor(cfg.ship.stateDir);
31964
- const evSize = existsSync53(evFile) ? statSync16(evFile).size : 0;
32212
+ const evSize = existsSync54(evFile) ? statSync17(evFile).size : 0;
31965
32213
  process.stdout.write(
31966
32214
  evSize > cfg.ship.eventsRotateBytes * 4 ? `events log: WARN ${evFile} is ${Math.round(evSize / 1048576)} MB (> 4x eventsRotateBytes); run \`crew reap\` to rotate it
31967
32215
  ` : "events log: ok\n"
@@ -32001,7 +32249,7 @@ routes: ${cfg.routes.map((c) => c.route).join(", ")}
32001
32249
  if (host === "linux" && detectSystemd()) {
32002
32250
  const ctl = planDaemonControl(CREW_HOME, host, true);
32003
32251
  const unitPlan = planInstall(cfg.ship, CREW_HOME, host, true, "run", installContext());
32004
- if (ctl.statusCommand && unitPlan.unitPaths.some((p) => existsSync53(p))) {
32252
+ if (ctl.statusCommand && unitPlan.unitPaths.some((p) => existsSync54(p))) {
32005
32253
  const st = spawnSync12(ctl.statusCommand[0], ctl.statusCommand.slice(1), { cwd: CREW_HOME, encoding: "utf8" });
32006
32254
  if (!st.error && st.status !== 0) {
32007
32255
  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 +32268,7 @@ routes: ${cfg.routes.map((c) => c.route).join(", ")}
32020
32268
  const changed2 = configChangedAfter(daemonConfigPaths(cfg), daemonStartedAt);
32021
32269
  if (changed2) {
32022
32270
  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\`
32271
+ `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
32272
  `
32025
32273
  );
32026
32274
  }