@tablation/crew 0.137.10 → 0.138.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/cli.js +904 -579
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -6539,6 +6539,15 @@ function repoContractRefusedItem(repo, detail, nowIso = (/* @__PURE__ */ new Dat
6539
6539
  message: `${repo}: its repo contract is refused and the repository is skipped \u2014 ${detail}. Resumes automatically once the file is valid on its base; \`crew doctor\` names the problem`
6540
6540
  };
6541
6541
  }
6542
+ var repoPlatformUnreleasableKey = (repo) => `repo_platform_unreleasable:${repo}`;
6543
+ function repoPlatformUnreleasableItem(repo, detail, nowIso = (/* @__PURE__ */ new Date()).toISOString()) {
6544
+ return {
6545
+ kind: "repo_platform_unreleasable",
6546
+ key: repoPlatformUnreleasableKey(repo),
6547
+ since: nowIso,
6548
+ message: `${detail}. Resumes automatically once a ship that satisfies the platform serves the route or a verified branch changes it`
6549
+ };
6550
+ }
6542
6551
  var agentLogRefusedKey = (route2) => `agent_log_refused:${route2}`;
6543
6552
  function agentLogRefusedItem(route2, role, status2, nowIso = (/* @__PURE__ */ new Date()).toISOString()) {
6544
6553
  return {
@@ -6876,33 +6885,95 @@ import { promisify as promisify2 } from "util";
6876
6885
 
6877
6886
  // src/deprovision-host.ts
6878
6887
  import { spawnSync as spawnSync7 } from "child_process";
6879
- import { existsSync as existsSync31, readdirSync as readdirSync12 } from "fs";
6888
+ import { existsSync as existsSync32, readdirSync as readdirSync12 } from "fs";
6889
+
6890
+ // src/repo-env.ts
6891
+ import { existsSync as existsSync19, mkdirSync as mkdirSync14, readFileSync as readFileSync20, renameSync as renameSync3, rmSync as rmSync10, writeFileSync as writeFileSync15 } from "fs";
6892
+ import { dirname as dirname11, join as join22 } from "path";
6893
+ function repoEnvPathFor(stateDir) {
6894
+ return join22(stateDir, "repo-env.json");
6895
+ }
6896
+ function normalizeRemote(remote) {
6897
+ return remote.trim().toLowerCase().replace(/^[a-z+]+:\/\//, "").replace(/^[^@/]+@/, "").replace(":", "/").replace(/\.git$/, "").replace(/\/+$/, "");
6898
+ }
6899
+ function sanitizeRepositoryEnv(raw) {
6900
+ if (!Array.isArray(raw)) return [];
6901
+ const out = [];
6902
+ for (const e of raw) {
6903
+ if (!e || typeof e !== "object" || !e.env || typeof e.env !== "object") continue;
6904
+ const repoRowId = typeof e.repoRowId === "string" && e.repoRowId ? e.repoRowId : void 0;
6905
+ const remote = typeof e.remote === "string" && e.remote ? e.remote : void 0;
6906
+ if (!repoRowId && !remote) continue;
6907
+ const env = {};
6908
+ for (const [k, v] of Object.entries(e.env)) {
6909
+ if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(k) && typeof v === "string") env[k] = v;
6910
+ }
6911
+ if (Object.keys(env).length) out.push({ ...repoRowId ? { repoRowId } : {}, ...remote ? { remote } : {}, env });
6912
+ }
6913
+ return out;
6914
+ }
6915
+ function readRepositoryEnv(stateDir) {
6916
+ try {
6917
+ return sanitizeRepositoryEnv(JSON.parse(readFileSync20(repoEnvPathFor(stateDir), "utf8")));
6918
+ } catch {
6919
+ return [];
6920
+ }
6921
+ }
6922
+ function writeRepositoryEnv(stateDir, entries) {
6923
+ const file = repoEnvPathFor(stateDir);
6924
+ const clean = sanitizeRepositoryEnv(entries);
6925
+ if (!clean.length) {
6926
+ eraseRepositoryEnv(stateDir);
6927
+ return;
6928
+ }
6929
+ mkdirSync14(dirname11(file), { recursive: true, mode: 448 });
6930
+ const tmp = `${file}.tmp`;
6931
+ writeFileSync15(tmp, `${JSON.stringify(clean)}
6932
+ `, { mode: 384 });
6933
+ renameSync3(tmp, file);
6934
+ }
6935
+ function eraseRepositoryEnv(stateDir) {
6936
+ rmSync10(repoEnvPathFor(stateDir), { force: true });
6937
+ }
6938
+ function hasRepositoryEnv(stateDir) {
6939
+ return existsSync19(repoEnvPathFor(stateDir));
6940
+ }
6941
+ function repositoryEnvCount(stateDir) {
6942
+ return readRepositoryEnv(stateDir).length;
6943
+ }
6944
+ function envForRepository(entries, repo) {
6945
+ const byId = repo.repoRowId ? entries.find((e) => e.repoRowId === repo.repoRowId) : void 0;
6946
+ if (byId) return { ...byId.env };
6947
+ const want = repo.remote ? normalizeRemote(repo.remote) : "";
6948
+ const byRemote = want ? entries.find((e) => e.remote && normalizeRemote(e.remote) === want) : void 0;
6949
+ return byRemote ? { ...byRemote.env } : {};
6950
+ }
6880
6951
 
6881
6952
  // src/interrupted.ts
6882
- import { existsSync as existsSync29, readdirSync as readdirSync10, readFileSync as readFileSync30 } from "fs";
6883
- import { join as join32 } from "path";
6953
+ import { existsSync as existsSync30, readdirSync as readdirSync10, readFileSync as readFileSync31 } from "fs";
6954
+ import { join as join33 } from "path";
6884
6955
 
6885
6956
  // src/agent.ts
6886
6957
  import { spawnSync as spawnSync6 } from "child_process";
6887
- import { readFileSync as readFileSync29, existsSync as existsSync28, statSync as statSync9, mkdirSync as mkdirSync20, writeFileSync as writeFileSync21, createWriteStream, openSync as openSync4, closeSync as closeSync4, readSync } from "fs";
6958
+ import { readFileSync as readFileSync30, existsSync as existsSync29, statSync as statSync9, mkdirSync as mkdirSync21, writeFileSync as writeFileSync22, createWriteStream, openSync as openSync4, closeSync as closeSync4, readSync } from "fs";
6888
6959
  import { StringDecoder } from "string_decoder";
6889
6960
  import { finished } from "stream/promises";
6890
- import { join as join31, dirname as dirname15, basename as basename9 } from "path";
6961
+ import { join as join32, dirname as dirname16, basename as basename9 } from "path";
6891
6962
  import { createHash as createHash6, randomUUID } from "crypto";
6892
6963
 
6893
6964
  // src/state.ts
6894
- import { readFileSync as readFileSync20, writeFileSync as writeFileSync15, existsSync as existsSync19, mkdirSync as mkdirSync14, rmSync as rmSync10, statSync as statSync7, readdirSync as readdirSync6 } from "fs";
6895
- import { join as join22 } from "path";
6965
+ import { readFileSync as readFileSync21, writeFileSync as writeFileSync16, existsSync as existsSync20, mkdirSync as mkdirSync15, rmSync as rmSync11, statSync as statSync7, readdirSync as readdirSync6 } from "fs";
6966
+ import { join as join23 } from "path";
6896
6967
  var EPOCH = "1970-01-01T00:00:00.000Z";
6897
6968
  var watermarkFile = (scope) => scope ? `.poll-watermark-${scope}` : ".poll-watermark";
6898
6969
  var State = class _State {
6899
6970
  dir;
6900
6971
  constructor(dir) {
6901
6972
  this.dir = dir;
6902
- mkdirSync14(dir, { recursive: true });
6973
+ mkdirSync15(dir, { recursive: true });
6903
6974
  }
6904
6975
  path(...parts) {
6905
- return join22(this.dir, ...parts);
6976
+ return join23(this.dir, ...parts);
6906
6977
  }
6907
6978
  /**
6908
6979
  * The timestamp every "new since last poll" check is measured against.
@@ -6913,7 +6984,7 @@ var State = class _State {
6913
6984
  */
6914
6985
  watermark(scope) {
6915
6986
  try {
6916
- const v = readFileSync20(this.path(watermarkFile(scope)), "utf8").trim();
6987
+ const v = readFileSync21(this.path(watermarkFile(scope)), "utf8").trim();
6917
6988
  return v || EPOCH;
6918
6989
  } catch {
6919
6990
  if (scope) return this.watermark();
@@ -6921,7 +6992,7 @@ var State = class _State {
6921
6992
  }
6922
6993
  }
6923
6994
  setWatermark(at, scope) {
6924
- writeFileSync15(this.path(watermarkFile(scope)), `${at}
6995
+ writeFileSync16(this.path(watermarkFile(scope)), `${at}
6925
6996
  `);
6926
6997
  }
6927
6998
  /**
@@ -6939,19 +7010,19 @@ var State = class _State {
6939
7010
  }
6940
7011
  /** Whole-crew pause, and the per-role sentinels one level down. */
6941
7012
  isPaused() {
6942
- return existsSync19(this.path(".crew-paused"));
7013
+ return existsSync20(this.path(".crew-paused"));
6943
7014
  }
6944
7015
  isRolePaused(role) {
6945
- return existsSync19(this.path(`.role-paused-${role}`));
7016
+ return existsSync20(this.path(`.role-paused-${role}`));
6946
7017
  }
6947
7018
  pausedRoles(roles) {
6948
7019
  return new Set(roles.filter((r) => this.isRolePaused(r)));
6949
7020
  }
6950
7021
  pause(role) {
6951
- writeFileSync15(role ? this.path(`.role-paused-${role}`) : this.path(".crew-paused"), "");
7022
+ writeFileSync16(role ? this.path(`.role-paused-${role}`) : this.path(".crew-paused"), "");
6952
7023
  }
6953
7024
  resume(role) {
6954
- rmSync10(role ? this.path(`.role-paused-${role}`) : this.path(".crew-paused"), { force: true });
7025
+ rmSync11(role ? this.path(`.role-paused-${role}`) : this.path(".crew-paused"), { force: true });
6955
7026
  }
6956
7027
  /**
6957
7028
  * The release phase (merge, deploy, release) has its own sentinel, one
@@ -6959,11 +7030,11 @@ var State = class _State {
6959
7030
  * while agents keep working.
6960
7031
  */
6961
7032
  isReleasePaused() {
6962
- return existsSync19(this.path(".release-paused"));
7033
+ return existsSync20(this.path(".release-paused"));
6963
7034
  }
6964
7035
  setReleasePaused(paused) {
6965
- if (paused) writeFileSync15(this.path(".release-paused"), "");
6966
- else rmSync10(this.path(".release-paused"), { force: true });
7036
+ if (paused) writeFileSync16(this.path(".release-paused"), "");
7037
+ else rmSync11(this.path(".release-paused"), { force: true });
6967
7038
  }
6968
7039
  /**
6969
7040
  * Why a release cycle must not run right now, or null when it may. Every
@@ -7000,7 +7071,7 @@ var State = class _State {
7000
7071
  const name = _State.safe(rawName);
7001
7072
  const file = this.path(`.${name}.lock`);
7002
7073
  try {
7003
- const existing = Number.parseInt(readFileSync20(file, "utf8").trim(), 10);
7074
+ const existing = Number.parseInt(readFileSync21(file, "utf8").trim(), 10);
7004
7075
  if (Number.isFinite(existing) && existing > 0) {
7005
7076
  try {
7006
7077
  process.kill(existing, 0);
@@ -7010,13 +7081,13 @@ var State = class _State {
7010
7081
  }
7011
7082
  } catch {
7012
7083
  }
7013
- writeFileSync15(file, `${process.pid}
7084
+ writeFileSync16(file, `${process.pid}
7014
7085
  `);
7015
7086
  return {
7016
7087
  ok: true,
7017
7088
  release: () => {
7018
7089
  try {
7019
- rmSync10(file, { force: true });
7090
+ rmSync11(file, { force: true });
7020
7091
  } catch {
7021
7092
  }
7022
7093
  }
@@ -7038,7 +7109,7 @@ var State = class _State {
7038
7109
  if (!/^\.release-.+\.lock$/.test(n)) continue;
7039
7110
  let pid = 0;
7040
7111
  try {
7041
- pid = Number.parseInt(readFileSync20(this.path(n), "utf8").trim(), 10);
7112
+ pid = Number.parseInt(readFileSync21(this.path(n), "utf8").trim(), 10);
7042
7113
  } catch {
7043
7114
  continue;
7044
7115
  }
@@ -7124,7 +7195,7 @@ var State = class _State {
7124
7195
  ticketInFlight(recordId) {
7125
7196
  const file = this.path(`.${_State.safe(`crew-ticket-${recordId}`)}.lock`);
7126
7197
  try {
7127
- const pid = Number.parseInt(readFileSync20(file, "utf8").trim(), 10);
7198
+ const pid = Number.parseInt(readFileSync21(file, "utf8").trim(), 10);
7128
7199
  if (!Number.isFinite(pid) || pid <= 0) return false;
7129
7200
  process.kill(pid, 0);
7130
7201
  return true;
@@ -7158,7 +7229,7 @@ var State = class _State {
7158
7229
  const heldReported = `.release-held-${suffix}`;
7159
7230
  const read = (f) => {
7160
7231
  try {
7161
- return readFileSync20(this.path(f), "utf8").trim() || null;
7232
+ return readFileSync21(this.path(f), "utf8").trim() || null;
7162
7233
  } catch {
7163
7234
  return null;
7164
7235
  }
@@ -7167,12 +7238,12 @@ var State = class _State {
7167
7238
  blockedCount: () => Number.parseInt(read(blocked) ?? "", 10) || 0,
7168
7239
  noteBlocked: () => {
7169
7240
  const n = (Number.parseInt(read(blocked) ?? "", 10) || 0) + 1;
7170
- writeFileSync15(this.path(blocked), `${n}
7241
+ writeFileSync16(this.path(blocked), `${n}
7171
7242
  `);
7172
7243
  return n;
7173
7244
  },
7174
7245
  clearBlocked: () => {
7175
- rmSync10(this.path(blocked), { force: true });
7246
+ rmSync11(this.path(blocked), { force: true });
7176
7247
  },
7177
7248
  /**
7178
7249
  * The commit a deploy last failed on.
@@ -7184,11 +7255,11 @@ var State = class _State {
7184
7255
  */
7185
7256
  deployFailedSha: () => read(failed),
7186
7257
  noteDeployFailed: (sha) => {
7187
- writeFileSync15(this.path(failed), `${sha}
7258
+ writeFileSync16(this.path(failed), `${sha}
7188
7259
  `);
7189
7260
  },
7190
7261
  clearDeployFailed: () => {
7191
- rmSync10(this.path(failed), { force: true });
7262
+ rmSync11(this.path(failed), { force: true });
7192
7263
  },
7193
7264
  /**
7194
7265
  * Consecutive test-gate failures on the same head (CREW-1368). A failure
@@ -7198,31 +7269,31 @@ var State = class _State {
7198
7269
  noteTestGateFailed: (sha) => {
7199
7270
  const [prev, n] = (read(gateFailed) ?? "").split(" ");
7200
7271
  const next = prev === sha ? (Number.parseInt(n ?? "", 10) || 0) + 1 : 1;
7201
- writeFileSync15(this.path(gateFailed), `${sha} ${next}
7272
+ writeFileSync16(this.path(gateFailed), `${sha} ${next}
7202
7273
  `);
7203
7274
  return next;
7204
7275
  },
7205
7276
  clearTestGateFailed: () => {
7206
- rmSync10(this.path(gateFailed), { force: true });
7277
+ rmSync11(this.path(gateFailed), { force: true });
7207
7278
  },
7208
7279
  /** Whether the board was already told about this head's red gate. */
7209
7280
  heldReported: () => {
7210
7281
  try {
7211
- return readFileSync20(this.path(heldReported), "utf8").replace(/\n$/, "") || null;
7282
+ return readFileSync21(this.path(heldReported), "utf8").replace(/\n$/, "") || null;
7212
7283
  } catch {
7213
7284
  return null;
7214
7285
  }
7215
7286
  },
7216
7287
  noteHeldReported: (signature) => {
7217
- writeFileSync15(this.path(heldReported), `${signature}
7288
+ writeFileSync16(this.path(heldReported), `${signature}
7218
7289
  `);
7219
7290
  },
7220
7291
  clearHeldReported: () => {
7221
- rmSync10(this.path(heldReported), { force: true });
7292
+ rmSync11(this.path(heldReported), { force: true });
7222
7293
  },
7223
7294
  testGateReported: (sha) => read(gateReported) === sha,
7224
7295
  noteTestGateReported: (sha) => {
7225
- writeFileSync15(this.path(gateReported), `${sha}
7296
+ writeFileSync16(this.path(gateReported), `${sha}
7226
7297
  `);
7227
7298
  }
7228
7299
  };
@@ -7245,13 +7316,13 @@ var State = class _State {
7245
7316
  const ticketStreakFile = `.fairness-ticket-streak-${suffix}`;
7246
7317
  const read = (f) => {
7247
7318
  try {
7248
- return readFileSync20(this.path(f), "utf8").trim() || null;
7319
+ return readFileSync21(this.path(f), "utf8").trim() || null;
7249
7320
  } catch {
7250
7321
  return null;
7251
7322
  }
7252
7323
  };
7253
7324
  const clear2 = () => {
7254
- for (const f of [streakFile, ticketFile, sinceFile, ticketStreakFile]) rmSync10(this.path(f), { force: true });
7325
+ for (const f of [streakFile, ticketFile, sinceFile, ticketStreakFile]) rmSync11(this.path(f), { force: true });
7255
7326
  };
7256
7327
  return {
7257
7328
  /** Consecutive cycles this route had actionable work and did not win. */
@@ -7278,18 +7349,18 @@ var State = class _State {
7278
7349
  clear2();
7279
7350
  return;
7280
7351
  }
7281
- writeFileSync15(this.path(streakFile), `${this.readInt(streakFile) + 1}
7352
+ writeFileSync16(this.path(streakFile), `${this.readInt(streakFile) + 1}
7282
7353
  `);
7283
7354
  const prior = read(ticketFile);
7284
7355
  if (topTicket && topTicket === prior) {
7285
- writeFileSync15(this.path(ticketStreakFile), `${this.readInt(ticketStreakFile) + 1}
7356
+ writeFileSync16(this.path(ticketStreakFile), `${this.readInt(ticketStreakFile) + 1}
7286
7357
  `);
7287
7358
  } else if (topTicket) {
7288
- writeFileSync15(this.path(ticketFile), `${topTicket}
7359
+ writeFileSync16(this.path(ticketFile), `${topTicket}
7289
7360
  `);
7290
- writeFileSync15(this.path(sinceFile), `${(/* @__PURE__ */ new Date()).toISOString()}
7361
+ writeFileSync16(this.path(sinceFile), `${(/* @__PURE__ */ new Date()).toISOString()}
7291
7362
  `);
7292
- writeFileSync15(this.path(ticketStreakFile), "1\n");
7363
+ writeFileSync16(this.path(ticketStreakFile), "1\n");
7293
7364
  }
7294
7365
  }
7295
7366
  };
@@ -7310,14 +7381,14 @@ var State = class _State {
7310
7381
  return {
7311
7382
  previous: () => {
7312
7383
  try {
7313
- const parsed = JSON.parse(readFileSync20(this.path(file), "utf8"));
7384
+ const parsed = JSON.parse(readFileSync21(this.path(file), "utf8"));
7314
7385
  return parsed && typeof parsed === "object" ? parsed : {};
7315
7386
  } catch {
7316
7387
  return {};
7317
7388
  }
7318
7389
  },
7319
7390
  persist: (next) => {
7320
- writeFileSync15(this.path(file), JSON.stringify(next));
7391
+ writeFileSync16(this.path(file), JSON.stringify(next));
7321
7392
  }
7322
7393
  };
7323
7394
  }
@@ -7333,14 +7404,14 @@ var State = class _State {
7333
7404
  return {
7334
7405
  previous: () => {
7335
7406
  try {
7336
- const parsed = JSON.parse(readFileSync20(this.path(file), "utf8"));
7407
+ const parsed = JSON.parse(readFileSync21(this.path(file), "utf8"));
7337
7408
  return Array.isArray(parsed) ? parsed.filter((x) => typeof x === "string") : [];
7338
7409
  } catch {
7339
7410
  return [];
7340
7411
  }
7341
7412
  },
7342
7413
  persist: (next) => {
7343
- writeFileSync15(this.path(file), JSON.stringify(next));
7414
+ writeFileSync16(this.path(file), JSON.stringify(next));
7344
7415
  }
7345
7416
  };
7346
7417
  }
@@ -7354,14 +7425,14 @@ var State = class _State {
7354
7425
  return {
7355
7426
  previous: () => {
7356
7427
  try {
7357
- const parsed = JSON.parse(readFileSync20(this.path(file), "utf8"));
7428
+ const parsed = JSON.parse(readFileSync21(this.path(file), "utf8"));
7358
7429
  return Array.isArray(parsed) ? parsed : [];
7359
7430
  } catch {
7360
7431
  return [];
7361
7432
  }
7362
7433
  },
7363
7434
  persist: (next) => {
7364
- writeFileSync15(this.path(file), JSON.stringify(next));
7435
+ writeFileSync16(this.path(file), JSON.stringify(next));
7365
7436
  }
7366
7437
  };
7367
7438
  }
@@ -7374,7 +7445,7 @@ var State = class _State {
7374
7445
  const file = ".release-last-run";
7375
7446
  return {
7376
7447
  touch: () => {
7377
- writeFileSync15(this.path(file), (/* @__PURE__ */ new Date()).toISOString());
7448
+ writeFileSync16(this.path(file), (/* @__PURE__ */ new Date()).toISOString());
7378
7449
  },
7379
7450
  at: () => {
7380
7451
  try {
@@ -7387,7 +7458,7 @@ var State = class _State {
7387
7458
  }
7388
7459
  readInt(file) {
7389
7460
  try {
7390
- return Number.parseInt(readFileSync20(this.path(file), "utf8").trim(), 10) || 0;
7461
+ return Number.parseInt(readFileSync21(this.path(file), "utf8").trim(), 10) || 0;
7391
7462
  } catch {
7392
7463
  return 0;
7393
7464
  }
@@ -7395,7 +7466,7 @@ var State = class _State {
7395
7466
  };
7396
7467
 
7397
7468
  // src/signed-out.ts
7398
- import { readFileSync as readFileSync21 } from "fs";
7469
+ import { readFileSync as readFileSync22 } from "fs";
7399
7470
  var SIGNED_OUT_PATTERN = /not logged in|please run \/?login|\/login|invalid api key|failed to authenticate|oauth session expired|could not be refreshed|reauthentication is needed|application default credentials/i;
7400
7471
  function authModeOf(spec, hostEnv = process.env) {
7401
7472
  const env = { ...hostEnv, ...spec.env };
@@ -7442,7 +7513,7 @@ function eventsShowSignedOut(events) {
7442
7513
  function streamShowsSignedOut(streamPath) {
7443
7514
  let raw;
7444
7515
  try {
7445
- raw = readFileSync21(streamPath, "utf8");
7516
+ raw = readFileSync22(streamPath, "utf8");
7446
7517
  } catch {
7447
7518
  return false;
7448
7519
  }
@@ -7460,7 +7531,7 @@ function streamShowsSignedOut(streamPath) {
7460
7531
  function streamShowsRealTurn(streamPath) {
7461
7532
  let raw;
7462
7533
  try {
7463
- raw = readFileSync21(streamPath, "utf8");
7534
+ raw = readFileSync22(streamPath, "utf8");
7464
7535
  } catch {
7465
7536
  return false;
7466
7537
  }
@@ -8403,8 +8474,8 @@ function renderEnvironment(i) {
8403
8474
  }
8404
8475
 
8405
8476
  // src/intel-bridge.ts
8406
- import { existsSync as existsSync20, mkdirSync as mkdirSync15, readFileSync as readFileSync22, rmSync as rmSync11, writeFileSync as writeFileSync16 } from "fs";
8407
- import { dirname as dirname11, join as join23 } from "path";
8477
+ import { existsSync as existsSync21, mkdirSync as mkdirSync16, readFileSync as readFileSync23, rmSync as rmSync12, writeFileSync as writeFileSync17 } from "fs";
8478
+ import { dirname as dirname12, join as join24 } from "path";
8408
8479
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
8409
8480
  import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
8410
8481
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
@@ -8420,17 +8491,17 @@ var statusFailed = (reason) => `The symbol service did not start (${reason}). Ru
8420
8491
  var STATUS_LOST = "The symbol service stopped answering, so its tools are unavailable. They return if the service comes back; until then use text search.";
8421
8492
  function intelDir(stateDir, route2, ticket) {
8422
8493
  const safe = (s) => s.replace(/[^A-Za-z0-9._-]+/g, "_");
8423
- return join23(stateDir, "intel", safe(route2), safe(ticket));
8494
+ return join24(stateDir, "intel", safe(route2), safe(ticket));
8424
8495
  }
8425
- var attachFilePath = (stateDir, route2, ticket) => join23(intelDir(stateDir, route2, ticket), "url");
8496
+ var attachFilePath = (stateDir, route2, ticket) => join24(intelDir(stateDir, route2, ticket), "url");
8426
8497
  function writeAttachFile(file, url) {
8427
- mkdirSync15(dirname11(file), { recursive: true });
8428
- writeFileSync16(file, `${url}
8498
+ mkdirSync16(dirname12(file), { recursive: true });
8499
+ writeFileSync17(file, `${url}
8429
8500
  `);
8430
8501
  }
8431
8502
  function readAttachFile(file) {
8432
8503
  try {
8433
- const url = readFileSync22(file, "utf8").trim();
8504
+ const url = readFileSync23(file, "utf8").trim();
8434
8505
  return /^https?:\/\/\S+$/i.test(url) ? url : void 0;
8435
8506
  } catch {
8436
8507
  return void 0;
@@ -8552,7 +8623,7 @@ function createBridge(o) {
8552
8623
  tryAttach,
8553
8624
  async start(transport) {
8554
8625
  await server.connect(transport);
8555
- if (existsSync20(o.attachFile)) await tryAttach();
8626
+ if (existsSync21(o.attachFile)) await tryAttach();
8556
8627
  timer = setInterval(() => {
8557
8628
  void tryAttach();
8558
8629
  }, o.pollMs ?? 1e3);
@@ -8809,14 +8880,14 @@ var BeforeFirstEditTracker = class {
8809
8880
  };
8810
8881
 
8811
8882
  // src/agent-log.ts
8812
- import { existsSync as existsSync24, mkdirSync as mkdirSync17, readdirSync as readdirSync8, readFileSync as readFileSync24, rmSync as rmSync13, writeFileSync as writeFileSync18 } from "fs";
8813
- import { join as join26 } from "path";
8883
+ import { existsSync as existsSync25, mkdirSync as mkdirSync18, readdirSync as readdirSync8, readFileSync as readFileSync25, rmSync as rmSync14, writeFileSync as writeFileSync19 } from "fs";
8884
+ import { join as join27 } from "path";
8814
8885
 
8815
8886
  // src/pending-backoff.ts
8816
8887
  var sleepBackoff = (attempts) => Math.min(6e4 * 2 ** Math.max(0, attempts - 1), 30 * 6e4);
8817
8888
 
8818
8889
  // src/handoff-guard.ts
8819
- import { existsSync as existsSync23 } from "fs";
8890
+ import { existsSync as existsSync24 } from "fs";
8820
8891
 
8821
8892
  // src/ticket-branch.ts
8822
8893
  import { basename as basename7 } from "path";
@@ -9902,23 +9973,23 @@ function materializeBranchForTicket(dir, cfg, t, role, onProblem, onReset) {
9902
9973
  }
9903
9974
 
9904
9975
  // src/pending-handoff.ts
9905
- import { existsSync as existsSync21, mkdirSync as mkdirSync16, readdirSync as readdirSync7, readFileSync as readFileSync23, rmSync as rmSync12, writeFileSync as writeFileSync17 } from "fs";
9906
- import { join as join24 } from "path";
9976
+ import { existsSync as existsSync22, mkdirSync as mkdirSync17, readdirSync as readdirSync7, readFileSync as readFileSync24, rmSync as rmSync13, writeFileSync as writeFileSync18 } from "fs";
9977
+ import { join as join25 } from "path";
9907
9978
  var PENDING_MAX_AGE_MS = 48 * 36e5;
9908
- var pendingDirFor = (stateDir) => join24(stateDir, "pending-handoffs");
9909
- var stateDirOfStream = (streamPath) => join24(streamPath, "..", "..");
9979
+ var pendingDirFor = (stateDir) => join25(stateDir, "pending-handoffs");
9980
+ var stateDirOfStream = (streamPath) => join25(streamPath, "..", "..");
9910
9981
  function writePendingHandoff(stateDir, rec) {
9911
9982
  const dir = pendingDirFor(stateDir);
9912
- mkdirSync16(dir, { recursive: true });
9913
- writeFileSync17(join24(dir, `${rec.ticketRecordId}.json`), JSON.stringify(rec, null, 2));
9983
+ mkdirSync17(dir, { recursive: true });
9984
+ writeFileSync18(join25(dir, `${rec.ticketRecordId}.json`), JSON.stringify(rec, null, 2));
9914
9985
  }
9915
9986
  function listPendingHandoffs(stateDir, route2) {
9916
9987
  const dir = pendingDirFor(stateDir);
9917
- if (!existsSync21(dir)) return [];
9988
+ if (!existsSync22(dir)) return [];
9918
9989
  const out = [];
9919
9990
  for (const f of readdirSync7(dir).filter((n) => n.endsWith(".json")).sort()) {
9920
9991
  try {
9921
- const rec = JSON.parse(readFileSync23(join24(dir, f), "utf8"));
9992
+ const rec = JSON.parse(readFileSync24(join25(dir, f), "utf8"));
9922
9993
  if (rec.version === 1 && rec.ticketRecordId && (!route2 || rec.route === route2)) out.push(rec);
9923
9994
  } catch {
9924
9995
  }
@@ -9926,7 +9997,7 @@ function listPendingHandoffs(stateDir, route2) {
9926
9997
  return out;
9927
9998
  }
9928
9999
  function removePendingHandoff(stateDir, ticketRecordId) {
9929
- rmSync12(join24(pendingDirFor(stateDir), `${ticketRecordId}.json`), { force: true });
10000
+ rmSync13(join25(pendingDirFor(stateDir), `${ticketRecordId}.json`), { force: true });
9930
10001
  }
9931
10002
  function pendingHandoffFor(stateDir, ticketRecordId) {
9932
10003
  return listPendingHandoffs(stateDir).find((r) => r.ticketRecordId === ticketRecordId);
@@ -10102,8 +10173,8 @@ function holdWarnings(tickets, ships, contract, humanHolds, now = Date.now()) {
10102
10173
  }
10103
10174
 
10104
10175
  // src/run-worktree.ts
10105
- import { existsSync as existsSync22 } from "fs";
10106
- import { dirname as dirname12, join as join25 } from "path";
10176
+ import { existsSync as existsSync23 } from "fs";
10177
+ import { dirname as dirname13, join as join26 } from "path";
10107
10178
  var describeRunWorktreePlan = (p) => {
10108
10179
  switch (p.action) {
10109
10180
  case "cut-remote":
@@ -10144,7 +10215,7 @@ function planRunWorktree(dir, cfg, t, role, opts = {}) {
10144
10215
  const existing = worktreeForNumber(dir, num2);
10145
10216
  const located = locateBranchForTicket(dir, cfg, t, role);
10146
10217
  const baseRef = hasRemote ? `${remote}/${base}` : base;
10147
- if (existing && !existing.prunable && existsSync22(existing.path)) {
10218
+ if (existing && !existing.prunable && existsSync23(existing.path)) {
10148
10219
  const branch = existing.branch;
10149
10220
  if (status(existing.path).length > 0) {
10150
10221
  return { action: opts.resumeInterrupted ? "resume-dirty" : "leave-dirty", path: existing.path, branch };
@@ -10160,7 +10231,7 @@ function planRunWorktree(dir, cfg, t, role, opts = {}) {
10160
10231
  if (countCommits(existing.path, `${baseRef}..HEAD`) > 0) return { action: "leave-unpushed", path: existing.path, branch };
10161
10232
  return { action: "recut", path: existing.path, branch, base: baseRef };
10162
10233
  }
10163
- const path = join25(dirname12(dir), worktreeForTicket(dir, cfg, t, role));
10234
+ const path = join26(dirname13(dir), worktreeForTicket(dir, cfg, t, role));
10164
10235
  if (located?.where === "remote" || located && hasRemote && remoteBranchExists(dir, remote, located.branch)) {
10165
10236
  return { action: "cut-remote", path, branch: located.branch };
10166
10237
  }
@@ -10214,7 +10285,7 @@ function dropEmptyRunBranch(dir, cfg, branch) {
10214
10285
  if (remoteConfigured(dir, remote) && remoteBranchExists(dir, remote, branch)) return false;
10215
10286
  if (countCommits(dir, `${baseRef}..${branch}`) !== 0) return false;
10216
10287
  const wt = worktrees(dir).find((w) => w.branch === branch && !w.prunable && w.path !== dir);
10217
- if (wt && existsSync22(wt.path)) {
10288
+ if (wt && existsSync23(wt.path)) {
10218
10289
  if (status(wt.path).length > 0) return false;
10219
10290
  if (gitOk(dir, ["worktree", "remove", wt.path]) === null) return false;
10220
10291
  }
@@ -10222,7 +10293,7 @@ function dropEmptyRunBranch(dir, cfg, branch) {
10222
10293
  }
10223
10294
  async function finishRunWorktree(dir, cfg, branch) {
10224
10295
  const wt = worktrees(dir).find((w) => w.branch === branch && !w.prunable && w.path !== dir);
10225
- if (!wt || !existsSync22(wt.path)) return { kind: "none" };
10296
+ if (!wt || !existsSync23(wt.path)) return { kind: "none" };
10226
10297
  if (cfg.hooks.handoff) return { kind: "kept-handoff", path: wt.path };
10227
10298
  if (status(wt.path).length > 0) return { kind: "kept-dirty", path: wt.path };
10228
10299
  if (remoteConfigured(dir, cfg.branch.remote) && worktreeHoldsUnpushed(wt.path, cfg.branch.remote)) {
@@ -10234,7 +10305,7 @@ async function finishRunWorktree(dir, cfg, branch) {
10234
10305
  if (pids.length) await killGently(pids);
10235
10306
  }
10236
10307
  gitOk(dir, ["worktree", "remove", wt.path]);
10237
- return existsSync22(wt.path) ? { kind: "kept-dirty", path: wt.path } : { kind: "removed", path: wt.path };
10308
+ return existsSync23(wt.path) ? { kind: "kept-dirty", path: wt.path } : { kind: "removed", path: wt.path };
10238
10309
  }
10239
10310
 
10240
10311
  // src/handoff-guard.ts
@@ -10292,7 +10363,7 @@ function inspectRemoteHandoff(origin, cfg, ticket, role) {
10292
10363
  function describeGuardError(e, dir) {
10293
10364
  const msg = e.message;
10294
10365
  if (!/ENOENT/.test(msg)) return msg;
10295
- return dir && !existsSync23(dir) ? `the run's clone at ${dir} is gone` : "git is not installed on this machine";
10366
+ return dir && !existsSync24(dir) ? `the run's clone at ${dir} is gone` : "git is not installed on this machine";
10296
10367
  }
10297
10368
  function inspectHandoff(dir, cfg, ticket, role) {
10298
10369
  const remote = cfg.branch.remote;
@@ -10850,9 +10921,12 @@ async function writeHandoffBounces(target, rowId, count) {
10850
10921
  }
10851
10922
  }
10852
10923
  async function post(target, path, body) {
10924
+ return send(target, "POST", path, body);
10925
+ }
10926
+ async function send(target, method, path, body) {
10853
10927
  const url = `${target.baseUrl.replace(/\/+$/, "")}/api/workspaces/${target.workspaceId}${path}`;
10854
10928
  const res = await fetch(url, {
10855
- method: "POST",
10929
+ method,
10856
10930
  headers: {
10857
10931
  Authorization: `Bearer ${target.apiKey}`,
10858
10932
  // Cloudflare 403s default agents on this host — same header connect.ts sends.
@@ -10864,24 +10938,41 @@ async function post(target, path, body) {
10864
10938
  if (!res.ok) throw new AgentLogHttpError(`${path}: ${res.status} ${res.statusText}`, res.status);
10865
10939
  return await res.json();
10866
10940
  }
10867
- var RUNNING_OUTCOME = "running";
10868
10941
  async function startAgentRunRow(target, s) {
10942
+ if (!target.actor && !s.runId) return void 0;
10943
+ const body = {
10944
+ agentId: target.agentId,
10945
+ ticketReference: s.ticketReference,
10946
+ startedAt: s.startedAt,
10947
+ source: "client",
10948
+ client: "crew",
10949
+ model: s.model,
10950
+ promptVersion: s.promptVersion,
10951
+ promptSha: s.promptSha,
10952
+ runId: s.runId,
10953
+ harness: s.harness,
10954
+ provider: s.provider
10955
+ };
10956
+ let actor = {};
10957
+ if (target.actor) {
10958
+ let label = s.actorLabel;
10959
+ try {
10960
+ const row = await request(target, "GET", `/data-models/${target.actor.table}/records/${target.actor.recordId}`);
10961
+ if (row.name) label = row.name;
10962
+ } catch {
10963
+ }
10964
+ actor = { actorTable: target.actor.table, actorRecordId: target.actor.recordId, ...label ? { actorLabel: label } : {} };
10965
+ }
10869
10966
  try {
10870
- const entry = await post(target, "/agents/log", {
10871
- agentId: target.agentId,
10872
- ticketReference: s.ticketReference,
10873
- outcome: RUNNING_OUTCOME,
10874
- startedAt: s.startedAt,
10875
- source: "client",
10876
- client: "crew",
10877
- model: s.model,
10878
- promptVersion: s.promptVersion,
10879
- promptSha: s.promptSha,
10880
- runId: s.runId,
10881
- harness: s.harness,
10882
- provider: s.provider
10883
- });
10884
- return entry.id;
10967
+ const entry = await post(target, "/agents/log", { ...body, ...actor });
10968
+ return { id: entry.id, live: target.actor !== void 0 };
10969
+ } catch (e) {
10970
+ if (!(e instanceof AgentLogHttpError) || e.status !== 400 || Object.keys(actor).length === 0) return void 0;
10971
+ }
10972
+ if (!s.runId) return void 0;
10973
+ try {
10974
+ const entry = await post(target, "/agents/log", body);
10975
+ return { id: entry.id, live: false };
10885
10976
  } catch {
10886
10977
  return void 0;
10887
10978
  }
@@ -10927,6 +11018,92 @@ async function updateStartedRow(target, rowId, body) {
10927
11018
  throw e;
10928
11019
  }
10929
11020
  }
11021
+ var CYCLE_BODY_LIMIT_BYTES = 2048;
11022
+ var CYCLE_TRUNCATION_MARKER = " \u2026[truncated]";
11023
+ var MAX_CYCLES_PER_BATCH = 200;
11024
+ function capCycleText(text2) {
11025
+ if (Buffer.byteLength(text2) <= CYCLE_BODY_LIMIT_BYTES) return text2;
11026
+ const room = CYCLE_BODY_LIMIT_BYTES - Buffer.byteLength(CYCLE_TRUNCATION_MARKER);
11027
+ let out = text2.slice(0, room);
11028
+ while (Buffer.byteLength(out) > room) out = out.slice(0, -1);
11029
+ return out + CYCLE_TRUNCATION_MARKER;
11030
+ }
11031
+ var LiveRunReporter = class {
11032
+ /** Cycles delivered to the row, from the start of the run. */
11033
+ posted = 0;
11034
+ live = true;
11035
+ nextIndex = 0;
11036
+ pending = [];
11037
+ lastSent = Date.now();
11038
+ timer;
11039
+ inFlight = Promise.resolve();
11040
+ windowMs;
11041
+ heartbeatMs;
11042
+ target;
11043
+ rowId;
11044
+ o;
11045
+ constructor(target, rowId, o = {}, alreadyPosted = 0) {
11046
+ this.target = target;
11047
+ this.rowId = rowId;
11048
+ this.o = o;
11049
+ this.windowMs = o.windowMs ?? 4e3;
11050
+ this.heartbeatMs = o.heartbeatMs ?? 3e4;
11051
+ this.posted = alreadyPosted;
11052
+ this.nextIndex = alreadyPosted;
11053
+ }
11054
+ start() {
11055
+ if (this.timer || !this.live) return;
11056
+ this.timer = setInterval(() => {
11057
+ void this.tick();
11058
+ }, this.windowMs);
11059
+ this.timer.unref?.();
11060
+ }
11061
+ /** Buffers one cycle for the next batch. A cycle already delivered or buffered is ignored. */
11062
+ add(c) {
11063
+ if (!this.live || c.cycleIndex < this.nextIndex) return;
11064
+ this.nextIndex = c.cycleIndex + 1;
11065
+ this.pending.push({ ...c, thinking: capCycleText(c.thinking) });
11066
+ }
11067
+ /** One window: send the buffered cycles, or a heartbeat when idle too long. Serialized. */
11068
+ tick() {
11069
+ this.inFlight = this.inFlight.then(() => this.step());
11070
+ return this.inFlight;
11071
+ }
11072
+ /** Stops the timer and waits out a send in flight. What is still buffered is left to the end-of-run report. */
11073
+ async stop() {
11074
+ if (this.timer) clearInterval(this.timer);
11075
+ this.timer = void 0;
11076
+ await this.inFlight;
11077
+ }
11078
+ async step() {
11079
+ if (!this.live) return;
11080
+ try {
11081
+ if (this.pending.length > 0) {
11082
+ const batch = this.pending.slice(0, MAX_CYCLES_PER_BATCH);
11083
+ await post(this.target, `/agents/log/${this.rowId}/cycles`, batch.map((c) => ({
11084
+ cycleIndex: c.cycleIndex,
11085
+ occurredAt: c.occurredAt,
11086
+ thinking: c.thinking,
11087
+ ...c.role ? { role: c.role } : {}
11088
+ })));
11089
+ this.pending.splice(0, batch.length);
11090
+ this.posted = batch[batch.length - 1].cycleIndex + 1;
11091
+ this.lastSent = Date.now();
11092
+ this.o.onPosted?.(this.posted);
11093
+ } else if (Date.now() - this.lastSent >= this.heartbeatMs) {
11094
+ await send(this.target, "PATCH", `/agents/log/${this.rowId}`, {});
11095
+ this.lastSent = Date.now();
11096
+ }
11097
+ } catch (e) {
11098
+ if (e instanceof AgentLogHttpError && e.status < 500) {
11099
+ this.live = false;
11100
+ if (this.timer) clearInterval(this.timer);
11101
+ this.timer = void 0;
11102
+ this.pending.length = 0;
11103
+ }
11104
+ }
11105
+ }
11106
+ };
10930
11107
  async function reportAgentRun(target, run4) {
10931
11108
  let ticketRecordId;
10932
11109
  if (target.tickets && run4.ticketReference) {
@@ -10976,7 +11153,7 @@ async function reportAgentRun(target, run4) {
10976
11153
  }
10977
11154
  }
10978
11155
  }
10979
- for (const cycle of run4.cycles) {
11156
+ for (const cycle of run4.cycles.slice(run4.cyclesPosted ?? 0)) {
10980
11157
  await post(target, `/agents/log/${entry.id}/cycles`, {
10981
11158
  cycleIndex: cycle.cycleIndex,
10982
11159
  occurredAt: cycle.occurredAt,
@@ -11032,20 +11209,20 @@ async function addRunToTicket(target, t, recordId, run4) {
11032
11209
  };
11033
11210
  }
11034
11211
  }
11035
- var queueDir = (stateDir) => join26(stateDir, "pending-agent-logs");
11212
+ var queueDir = (stateDir) => join27(stateDir, "pending-agent-logs");
11036
11213
  function queueAgentRun(stateDir, name, q2) {
11037
- mkdirSync17(queueDir(stateDir), { recursive: true });
11038
- writeFileSync18(join26(queueDir(stateDir), `${name}.json`), JSON.stringify(q2));
11214
+ mkdirSync18(queueDir(stateDir), { recursive: true });
11215
+ writeFileSync19(join27(queueDir(stateDir), `${name}.json`), JSON.stringify(q2));
11039
11216
  }
11040
11217
  async function replayQueuedAgentRuns(stateDir, route2, keyFor, log, now = /* @__PURE__ */ new Date()) {
11041
11218
  const dir = queueDir(stateDir);
11042
- if (!existsSync24(dir)) return 0;
11219
+ if (!existsSync25(dir)) return 0;
11043
11220
  let sent = 0;
11044
11221
  for (const f of readdirSync8(dir).filter((n) => n.endsWith(".json")).sort()) {
11045
- const path = join26(dir, f);
11222
+ const path = join27(dir, f);
11046
11223
  let q2;
11047
11224
  try {
11048
- q2 = JSON.parse(readFileSync24(path, "utf8"));
11225
+ q2 = JSON.parse(readFileSync25(path, "utf8"));
11049
11226
  } catch {
11050
11227
  continue;
11051
11228
  }
@@ -11064,17 +11241,17 @@ async function replayQueuedAgentRuns(stateDir, route2, keyFor, log, now = /* @__
11064
11241
  attempts: 0,
11065
11242
  nextAttemptAt: (/* @__PURE__ */ new Date()).toISOString()
11066
11243
  });
11067
- rmSync13(path, { force: true });
11244
+ rmSync14(path, { force: true });
11068
11245
  sent += 1;
11069
11246
  log.emit(`sent a queued Agent Log report (${f})`);
11070
11247
  } catch (e) {
11071
11248
  if (!(e instanceof AgentLogUnreachableError)) {
11072
- rmSync13(path, { force: true });
11249
+ rmSync14(path, { force: true });
11073
11250
  log.warn(`dropped a queued Agent Log report (${f}): ${e.message}`);
11074
11251
  continue;
11075
11252
  }
11076
11253
  const attempts = q2.attempts + 1;
11077
- writeFileSync18(path, JSON.stringify({
11254
+ writeFileSync19(path, JSON.stringify({
11078
11255
  ...q2,
11079
11256
  attempts,
11080
11257
  warned: true,
@@ -11085,20 +11262,20 @@ async function replayQueuedAgentRuns(stateDir, route2, keyFor, log, now = /* @__
11085
11262
  }
11086
11263
  return sent;
11087
11264
  }
11088
- var countersDir = (stateDir) => join26(stateDir, "pending-ticket-counters");
11265
+ var countersDir = (stateDir) => join27(stateDir, "pending-ticket-counters");
11089
11266
  function queueTicketCounters(stateDir, name, q2) {
11090
- mkdirSync17(countersDir(stateDir), { recursive: true });
11091
- writeFileSync18(join26(countersDir(stateDir), `${name}.json`), JSON.stringify(q2));
11267
+ mkdirSync18(countersDir(stateDir), { recursive: true });
11268
+ writeFileSync19(join27(countersDir(stateDir), `${name}.json`), JSON.stringify(q2));
11092
11269
  }
11093
11270
  async function replayQueuedTicketCounters(stateDir, route2, keyFor, log, now = /* @__PURE__ */ new Date()) {
11094
11271
  const dir = countersDir(stateDir);
11095
- if (!existsSync24(dir)) return 0;
11272
+ if (!existsSync25(dir)) return 0;
11096
11273
  let sent = 0;
11097
11274
  for (const f of readdirSync8(dir).filter((n) => n.endsWith(".json")).sort()) {
11098
- const path = join26(dir, f);
11275
+ const path = join27(dir, f);
11099
11276
  let q2;
11100
11277
  try {
11101
- q2 = JSON.parse(readFileSync24(path, "utf8"));
11278
+ q2 = JSON.parse(readFileSync25(path, "utf8"));
11102
11279
  } catch {
11103
11280
  continue;
11104
11281
  }
@@ -11107,17 +11284,17 @@ async function replayQueuedTicketCounters(stateDir, route2, keyFor, log, now = /
11107
11284
  const apiKey = await keyFor(q2.role);
11108
11285
  if (!apiKey) continue;
11109
11286
  await writeCounters({ ...q2.target, apiKey }, q2.write);
11110
- rmSync13(path, { force: true });
11287
+ rmSync14(path, { force: true });
11111
11288
  sent += 1;
11112
11289
  log.emit(`added a queued run's spend to ${q2.write.ticketReference ?? q2.write.recordId} (${f})`);
11113
11290
  } catch (e) {
11114
11291
  if (!isRetryable(e)) {
11115
- rmSync13(path, { force: true });
11292
+ rmSync14(path, { force: true });
11116
11293
  log.warn(`dropped a queued ticket counter update (${f}): ${e.message}`);
11117
11294
  continue;
11118
11295
  }
11119
11296
  const attempts = q2.attempts + 1;
11120
- writeFileSync18(path, JSON.stringify({
11297
+ writeFileSync19(path, JSON.stringify({
11121
11298
  ...q2,
11122
11299
  attempts,
11123
11300
  warned: true,
@@ -11360,8 +11537,8 @@ var HandoffTranscriptTracker = class {
11360
11537
  import { createHash as createHash4 } from "crypto";
11361
11538
  import { spawn as spawn4 } from "child_process";
11362
11539
  import { execFileSync as execFileSync8 } from "child_process";
11363
- import { existsSync as existsSync25, mkdirSync as mkdirSync18, readFileSync as readFileSync25, renameSync as renameSync3, writeFileSync as writeFileSync19, rmSync as rmSync14, statSync as statSync8 } from "fs";
11364
- import { dirname as dirname13, join as join27 } from "path";
11540
+ import { existsSync as existsSync26, mkdirSync as mkdirSync19, readFileSync as readFileSync26, renameSync as renameSync4, writeFileSync as writeFileSync20, rmSync as rmSync15, statSync as statSync8 } from "fs";
11541
+ import { dirname as dirname14, join as join28 } from "path";
11365
11542
  import { fileURLToPath } from "url";
11366
11543
  import { tmpdir as tmpdir3 } from "os";
11367
11544
  var SANDBOX_BASE_IMAGE = "nvcr.io/nvidia/base/ubuntu:24.04";
@@ -11376,9 +11553,9 @@ var SANDBOX_UID = 1e3;
11376
11553
  var CREW_PREFIX = "/opt/crew";
11377
11554
  var SANDBOX_BRIDGE_PATH = `${CREW_PREFIX}/bin/intel-bridge`;
11378
11555
  function readBridgeBundle() {
11379
- const here = dirname13(fileURLToPath(import.meta.url));
11380
- for (const p of [join27(here, "sandbox-intel-bridge.cjs"), join27(here, "..", "dist", "sandbox-intel-bridge.cjs")]) {
11381
- if (existsSync25(p)) return readFileSync25(p, "utf8");
11556
+ const here = dirname14(fileURLToPath(import.meta.url));
11557
+ for (const p of [join28(here, "sandbox-intel-bridge.cjs"), join28(here, "..", "dist", "sandbox-intel-bridge.cjs")]) {
11558
+ if (existsSync26(p)) return readFileSync26(p, "utf8");
11382
11559
  }
11383
11560
  return void 0;
11384
11561
  }
@@ -11462,7 +11639,7 @@ var HOST_CA_BUNDLES = ["/etc/ssl/certs/ca-certificates.crt", "/etc/pki/tls/certs
11462
11639
  function readHostCaBundle(paths = HOST_CA_BUNDLES) {
11463
11640
  for (const path of paths) {
11464
11641
  try {
11465
- return readFileSync25(path, "utf8");
11642
+ return readFileSync26(path, "utf8");
11466
11643
  } catch {
11467
11644
  }
11468
11645
  }
@@ -11553,21 +11730,21 @@ function planSandbox(repo, decl, warm = {}, bridge) {
11553
11730
  }
11554
11731
  var SHIP_SANDBOX_KEY = "@ship";
11555
11732
  var shipSandboxRef = () => ({ name: SHIP_SANDBOX_KEY, decl: { packages: [], setup: [] } });
11556
- var sandboxStatePath = (stateDir) => join27(stateDir, "sandbox-images.json");
11733
+ var sandboxStatePath = (stateDir) => join28(stateDir, "sandbox-images.json");
11557
11734
  function readSandboxState(stateDir) {
11558
11735
  try {
11559
- const v = JSON.parse(readFileSync25(sandboxStatePath(stateDir), "utf8"));
11736
+ const v = JSON.parse(readFileSync26(sandboxStatePath(stateDir), "utf8"));
11560
11737
  return v && typeof v === "object" && !Array.isArray(v) ? v : {};
11561
11738
  } catch {
11562
11739
  return {};
11563
11740
  }
11564
11741
  }
11565
11742
  function writeSandboxState(stateDir, state) {
11566
- mkdirSync18(stateDir, { recursive: true });
11743
+ mkdirSync19(stateDir, { recursive: true });
11567
11744
  const file = sandboxStatePath(stateDir);
11568
- writeFileSync19(`${file}.tmp`, `${JSON.stringify(state, null, 2)}
11745
+ writeFileSync20(`${file}.tmp`, `${JSON.stringify(state, null, 2)}
11569
11746
  `);
11570
- renameSync3(`${file}.tmp`, file);
11747
+ renameSync4(`${file}.tmp`, file);
11571
11748
  }
11572
11749
  function sandboxImageFor(state, repo) {
11573
11750
  return state[repo]?.tags[0]?.tag ?? null;
@@ -11603,7 +11780,7 @@ var spawnBuildRunner = (engine = "docker") => (args, logPath) => new Promise((re
11603
11780
  child.stdout.on("data", (d) => chunks.push(d));
11604
11781
  child.stderr.on("data", (d) => chunks.push(d));
11605
11782
  const done = (code, extra = "") => {
11606
- writeFileSync19(logPath, `$ ${engine} ${args.join(" ")}
11783
+ writeFileSync20(logPath, `$ ${engine} ${args.join(" ")}
11607
11784
  ${Buffer.concat(chunks).toString("utf8")}${extra}`, { flag: "a" });
11608
11785
  resolve8(code);
11609
11786
  };
@@ -11625,7 +11802,7 @@ var engineRemoveImage = (engine = "docker", exec = realExec) => (tag) => {
11625
11802
  } catch {
11626
11803
  }
11627
11804
  };
11628
- var sandboxLogDir = (stateDir) => join27(stateDir, "sandbox-logs");
11805
+ var sandboxLogDir = (stateDir) => join28(stateDir, "sandbox-logs");
11629
11806
  async function buildSandboxImage(plan, deps) {
11630
11807
  const now = deps.now ?? (() => /* @__PURE__ */ new Date());
11631
11808
  const state = readSandboxState(deps.stateDir);
@@ -11634,21 +11811,21 @@ async function buildSandboxImage(plan, deps) {
11634
11811
  return { kind: "reused", tag: plan.tag };
11635
11812
  }
11636
11813
  const logDir = sandboxLogDir(deps.stateDir);
11637
- mkdirSync18(logDir, { recursive: true });
11638
- const logPath = join27(logDir, `${slug(plan.repo)}-${now().toISOString().replace(/[:.]/g, "-")}.log`);
11814
+ mkdirSync19(logDir, { recursive: true });
11815
+ const logPath = join28(logDir, `${slug(plan.repo)}-${now().toISOString().replace(/[:.]/g, "-")}.log`);
11639
11816
  const builtLayers = [];
11640
11817
  for (const layer of plan.layers) {
11641
11818
  if (deps.hasImage(layer.tag)) continue;
11642
- const ctx = join27(tmpdir3(), `crew-sandbox-${hash([layer.tag, process.pid, Date.now()])}`);
11643
- mkdirSync18(ctx, { recursive: true });
11819
+ const ctx = join28(tmpdir3(), `crew-sandbox-${hash([layer.tag, process.pid, Date.now()])}`);
11820
+ mkdirSync19(ctx, { recursive: true });
11644
11821
  try {
11645
- writeFileSync19(join27(ctx, "Dockerfile"), layer.dockerfile);
11822
+ writeFileSync20(join28(ctx, "Dockerfile"), layer.dockerfile);
11646
11823
  for (const [name, content] of Object.entries(layer.files)) {
11647
- mkdirSync18(dirname13(join27(ctx, name)), { recursive: true });
11648
- writeFileSync19(join27(ctx, name), content);
11824
+ mkdirSync19(dirname14(join28(ctx, name)), { recursive: true });
11825
+ writeFileSync20(join28(ctx, name), content);
11649
11826
  }
11650
- if (layer.caBundleFile) writeFileSync19(join27(ctx, layer.caBundleFile), (deps.caBundle ?? readHostCaBundle)());
11651
- const code = await deps.run(["build", "--tag", layer.tag, "--file", join27(ctx, "Dockerfile"), ctx], logPath);
11827
+ if (layer.caBundleFile) writeFileSync20(join28(ctx, layer.caBundleFile), (deps.caBundle ?? readHostCaBundle)());
11828
+ const code = await deps.run(["build", "--tag", layer.tag, "--file", join28(ctx, "Dockerfile"), ctx], logPath);
11652
11829
  if (code === BUILD_INTERRUPTED) return { kind: "interrupted", tag: plan.tag };
11653
11830
  if (code !== 0) {
11654
11831
  state[plan.repo] = { ...entry, failure: { tag: plan.tag, at: now().toISOString(), logPath } };
@@ -11657,7 +11834,7 @@ async function buildSandboxImage(plan, deps) {
11657
11834
  }
11658
11835
  builtLayers.push(layer.name);
11659
11836
  } finally {
11660
- rmSync14(ctx, { recursive: true, force: true });
11837
+ rmSync15(ctx, { recursive: true, force: true });
11661
11838
  }
11662
11839
  }
11663
11840
  const tags = [{ tag: plan.tag, builtAt: now().toISOString(), claude: plan.claude }, ...entry.tags.filter((t) => t.tag !== plan.tag)];
@@ -11760,8 +11937,8 @@ function expandSkillMarkers(text2, lookup2, opts = {}) {
11760
11937
  }
11761
11938
 
11762
11939
  // src/skills.ts
11763
- import { readFileSync as readFileSync28, readdirSync as readdirSync9, existsSync as existsSync27 } from "fs";
11764
- import { join as join29 } from "path";
11940
+ import { readFileSync as readFileSync29, readdirSync as readdirSync9, existsSync as existsSync28 } from "fs";
11941
+ import { join as join30 } from "path";
11765
11942
  import { parse as parseYaml2 } from "yaml";
11766
11943
  import { TablationClient as TablationClient3, StaleWriteError as StaleWriteError3, TablationApiError as TablationApiError2 } from "@tablation/client";
11767
11944
 
@@ -11777,7 +11954,7 @@ ${additions}`;
11777
11954
  }
11778
11955
 
11779
11956
  // src/persona-file.ts
11780
- import { readFileSync as readFileSync26 } from "fs";
11957
+ import { readFileSync as readFileSync27 } from "fs";
11781
11958
  import { parse as parseYaml } from "yaml";
11782
11959
  function parsePersonaText(text2, path) {
11783
11960
  const match = /^---\n([\s\S]*?)\n---\n([\s\S]*)$/.exec(text2);
@@ -11789,12 +11966,12 @@ function parsePersonaText(text2, path) {
11789
11966
  return { body: match[2], ...typeof meta.chat_enabled === "boolean" ? { chatEnabled: meta.chat_enabled } : {} };
11790
11967
  }
11791
11968
  function readPersonaFile(path) {
11792
- return parsePersonaText(readFileSync26(path, "utf8"), path);
11969
+ return parsePersonaText(readFileSync27(path, "utf8"), path);
11793
11970
  }
11794
11971
 
11795
11972
  // src/agents.ts
11796
- import { readFileSync as readFileSync27, existsSync as existsSync26 } from "fs";
11797
- import { join as join28 } from "path";
11973
+ import { readFileSync as readFileSync28, existsSync as existsSync27 } from "fs";
11974
+ import { join as join29 } from "path";
11798
11975
  import { TablationClient as TablationClient2, StaleWriteError as StaleWriteError2, TablationApiError } from "@tablation/client";
11799
11976
  var PERSONA_NAME = {
11800
11977
  dev: "Developer",
@@ -11808,17 +11985,17 @@ var CREW_AGENT_COLUMN = "agent_id";
11808
11985
  var AgentsSyncError = class extends Error {
11809
11986
  };
11810
11987
  function personaDefaultPrompt(promptsDir, role) {
11811
- const briefPath = join28(promptsDir, "personas", `lane-${role}.md`);
11812
- if (!existsSync26(briefPath)) throw new AgentsSyncError(`no brief at ${briefPath}`);
11988
+ const briefPath = join29(promptsDir, "personas", `lane-${role}.md`);
11989
+ if (!existsSync27(briefPath)) throw new AgentsSyncError(`no brief at ${briefPath}`);
11813
11990
  const brief = readPersonaFile(briefPath).body;
11814
11991
  if (SELF_CONTAINED_ROLES.has(role)) return brief;
11815
- const commonPath = join28(promptsDir, "personas", "common.md");
11816
- if (!existsSync26(commonPath)) return brief;
11817
- return `${readFileSync27(commonPath, "utf8")}${brief}`;
11992
+ const commonPath = join29(promptsDir, "personas", "common.md");
11993
+ if (!existsSync27(commonPath)) return brief;
11994
+ return `${readFileSync28(commonPath, "utf8")}${brief}`;
11818
11995
  }
11819
11996
  function personaChatEnabled(promptsDir, role) {
11820
- const briefPath = join28(promptsDir, "personas", `lane-${role}.md`);
11821
- return existsSync26(briefPath) ? readPersonaFile(briefPath).chatEnabled : void 0;
11997
+ const briefPath = join29(promptsDir, "personas", `lane-${role}.md`);
11998
+ return existsSync27(briefPath) ? readPersonaFile(briefPath).chatEnabled : void 0;
11822
11999
  }
11823
12000
  async function resolveAgentId(route2, role, opts) {
11824
12001
  const cached = route2.resolved?.agentPersonas?.[role]?.agentId;
@@ -12288,7 +12465,7 @@ function describeCrewLink(o) {
12288
12465
  var SkillSyncError = class extends Error {
12289
12466
  };
12290
12467
  function parseSkillFile(path) {
12291
- const text2 = readFileSync28(path, "utf8");
12468
+ const text2 = readFileSync29(path, "utf8");
12292
12469
  const match = /^---\n([\s\S]*?)\n---\n([\s\S]*)$/.exec(text2);
12293
12470
  if (!match) throw new SkillSyncError(`${path}: missing YAML frontmatter (expected a leading --- block)`);
12294
12471
  const frontmatter = match[1];
@@ -12315,9 +12492,9 @@ function parseSkillFile(path) {
12315
12492
  };
12316
12493
  }
12317
12494
  function listLocalSkills(promptsDir) {
12318
- const dir = join29(promptsDir, "skills");
12319
- if (!existsSync27(dir)) return [];
12320
- return readdirSync9(dir).filter((f) => f.endsWith(".md")).map((f) => parseSkillFile(join29(dir, f)));
12495
+ const dir = join30(promptsDir, "skills");
12496
+ if (!existsSync28(dir)) return [];
12497
+ return readdirSync9(dir).filter((f) => f.endsWith(".md")).map((f) => parseSkillFile(join30(dir, f)));
12321
12498
  }
12322
12499
  function personaColumn(model) {
12323
12500
  for (const c of ["persona_id", "persona"]) if (model.fields?.some((f) => f.columnName === c)) return c;
@@ -12551,10 +12728,10 @@ function skillMarkerWarnings(promptsDir, personaPrompts) {
12551
12728
 
12552
12729
  // src/runner.ts
12553
12730
  import { spawn as spawn5, execFile, execFileSync as execFileSync9 } from "child_process";
12554
- import { mkdtempSync, mkdirSync as mkdirSync19, writeFileSync as writeFileSync20, rmSync as rmSync15 } from "fs";
12731
+ import { mkdtempSync, mkdirSync as mkdirSync20, writeFileSync as writeFileSync21, rmSync as rmSync16 } from "fs";
12555
12732
  import { createHash as createHash5 } from "crypto";
12556
12733
  import { tmpdir as tmpdir4 } from "os";
12557
- import { basename as basename8, dirname as dirname14, join as join30 } from "path";
12734
+ import { basename as basename8, dirname as dirname15, join as join31 } from "path";
12558
12735
  import { promisify } from "util";
12559
12736
 
12560
12737
  // src/run-limit.ts
@@ -12689,6 +12866,12 @@ var SandboxRunner = class {
12689
12866
  if (/[\r\n]/.test(v)) throw new Error(`the sandbox environment variable ${k} contains a newline, which the sandbox gateway refuses`);
12690
12867
  }
12691
12868
  const createEnv = { ...process.env, ...plan.setEnv };
12869
+ for (const [k, v] of Object.entries(plan.sandboxRepoEnv ?? {})) {
12870
+ if (k in plan.setEnv) continue;
12871
+ if (/[\r\n]/.test(v)) throw new Error(`the repository environment variable ${k} contains a newline, which the sandbox gateway refuses`);
12872
+ createEnv[k] = v;
12873
+ if (!secretKeys.includes(k)) secretKeys.push(k);
12874
+ }
12692
12875
  if (cfg.forgeTokenVar && o.env[cfg.forgeTokenVar] !== void 0) createEnv[cfg.forgeTokenVar] = o.env[cfg.forgeTokenVar];
12693
12876
  let policyFile = cfg.policy;
12694
12877
  let generated;
@@ -12699,8 +12882,8 @@ var SandboxRunner = class {
12699
12882
  throw new Error(`cannot generate the sandbox policy: ${e.message}`);
12700
12883
  }
12701
12884
  policyFile = policyPathFor(plan.streamPath);
12702
- mkdirSync19(dirname14(policyFile), { recursive: true });
12703
- writeFileSync20(policyFile, generated.yaml, { mode: 384 });
12885
+ mkdirSync20(dirname15(policyFile), { recursive: true });
12886
+ writeFileSync21(policyFile, generated.yaml, { mode: 384 });
12704
12887
  }
12705
12888
  const create2 = ["sandbox", "create", "--name", name, "--detach"];
12706
12889
  if (policyFile) create2.push("--policy", policyFile);
@@ -12749,13 +12932,13 @@ var SandboxRunner = class {
12749
12932
  const harness = cfg.agentBin ?? basename8(plan.bin);
12750
12933
  const viaUpload = Buffer.byteLength(plan.prompt) > SANDBOX_STDIN_LIMIT;
12751
12934
  if (viaUpload) {
12752
- const tmp = mkdtempSync(join30(tmpdir4(), "crew-prompt-"));
12935
+ const tmp = mkdtempSync(join31(tmpdir4(), "crew-prompt-"));
12753
12936
  try {
12754
- const file = join30(tmp, "prompt.txt");
12755
- writeFileSync20(file, plan.prompt, { mode: 384 });
12937
+ const file = join31(tmp, "prompt.txt");
12938
+ writeFileSync21(file, plan.prompt, { mode: 384 });
12756
12939
  await this.os(["sandbox", "upload", name, file, SANDBOX_PROMPT_PATH]);
12757
12940
  } finally {
12758
- rmSync15(tmp, { recursive: true, force: true });
12941
+ rmSync16(tmp, { recursive: true, force: true });
12759
12942
  }
12760
12943
  }
12761
12944
  const withStubs = `${sandboxEnvExports()}PATH=${shQuote2(SANDBOX_STUB_DIR)}:"$PATH"; export PATH; `;
@@ -12950,7 +13133,7 @@ var ALLOWANCE_REFUSAL_MARKER = "AI_ALLOWANCE_EXCEEDED";
12950
13133
  function streamShowsAllowanceRefusal(streamPath) {
12951
13134
  let raw;
12952
13135
  try {
12953
- raw = readFileSync29(streamPath, "utf8");
13136
+ raw = readFileSync30(streamPath, "utf8");
12954
13137
  } catch {
12955
13138
  return false;
12956
13139
  }
@@ -12973,7 +13156,7 @@ function streamShowsAllowanceRefusal(streamPath) {
12973
13156
  }
12974
13157
  return false;
12975
13158
  }
12976
- var digestPathFor = (stateDir, routeLabel, role, runId) => join31(stateDir, `digest-${routeLabel}-${role}${runId ? `-${runId}` : ""}.md`);
13159
+ var digestPathFor = (stateDir, routeLabel, role, runId) => join32(stateDir, `digest-${routeLabel}-${role}${runId ? `-${runId}` : ""}.md`);
12977
13160
  function codeBridgeFor(o, harness) {
12978
13161
  if (!o.ticket) return void 0;
12979
13162
  const number = /(\d+)$/.exec(o.ticket)?.[1];
@@ -13000,7 +13183,7 @@ function codeBridgeFor(o, harness) {
13000
13183
  "--clone",
13001
13184
  o.ship.sandbox?.workDir ?? DEFAULT_SANDBOX_WORKDIR,
13002
13185
  "--state-dir",
13003
- dirname15(SANDBOX_INTEL_DIR),
13186
+ dirname16(SANDBOX_INTEL_DIR),
13004
13187
  "--ticket",
13005
13188
  number,
13006
13189
  ...seed ? ["--seed-cache", seed] : []
@@ -13013,32 +13196,32 @@ function codeBridgeFor(o, harness) {
13013
13196
  bridge.settingsFile = `${SANDBOX_INTEL_DIR}/gemini-settings.json`;
13014
13197
  bridge.files = [{ path: bridge.settingsFile, content: text2 }];
13015
13198
  } else {
13016
- const file = join31(intelDir(o.stateDir, o.route.route, number), "gemini-settings.json");
13017
- mkdirSync20(dirname15(file), { recursive: true });
13018
- writeFileSync21(file, text2);
13199
+ const file = join32(intelDir(o.stateDir, o.route.route, number), "gemini-settings.json");
13200
+ mkdirSync21(dirname16(file), { recursive: true });
13201
+ writeFileSync22(file, text2);
13019
13202
  bridge.settingsFile = file;
13020
13203
  }
13021
13204
  }
13022
13205
  return bridge;
13023
13206
  }
13024
13207
  function planAgentRun(o) {
13025
- const briefPath = join31(o.route.promptsDir, "personas", `lane-${o.role}.md`);
13026
- if (!existsSync28(briefPath)) {
13208
+ const briefPath = join32(o.route.promptsDir, "personas", `lane-${o.role}.md`);
13209
+ if (!existsSync29(briefPath)) {
13027
13210
  throw new AgentError(`no brief at ${briefPath} \u2014 refusing to run an unscoped session`);
13028
13211
  }
13029
- const commonPath = join31(o.route.promptsDir, "personas", "common.md");
13030
- const usesCommon = !SELF_CONTAINED_ROLES.has(o.role) && existsSync28(commonPath);
13212
+ const commonPath = join32(o.route.promptsDir, "personas", "common.md");
13213
+ const usesCommon = !SELF_CONTAINED_ROLES.has(o.role) && existsSync29(commonPath);
13031
13214
  const now = o.now ?? (() => Date.now());
13032
13215
  const routeLabel = routeSlug(o.route.route);
13033
13216
  const ownDigest = o.runId ? digestPathFor(o.stateDir, routeLabel, o.role, o.runId) : void 0;
13034
- const digestPath2 = ownDigest && existsSync28(ownDigest) ? ownDigest : digestPathFor(o.stateDir, routeLabel, o.role);
13217
+ const digestPath2 = ownDigest && existsSync29(ownDigest) ? ownDigest : digestPathFor(o.stateDir, routeLabel, o.role);
13035
13218
  let digest;
13036
13219
  let ageSeconds;
13037
- if (existsSync28(digestPath2)) {
13220
+ if (existsSync29(digestPath2)) {
13038
13221
  ageSeconds = Math.floor((now() - statSync9(digestPath2).mtimeMs) / 1e3);
13039
- if (ageSeconds <= DIGEST_MAX_AGE_SECONDS) digest = readFileSync29(digestPath2, "utf8");
13222
+ if (ageSeconds <= DIGEST_MAX_AGE_SECONDS) digest = readFileSync30(digestPath2, "utf8");
13040
13223
  }
13041
- const common = usesCommon ? readFileSync29(commonPath, "utf8") : "";
13224
+ const common = usesCommon ? readFileSync30(commonPath, "utf8") : "";
13042
13225
  const brief = readPersonaFile(briefPath).body;
13043
13226
  const effectiveCommon = o.divergedPrompt ? "" : common;
13044
13227
  const effectiveBrief = appendAdditions(o.divergedPrompt ?? brief, o.personaAdditions);
@@ -13062,7 +13245,7 @@ function planAgentRun(o) {
13062
13245
  digest
13063
13246
  });
13064
13247
  const promptSha = createHash6("sha256").update(expanded.text).digest("hex");
13065
- const streamsDir = join31(o.stateDir, "streams");
13248
+ const streamsDir = join32(o.stateDir, "streams");
13066
13249
  const base = `${routeLabel}-${o.role}-${o.cycle}${o.runId ? `-${o.runId}` : ""}`;
13067
13250
  const seat = resolveSeat(o.ship, o.route, o.role, o.agentPersona ?? (o.agentModel ? { model: o.agentModel } : {}), o.repo);
13068
13251
  const { model } = seat;
@@ -13082,6 +13265,7 @@ function planAgentRun(o) {
13082
13265
  const code = codeBridgeFor(o, adapter.harness);
13083
13266
  const sandboxLsp = o.ship.runner === "sandbox" && adapter.harness === "claude" ? sandboxLspPluginFor(o.route, o.repo) : void 0;
13084
13267
  const sandboxOrigin = o.ship.runner === "sandbox" ? sandboxOriginFor(o.route, o.repo) : void 0;
13268
+ const repoEnv = o.ship.runner === "sandbox" && o.repo ? envForRepository(readRepositoryEnv(o.stateDir), { repoRowId: repoIdForName(o.route, o.repo), remote: sandboxOrigin }) : {};
13085
13269
  const sandboxChoice = o.ship.runner === "sandbox" ? sandboxImageOf(o.route, o.repo, o.stateDir, o.repoContract) : void 0;
13086
13270
  const sandboxImage = sandboxChoice?.image;
13087
13271
  const sandboxFiles = [...code?.files ?? [], ...sandboxLsp?.files ?? []];
@@ -13101,6 +13285,7 @@ function planAgentRun(o) {
13101
13285
  apiKey: o.apiKey,
13102
13286
  userAgent: o.ship.userAgent,
13103
13287
  agentId: o.resolvedAgentId,
13288
+ ...o.route.resolved.models?.crew && o.route.resolved.seats?.[o.role] ? { actor: { table: o.route.resolved.models.crew, recordId: o.route.resolved.seats[o.role] } } : {},
13104
13289
  ...o.route.resolved.models?.issues ? { tickets: {
13105
13290
  issuesModelId: o.route.resolved.models.issues,
13106
13291
  keyColumn: columns.key,
@@ -13138,6 +13323,7 @@ function planAgentRun(o) {
13138
13323
  runner: "sandbox",
13139
13324
  ...o.ship.sandbox ? { sandboxConfig: o.ship.sandbox } : {},
13140
13325
  ...sandboxOrigin ? { sandboxOrigin } : {},
13326
+ ...Object.keys(repoEnv).length ? { sandboxRepoEnv: repoEnv } : {},
13141
13327
  ...sandboxImage ? { sandboxImage } : {},
13142
13328
  ...sandboxChoice ? { sandboxImageReason: sandboxChoice.reason } : {},
13143
13329
  sandboxPolicy: sandboxPolicyInputFor(o.route, toolchain, { harnessBin: invocation.bin, repo: o.repo, sandbox: o.ship.sandbox, contract: o.repoContract }),
@@ -13167,8 +13353,8 @@ function planAgentRun(o) {
13167
13353
  digestAttached: digest !== void 0,
13168
13354
  digestAgeSeconds: ageSeconds,
13169
13355
  model,
13170
- streamPath: join31(streamsDir, `${base}.jsonl`),
13171
- eventsPath: join31(streamsDir, `${base}.events.jsonl`),
13356
+ streamPath: join32(streamsDir, `${base}.jsonl`),
13357
+ eventsPath: join32(streamsDir, `${base}.events.jsonl`),
13172
13358
  ticket: o.ticket,
13173
13359
  ticketRecordId: o.ticketRecordId ?? null,
13174
13360
  repo: o.repo ?? null,
@@ -13197,10 +13383,18 @@ function describePlan(p) {
13197
13383
  `stream: ${p.streamPath}`
13198
13384
  ].join("\n");
13199
13385
  }
13386
+ function updateSidecar(streamPath, patch2) {
13387
+ const sc = readRunSidecar(streamPath);
13388
+ if (!sc) return;
13389
+ try {
13390
+ writeFileSync22(pidPathFor(streamPath), JSON.stringify({ ...sc, ...patch2 }));
13391
+ } catch {
13392
+ }
13393
+ }
13200
13394
  var pidPathFor = (streamPath) => `${streamPath}.pid`;
13201
13395
  function readRunSidecar(streamPath) {
13202
13396
  try {
13203
- const sc = JSON.parse(readFileSync29(pidPathFor(streamPath), "utf8"));
13397
+ const sc = JSON.parse(readFileSync30(pidPathFor(streamPath), "utf8"));
13204
13398
  return typeof sc.pid === "number" && typeof sc.spawnedAt === "string" && typeof sc.role === "string" ? sc : null;
13205
13399
  } catch {
13206
13400
  return null;
@@ -13248,7 +13442,7 @@ async function killForDeadline(kill, pid, emit, role, ticket, spawnedAt, limitMi
13248
13442
  var withoutKey = ({ apiKey: _apiKey, ...rest }) => rest;
13249
13443
  function openSink(path) {
13250
13444
  try {
13251
- mkdirSync20(dirname15(path), { recursive: true });
13445
+ mkdirSync21(dirname16(path), { recursive: true });
13252
13446
  return createWriteStream(path, { flags: "a" });
13253
13447
  } catch {
13254
13448
  return void 0;
@@ -13291,6 +13485,8 @@ var FileTail = class {
13291
13485
  var TAIL_POLL_MS = 200;
13292
13486
  var RunObserver = class {
13293
13487
  cycles = [];
13488
+ /** CREW-3116: sends the cycles to the run's Agent Log row as they are mapped. */
13489
+ reporter;
13294
13490
  attribution = new TicketAttributionTracker();
13295
13491
  /** Hand-off writes and their outcomes, to tell a run whose hand-off never landed (CREW-2363). */
13296
13492
  handoff = new HandoffTranscriptTracker();
@@ -13324,6 +13520,11 @@ var RunObserver = class {
13324
13520
  this.liveTicket = id.ticket ?? void 0;
13325
13521
  this.mapper = adapter.createStreamMapper?.() ?? { map: (p) => adapter.mapStreamLine(p), flush: () => [] };
13326
13522
  }
13523
+ /** Hands the live reporter every cycle mapped so far, then each new one as it arrives. */
13524
+ attachReporter(r) {
13525
+ this.reporter = r;
13526
+ for (const c of this.cycles) r.add(c);
13527
+ }
13327
13528
  feed(text2) {
13328
13529
  this.buf += text2;
13329
13530
  const lines2 = this.buf.split("\n");
@@ -13405,7 +13606,7 @@ var RunObserver = class {
13405
13606
  turnText += `${ev.text}
13406
13607
  `;
13407
13608
  const cycleIndex = this.cycles.length;
13408
- this.cycles.push({
13609
+ const cycle = {
13409
13610
  cycleIndex,
13410
13611
  occurredAt: e.at,
13411
13612
  thinking: ev.text,
@@ -13416,7 +13617,9 @@ var RunObserver = class {
13416
13617
  // for the same column. A `thought` cycle stays untagged, same
13417
13618
  // as before this change.
13418
13619
  ...ev.kind === "text" ? { role: "assistant" } : {}
13419
- });
13620
+ };
13621
+ this.cycles.push(cycle);
13622
+ this.reporter?.add(cycle);
13420
13623
  if (!this.muted) {
13421
13624
  this.eventsSink?.write(`${JSON.stringify({
13422
13625
  ...e,
@@ -13434,7 +13637,7 @@ var RunObserver = class {
13434
13637
  };
13435
13638
  function writeRunMeta(id, startedAt, liveTicket, extra) {
13436
13639
  try {
13437
- writeFileSync21(`${id.streamPath}.meta.json`, JSON.stringify({
13640
+ writeFileSync22(`${id.streamPath}.meta.json`, JSON.stringify({
13438
13641
  route: id.route,
13439
13642
  role: id.role,
13440
13643
  hint: id.ticket,
@@ -13541,6 +13744,7 @@ async function finishRun(id, obs, emit, startedAt, end, agentLogKey, hintMoved)
13541
13744
  // CREW-2980: under `auth: workspace` the endpoint's rows are the accounting; the run row
13542
13745
  // keeps turns only, and `reportAgentRun` sums those rows into the ticket counters.
13543
13746
  ...id.agentLogRowId ? { rowId: id.agentLogRowId } : {},
13747
+ ...obs.reporter ? { cyclesPosted: obs.reporter.posted } : {},
13544
13748
  ...id.workspaceRunId ? { runId: id.workspaceRunId } : {
13545
13749
  tokensIn: result?.inputTokens,
13546
13750
  tokensOut: result?.outputTokens,
@@ -13626,7 +13830,7 @@ function spawnAgent(plan, emit, hintMoved) {
13626
13830
  const id = identityOf(plan, adapter.harness);
13627
13831
  let streamFd;
13628
13832
  try {
13629
- mkdirSync20(dirname15(plan.streamPath), { recursive: true });
13833
+ mkdirSync21(dirname16(plan.streamPath), { recursive: true });
13630
13834
  streamFd = openSync4(plan.streamPath, "a");
13631
13835
  } catch (e) {
13632
13836
  void endSink(eventsSink);
@@ -13685,11 +13889,12 @@ function spawnAgent(plan, emit, hintMoved) {
13685
13889
  ...plan.workspaceRunId ? { workspaceRunId: plan.workspaceRunId } : {}
13686
13890
  };
13687
13891
  try {
13688
- writeFileSync21(pidPathFor(plan.streamPath), JSON.stringify(sidecar));
13892
+ writeFileSync22(pidPathFor(plan.streamPath), JSON.stringify(sidecar));
13689
13893
  } catch {
13690
13894
  }
13691
13895
  }
13692
- const startedRow = plan.workspaceRunId && plan.agentLog ? startAgentRunRow(plan.agentLog, {
13896
+ const obs = new RunObserver(id, adapter, eventsSink, emit.cycle);
13897
+ const startedRow = plan.agentLog ? startAgentRunRow(plan.agentLog, {
13693
13898
  runId: plan.workspaceRunId,
13694
13899
  ticketReference: plan.ticket ?? void 0,
13695
13900
  startedAt,
@@ -13697,19 +13902,20 @@ function spawnAgent(plan, emit, hintMoved) {
13697
13902
  harness: id.harness,
13698
13903
  provider: id.provider,
13699
13904
  promptVersion: plan.promptVersion,
13700
- promptSha: plan.promptSha
13701
- }).then((rowId) => {
13702
- if (!rowId) return;
13703
- id.agentLogRowId = rowId;
13704
- const sc = readRunSidecar(plan.streamPath);
13705
- if (sc) {
13706
- try {
13707
- writeFileSync21(pidPathFor(plan.streamPath), JSON.stringify({ ...sc, agentLogRowId: rowId }));
13708
- } catch {
13709
- }
13905
+ promptSha: plan.promptSha,
13906
+ actorLabel: plan.role
13907
+ }).then((row) => {
13908
+ if (!row) return;
13909
+ id.agentLogRowId = row.id;
13910
+ updateSidecar(plan.streamPath, { agentLogRowId: row.id });
13911
+ if (row.live && plan.agentLog) {
13912
+ const reporter = new LiveRunReporter(plan.agentLog, row.id, {
13913
+ onPosted: (n) => updateSidecar(plan.streamPath, { cyclesPosted: n })
13914
+ });
13915
+ obs.attachReporter(reporter);
13916
+ reporter.start();
13710
13917
  }
13711
13918
  }) : Promise.resolve();
13712
- const obs = new RunObserver(id, adapter, eventsSink, emit.cycle);
13713
13919
  const meta = { pid: child.pid ?? null, ...deadline ? { deadline } : {} };
13714
13920
  obs.onClaim = () => writeRunMeta(id, startedAt, obs.liveTicket, meta);
13715
13921
  if (child.pid !== void 0) writeRunMeta(id, startedAt, obs.liveTicket, meta);
@@ -13741,6 +13947,7 @@ function spawnAgent(plan, emit, hintMoved) {
13741
13947
  killed = { limitMinutes: plan.maxRunMinutes ?? 0, elapsedMs: Date.now() - Date.parse(spawnedAt) };
13742
13948
  }
13743
13949
  await startedRow;
13950
+ await obs.reporter?.stop();
13744
13951
  const { ms: ms3, handoffPending } = await finishRun(
13745
13952
  id,
13746
13953
  obs,
@@ -13770,6 +13977,13 @@ async function reattachRun(streamPath, sc, emit, o = {}) {
13770
13977
  obs.muted = true;
13771
13978
  obs.feed(tail3.poll());
13772
13979
  obs.muted = false;
13980
+ if (sc.agentLogRowId && sc.agentLog && o.agentLogKey) {
13981
+ const reporter = new LiveRunReporter({ ...sc.agentLog, apiKey: o.agentLogKey }, sc.agentLogRowId, {
13982
+ onPosted: (n) => updateSidecar(streamPath, { cyclesPosted: n })
13983
+ }, sc.cyclesPosted ?? 0);
13984
+ obs.attachReporter(reporter);
13985
+ reporter.start();
13986
+ }
13773
13987
  const runner = runnerOfSidecar(sc);
13774
13988
  const adopted = isAlive(sc);
13775
13989
  let killed;
@@ -13787,6 +14001,7 @@ async function reattachRun(streamPath, sc, emit, o = {}) {
13787
14001
  }
13788
14002
  obs.feed(tail3.poll());
13789
14003
  obs.end();
14004
+ await obs.reporter?.stop();
13790
14005
  await endSink(eventsSink);
13791
14006
  await runner.release(runner.reattach(sc), emit);
13792
14007
  const interrupted = killed ? WALL_CLOCK_REASON : obs.sawResult ? void 0 : adopted ? "no-result" : "daemon-exit";
@@ -13820,21 +14035,21 @@ var pidAlive = (pid) => {
13820
14035
  };
13821
14036
  function runFinished(streamPath) {
13822
14037
  const path = `${streamPath}.meta.json`;
13823
- if (!existsSync29(path)) return false;
14038
+ if (!existsSync30(path)) return false;
13824
14039
  try {
13825
- return JSON.parse(readFileSync30(path, "utf8")).running !== true;
14040
+ return JSON.parse(readFileSync31(path, "utf8")).running !== true;
13826
14041
  } catch {
13827
14042
  return true;
13828
14043
  }
13829
14044
  }
13830
14045
  function orphanedStreams(o) {
13831
- const dir = join32(o.stateDir, "streams");
13832
- if (!existsSync29(dir)) return [];
14046
+ const dir = join33(o.stateDir, "streams");
14047
+ if (!existsSync30(dir)) return [];
13833
14048
  const ownerAlive = o.isOwnerAlive ?? pidAlive;
13834
14049
  const out = [];
13835
14050
  for (const name of readdirSync10(dir)) {
13836
14051
  if (!name.endsWith(".jsonl") || name.endsWith(".events.jsonl")) continue;
13837
- const streamPath = join32(dir, name);
14052
+ const streamPath = join33(dir, name);
13838
14053
  if (runFinished(streamPath)) continue;
13839
14054
  const sidecar = readRunSidecar(streamPath);
13840
14055
  if (!sidecar || sidecar.route !== o.routeLabel) continue;
@@ -13887,15 +14102,15 @@ async function reconcileRuns(o) {
13887
14102
  }
13888
14103
 
13889
14104
  // src/live-runs.ts
13890
- import { existsSync as existsSync30, readdirSync as readdirSync11, statSync as statSync10 } from "fs";
13891
- import { join as join33 } from "path";
14105
+ import { existsSync as existsSync31, readdirSync as readdirSync11, statSync as statSync10 } from "fs";
14106
+ import { join as join34 } from "path";
13892
14107
  function liveRuns(stateDir, isAlive = runIsAlive) {
13893
- const dir = join33(stateDir, "streams");
13894
- if (!existsSync30(dir)) return [];
14108
+ const dir = join34(stateDir, "streams");
14109
+ if (!existsSync31(dir)) return [];
13895
14110
  const out = [];
13896
14111
  for (const name of readdirSync11(dir)) {
13897
14112
  if (!name.endsWith(".jsonl") || name.endsWith(".events.jsonl")) continue;
13898
- const streamPath = join33(dir, name);
14113
+ const streamPath = join34(dir, name);
13899
14114
  if (runFinished(streamPath)) continue;
13900
14115
  const sidecar = readRunSidecar(streamPath);
13901
14116
  if (!sidecar || !isAlive(sidecar)) continue;
@@ -13905,12 +14120,12 @@ function liveRuns(stateDir, isAlive = runIsAlive) {
13905
14120
  }
13906
14121
  function runActivity(stateDir, isAlive = runIsAlive) {
13907
14122
  const activeRuns = liveRuns(stateDir, isAlive).length;
13908
- const dir = join33(stateDir, "streams");
14123
+ const dir = join34(stateDir, "streams");
13909
14124
  let newest = 0;
13910
- if (existsSync30(dir)) {
14125
+ if (existsSync31(dir)) {
13911
14126
  for (const name of readdirSync11(dir)) {
13912
14127
  if (!name.endsWith(".jsonl") || name.endsWith(".events.jsonl")) continue;
13913
- const streamPath = join33(dir, name);
14128
+ const streamPath = join34(dir, name);
13914
14129
  if (!runFinished(streamPath)) continue;
13915
14130
  try {
13916
14131
  newest = Math.max(newest, statSync10(`${streamPath}.meta.json`).mtimeMs);
@@ -14005,7 +14220,7 @@ function realDeprovisionDeps(cfg, emit, crewHome, getStore) {
14005
14220
  if (host === "windows") return [];
14006
14221
  const ctx = installContext();
14007
14222
  const systemd = detectSystemd();
14008
- return ["run", "release", "passengers"].flatMap((job) => planInstall(cfg.ship, crewHome, host, systemd, job, ctx).unitPaths).filter((p) => existsSync31(p));
14223
+ return ["run", "release", "passengers"].flatMap((job) => planInstall(cfg.ship, crewHome, host, systemd, job, ctx).unitPaths).filter((p) => existsSync32(p));
14009
14224
  };
14010
14225
  return {
14011
14226
  liveRuns: () => liveRuns(stateDir).map((r) => ({ role: r.role, route: r.route, pid: r.pid, ticketRecordId: r.ticketRecordId ?? void 0, streamPath: r.streamPath })),
@@ -14061,6 +14276,9 @@ function realDeprovisionDeps(cfg, emit, crewHome, getStore) {
14061
14276
  },
14062
14277
  forgeHosts,
14063
14278
  eraseForgeToken: (host) => eraseForgeToken(cfg.ship.forges, host, stateDir),
14279
+ eraseRepositoryEnv: () => {
14280
+ eraseRepositoryEnv(stateDir);
14281
+ },
14064
14282
  labeled: labeledDocker,
14065
14283
  removeVolume: (name) => {
14066
14284
  docker(["volume", "rm", "-f", name]);
@@ -14070,8 +14288,9 @@ function realDeprovisionDeps(cfg, emit, crewHome, getStore) {
14070
14288
  },
14071
14289
  remaining() {
14072
14290
  const left = [];
14073
- if (existsSync31(cfg.configFile)) left.push(`config ${cfg.configFile}`);
14291
+ if (existsSync32(cfg.configFile)) left.push(`config ${cfg.configFile}`);
14074
14292
  for (const h of forgeHosts()) if (hasForgeToken(cfg.ship.forges, h, stateDir)) left.push(`forge token for ${h}`);
14293
+ if (hasRepositoryEnv(stateDir)) left.push("repository environment");
14075
14294
  try {
14076
14295
  for (const k of readdirSync12(keysDir(stateDir))) left.push(`seat key ${k}`);
14077
14296
  } catch {
@@ -14894,9 +15113,9 @@ function managedGitIdentityWarnings(kind, identity) {
14894
15113
 
14895
15114
  // src/selftest.ts
14896
15115
  import { spawn as spawn7 } from "child_process";
14897
- import { existsSync as existsSync32, mkdirSync as mkdirSync21, mkdtempSync as mkdtempSync2, readFileSync as readFileSync31, rmSync as rmSync16, writeFileSync as writeFileSync22 } from "fs";
15116
+ import { existsSync as existsSync33, mkdirSync as mkdirSync22, mkdtempSync as mkdtempSync2, readFileSync as readFileSync32, rmSync as rmSync17, writeFileSync as writeFileSync23 } from "fs";
14898
15117
  import { tmpdir as tmpdir5 } from "os";
14899
- import { join as join34 } from "path";
15118
+ import { join as join35 } from "path";
14900
15119
  var SELFTEST_TIMEOUT_MS = 12e4;
14901
15120
  var KEY_VAR = "CREW_API_KEY";
14902
15121
  var SELFTEST_PROMPT = "This is a read-only connectivity check. Use the tracker MCP tool to read this workspace (the workspaces find-one tool, using the workspace id below) and reply with the workspace's name alone, on one line. Do not write anything, do not create files, and do not use any other tool.\n\nWorkspace id: ";
@@ -15062,7 +15281,7 @@ async function runSelftest(i, deps = realDeps) {
15062
15281
  ...adapter.runEnv(spec),
15063
15282
  [KEY_VAR]: i.apiKey
15064
15283
  };
15065
- const cwd = mkdtempSync2(join34(tmpdir5(), "crew-selftest-"));
15284
+ const cwd = mkdtempSync2(join35(tmpdir5(), "crew-selftest-"));
15066
15285
  try {
15067
15286
  const run4 = await deps.run({
15068
15287
  bin: invocation.bin,
@@ -15084,7 +15303,7 @@ async function runSelftest(i, deps = realDeps) {
15084
15303
  return finish({ ok: false, failure, detail, ...usage2 });
15085
15304
  } finally {
15086
15305
  try {
15087
- rmSync16(cwd, { recursive: true, force: true });
15306
+ rmSync17(cwd, { recursive: true, force: true });
15088
15307
  } catch {
15089
15308
  }
15090
15309
  }
@@ -15095,11 +15314,11 @@ function formatResult(r) {
15095
15314
  const secs = `${(r.ms / 1e3).toFixed(1)}s`;
15096
15315
  return r.ok ? `${r.toolchain}: PASS ${r.detail} (${secs}${tok})` : `${r.toolchain}: FAIL ${r.failure} \u2014 ${r.detail} (${secs})`;
15097
15316
  }
15098
- var fileFor2 = (stateDir) => join34(stateDir, "selftest.json");
15317
+ var fileFor2 = (stateDir) => join35(stateDir, "selftest.json");
15099
15318
  function readSelftest(stateDir) {
15100
15319
  try {
15101
15320
  const p = fileFor2(stateDir);
15102
- return existsSync32(p) ? JSON.parse(readFileSync31(p, "utf8")) : {};
15321
+ return existsSync33(p) ? JSON.parse(readFileSync32(p, "utf8")) : {};
15103
15322
  } catch {
15104
15323
  return {};
15105
15324
  }
@@ -15107,8 +15326,8 @@ function readSelftest(stateDir) {
15107
15326
  function recordSelftest(stateDir, results) {
15108
15327
  const all = readSelftest(stateDir);
15109
15328
  for (const r of results) all[r.toolchain] = r;
15110
- mkdirSync21(stateDir, { recursive: true });
15111
- writeFileSync22(fileFor2(stateDir), `${JSON.stringify(all, null, 2)}
15329
+ mkdirSync22(stateDir, { recursive: true });
15330
+ writeFileSync23(fileFor2(stateDir), `${JSON.stringify(all, null, 2)}
15112
15331
  `);
15113
15332
  }
15114
15333
  function doctorSelftestLines(stored, toolchains) {
@@ -15120,7 +15339,7 @@ function doctorSelftestLines(stored, toolchains) {
15120
15339
  }
15121
15340
 
15122
15341
  // src/cli.ts
15123
- import { resolve as resolve7, dirname as dirname36, join as join58, basename as basename16 } from "path";
15342
+ import { resolve as resolve7, dirname as dirname37, join as join60, basename as basename16 } from "path";
15124
15343
  import { fileURLToPath as fileURLToPath2 } from "url";
15125
15344
  import { hostname as hostname5, homedir as homedir11, userInfo as userInfo2 } from "os";
15126
15345
  import { spawnSync as spawnSync13 } from "child_process";
@@ -15319,14 +15538,14 @@ function rosterMarkdown(roster, meId) {
15319
15538
  }
15320
15539
 
15321
15540
  // src/connect-resume.ts
15322
- import { mkdirSync as mkdirSync22, readFileSync as readFileSync32, rmSync as rmSync17, writeFileSync as writeFileSync23 } from "fs";
15323
- import { dirname as dirname16, join as join35 } from "path";
15541
+ import { mkdirSync as mkdirSync23, readFileSync as readFileSync33, rmSync as rmSync18, writeFileSync as writeFileSync24 } from "fs";
15542
+ import { dirname as dirname17, join as join36 } from "path";
15324
15543
  function lastSessionFile(stateDir) {
15325
- return join35(stateDir, "connect-session.json");
15544
+ return join36(stateDir, "connect-session.json");
15326
15545
  }
15327
15546
  function readPointers(stateDir) {
15328
15547
  try {
15329
- const parsed = JSON.parse(readFileSync32(lastSessionFile(stateDir), "utf8"));
15548
+ const parsed = JSON.parse(readFileSync33(lastSessionFile(stateDir), "utf8"));
15330
15549
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
15331
15550
  const out = {};
15332
15551
  for (const [host, v] of Object.entries(parsed)) {
@@ -15340,8 +15559,8 @@ function readPointers(stateDir) {
15340
15559
  }
15341
15560
  function writePointers(stateDir, pointers) {
15342
15561
  const file = lastSessionFile(stateDir);
15343
- mkdirSync22(dirname16(file), { recursive: true });
15344
- writeFileSync23(file, `${JSON.stringify(pointers, null, 2)}
15562
+ mkdirSync23(dirname17(file), { recursive: true });
15563
+ writeFileSync24(file, `${JSON.stringify(pointers, null, 2)}
15345
15564
  `, { mode: 384 });
15346
15565
  }
15347
15566
  function rememberSession(stateDir, host, workspaceSlug) {
@@ -15358,7 +15577,7 @@ function forgetWorkspace(stateDir, host, workspaceSlug) {
15358
15577
  const { [host]: _old, ...rest } = all;
15359
15578
  const next = left.length ? { ...rest, [host]: left } : rest;
15360
15579
  if (Object.keys(next).length) writePointers(stateDir, next);
15361
- else rmSync17(lastSessionFile(stateDir), { force: true });
15580
+ else rmSync18(lastSessionFile(stateDir), { force: true });
15362
15581
  } catch {
15363
15582
  }
15364
15583
  }
@@ -15398,7 +15617,7 @@ function forgetSession(stateDir, host) {
15398
15617
  try {
15399
15618
  const { [host]: _gone, ...rest } = readPointers(stateDir);
15400
15619
  if (Object.keys(rest).length) writePointers(stateDir, rest);
15401
- else rmSync17(lastSessionFile(stateDir), { force: true });
15620
+ else rmSync18(lastSessionFile(stateDir), { force: true });
15402
15621
  } catch {
15403
15622
  }
15404
15623
  }
@@ -15426,15 +15645,15 @@ async function signOutSessions(o) {
15426
15645
  }
15427
15646
 
15428
15647
  // src/reset.ts
15429
- import { existsSync as existsSync33, mkdirSync as mkdirSync23, readFileSync as readFileSync33, readdirSync as readdirSync13, rmSync as rmSync18, statSync as statSync11, writeFileSync as writeFileSync24 } from "fs";
15430
- import { dirname as dirname17, join as join36 } from "path";
15648
+ import { existsSync as existsSync34, mkdirSync as mkdirSync24, readFileSync as readFileSync34, readdirSync as readdirSync13, rmSync as rmSync19, statSync as statSync11, writeFileSync as writeFileSync25 } from "fs";
15649
+ import { dirname as dirname18, join as join37 } from "path";
15431
15650
  import { hostFromUrl as hostFromUrl3 } from "@tablation/client";
15432
15651
  function clonedCheckoutsFile(stateDir) {
15433
- return join36(stateDir, "cloned-checkouts.json");
15652
+ return join37(stateDir, "cloned-checkouts.json");
15434
15653
  }
15435
15654
  function readClonedCheckouts(stateDir) {
15436
15655
  try {
15437
- const parsed = JSON.parse(readFileSync33(clonedCheckoutsFile(stateDir), "utf8"));
15656
+ const parsed = JSON.parse(readFileSync34(clonedCheckoutsFile(stateDir), "utf8"));
15438
15657
  return Array.isArray(parsed) ? parsed.filter((d) => typeof d === "string") : [];
15439
15658
  } catch {
15440
15659
  return [];
@@ -15444,8 +15663,8 @@ function recordClonedCheckout(stateDir, dir) {
15444
15663
  const known = readClonedCheckouts(stateDir);
15445
15664
  if (known.includes(dir)) return;
15446
15665
  const file = clonedCheckoutsFile(stateDir);
15447
- mkdirSync23(dirname17(file), { recursive: true });
15448
- writeFileSync24(file, `${JSON.stringify([...known, dir], null, 2)}
15666
+ mkdirSync24(dirname18(file), { recursive: true });
15667
+ writeFileSync25(file, `${JSON.stringify([...known, dir], null, 2)}
15449
15668
  `);
15450
15669
  }
15451
15670
  var mark = (dryRun) => dryRun ? "would-remove" : "removed";
@@ -15499,8 +15718,8 @@ async function runReset(o, fx) {
15499
15718
  }
15500
15719
  if (o.beforeState) steps.push(...await o.beforeState());
15501
15720
  steps.push(...o.wipeState ? wipeStateDir(o.stateDir, o.dryRun) : removeState(o.stateDir, o.dryRun));
15502
- if (existsSync33(o.configFile)) {
15503
- if (!o.dryRun) rmSync18(o.configFile, { force: true });
15721
+ if (existsSync34(o.configFile)) {
15722
+ if (!o.dryRun) rmSync19(o.configFile, { force: true });
15504
15723
  steps.push({ step: "config", target: o.configFile, action: mark(o.dryRun) });
15505
15724
  } else {
15506
15725
  steps.push({ step: "config", target: o.configFile, action: "absent" });
@@ -15508,7 +15727,7 @@ async function runReset(o, fx) {
15508
15727
  return steps;
15509
15728
  }
15510
15729
  function removeCheckout(dir, dryRun, fx) {
15511
- if (!existsSync33(dir)) return { step: "checkout", target: dir, action: "absent", detail: "already gone" };
15730
+ if (!existsSync34(dir)) return { step: "checkout", target: dir, action: "absent", detail: "already gone" };
15512
15731
  const { dirty, linkedWorktrees } = fx.inspectCheckout(dir);
15513
15732
  if (dirty.length) {
15514
15733
  return { step: "checkout", target: dir, action: "kept", detail: `has uncommitted changes (${dirty.length} path${dirty.length === 1 ? "" : "s"}: ${dirty.slice(0, 5).join(", ")}${dirty.length > 5 ? ", \u2026" : ""})` };
@@ -15516,21 +15735,21 @@ function removeCheckout(dir, dryRun, fx) {
15516
15735
  if (linkedWorktrees.length) {
15517
15736
  return { step: "checkout", target: dir, action: "kept", detail: `has linked worktrees (${linkedWorktrees.join(", ")}); remove them first` };
15518
15737
  }
15519
- if (!dryRun) rmSync18(dir, { recursive: true, force: true });
15738
+ if (!dryRun) rmSync19(dir, { recursive: true, force: true });
15520
15739
  return { step: "checkout", target: dir, action: mark(dryRun) };
15521
15740
  }
15522
15741
  function removeState(stateDir, dryRun) {
15523
15742
  const out = [];
15524
- const targets = [join36(stateDir, "resolved"), join36(stateDir, "keys"), clonedCheckoutsFile(stateDir), join36(stateDir, "connect-session.json"), join36(stateDir, "reload-requested"), join36(stateDir, "daemon.started")];
15743
+ const targets = [join37(stateDir, "resolved"), join37(stateDir, "keys"), clonedCheckoutsFile(stateDir), join37(stateDir, "connect-session.json"), join37(stateDir, "reload-requested"), join37(stateDir, "daemon.started")];
15525
15744
  try {
15526
15745
  for (const name of readdirSync13(stateDir)) {
15527
- if (name.startsWith(".") && statSync11(join36(stateDir, name)).isFile()) targets.push(join36(stateDir, name));
15746
+ if (name.startsWith(".") && statSync11(join37(stateDir, name)).isFile()) targets.push(join37(stateDir, name));
15528
15747
  }
15529
15748
  } catch {
15530
15749
  }
15531
15750
  for (const t of targets) {
15532
- if (!existsSync33(t)) continue;
15533
- if (!dryRun) rmSync18(t, { recursive: true, force: true });
15751
+ if (!existsSync34(t)) continue;
15752
+ if (!dryRun) rmSync19(t, { recursive: true, force: true });
15534
15753
  out.push({ step: "state", target: t, action: mark(dryRun) });
15535
15754
  }
15536
15755
  if (!out.length) out.push({ step: "state", target: stateDir, action: "absent", detail: "nothing to remove" });
@@ -15544,7 +15763,7 @@ function wipeStateDir(stateDir, dryRun) {
15544
15763
  return [{ step: "state", target: stateDir, action: "absent", detail: "no state directory" }];
15545
15764
  }
15546
15765
  if (!names.length) return [{ step: "state", target: stateDir, action: "absent", detail: "already empty" }];
15547
- if (!dryRun) for (const n of names) rmSync18(join36(stateDir, n), { recursive: true, force: true });
15766
+ if (!dryRun) for (const n of names) rmSync19(join37(stateDir, n), { recursive: true, force: true });
15548
15767
  return [{ step: "state", target: stateDir, action: mark(dryRun), detail: `${names.length} entr${names.length === 1 ? "y" : "ies"}` }];
15549
15768
  }
15550
15769
  function describeResetStep(s) {
@@ -15610,6 +15829,7 @@ async function runDeprovision(o, fx, deps) {
15610
15829
  steps2.push({ step: "forge", target: host, action: "failed", detail: e.message });
15611
15830
  }
15612
15831
  }
15832
+ if (!o.dryRun) deps.eraseRepositoryEnv?.();
15613
15833
  const { volumes, images } = deps.labeled();
15614
15834
  for (const v of volumes) steps2.push(attempt("cache", `volume ${v}`, () => {
15615
15835
  deps.removeVolume(v);
@@ -15625,9 +15845,9 @@ async function runDeprovision(o, fx, deps) {
15625
15845
  }
15626
15846
 
15627
15847
  // src/pool-member.ts
15628
- import { mkdirSync as mkdirSync24, readFileSync as readFileSync34, renameSync as renameSync4, writeFileSync as writeFileSync25 } from "fs";
15848
+ import { mkdirSync as mkdirSync25, readFileSync as readFileSync35, renameSync as renameSync5, writeFileSync as writeFileSync26 } from "fs";
15629
15849
  import { homedir as homedir8 } from "os";
15630
- import { dirname as dirname18, join as join37 } from "path";
15850
+ import { dirname as dirname19, join as join38 } from "path";
15631
15851
  var POOL_EXIT = { ok: 0, failed: 1, credential: 2 };
15632
15852
  function backoffMs(attempt) {
15633
15853
  return Math.min(6e4, 5e3 * 2 ** Math.max(0, attempt));
@@ -15833,6 +16053,13 @@ async function runPoolMember(deps) {
15833
16053
  deps.log(`tokens: ${applied.reason ?? "could not apply the delivered forge tokens"}`);
15834
16054
  continue;
15835
16055
  }
16056
+ if (Array.isArray(body.repositoryEnv) && deps.applyRepositoryEnv) {
16057
+ const env = await deps.applyRepositoryEnv(body.repositoryEnv);
16058
+ if (!env.ok) {
16059
+ deps.log(`tokens: ${env.reason ?? "could not apply the delivered repository environment"}`);
16060
+ continue;
16061
+ }
16062
+ }
15836
16063
  deps.log(`tokens: replaced the forge tokens (${(body.forges ?? []).length} host${(body.forges ?? []).length === 1 ? "" : "s"})`);
15837
16064
  const r2 = await report("running", { leaseId: current });
15838
16065
  if (r2 === "credential") return POOL_EXIT.credential;
@@ -15850,6 +16077,10 @@ async function runPoolMember(deps) {
15850
16077
  if (r === "stopped") return POOL_EXIT.ok;
15851
16078
  const done = await deps.provision(lease, platform2.instanceClassKey, platform2.shipKind ?? "pooled_instance");
15852
16079
  if (!done.ok) return fail2(lease.id, done.reason ?? "provisioning failed");
16080
+ if (deps.applyRepositoryEnv) {
16081
+ const env = await deps.applyRepositoryEnv(lease.repositoryEnv ?? []);
16082
+ if (!env.ok) return fail2(lease.id, env.reason ?? "could not store the repository environment");
16083
+ }
15853
16084
  r = await report("running", { leaseId: lease.id });
15854
16085
  if (r === "credential") return POOL_EXIT.credential;
15855
16086
  current = lease.id;
@@ -15858,24 +16089,24 @@ async function runPoolMember(deps) {
15858
16089
  }
15859
16090
  }
15860
16091
  function defaultMemberDir(env = process.env) {
15861
- return env.CREW_POOL_DIR ?? join37(env.XDG_STATE_HOME ?? join37(homedir8(), ".local", "state"), "crew-pool-member");
16092
+ return env.CREW_POOL_DIR ?? join38(env.XDG_STATE_HOME ?? join38(homedir8(), ".local", "state"), "crew-pool-member");
15862
16093
  }
15863
16094
  function fileMemberStore(dir) {
15864
- const file = join37(dir, "member.json");
16095
+ const file = join38(dir, "member.json");
15865
16096
  return {
15866
16097
  read() {
15867
16098
  try {
15868
- return JSON.parse(readFileSync34(file, "utf8"));
16099
+ return JSON.parse(readFileSync35(file, "utf8"));
15869
16100
  } catch {
15870
16101
  return {};
15871
16102
  }
15872
16103
  },
15873
16104
  write(f) {
15874
- mkdirSync24(dirname18(file), { recursive: true, mode: 448 });
16105
+ mkdirSync25(dirname19(file), { recursive: true, mode: 448 });
15875
16106
  const tmp = `${file}.tmp`;
15876
- writeFileSync25(tmp, `${JSON.stringify(f)}
16107
+ writeFileSync26(tmp, `${JSON.stringify(f)}
15877
16108
  `, { mode: 384 });
15878
- renameSync4(tmp, file);
16109
+ renameSync5(tmp, file);
15879
16110
  }
15880
16111
  };
15881
16112
  }
@@ -15925,16 +16156,16 @@ function hostArchitecture(arch = process.arch) {
15925
16156
 
15926
16157
  // src/pool-member-host.ts
15927
16158
  import "child_process";
15928
- import { existsSync as existsSync36 } from "fs";
16159
+ import { existsSync as existsSync37 } from "fs";
15929
16160
  import { hostname as hostname3 } from "os";
15930
16161
 
15931
16162
  // src/machine-id.ts
15932
16163
  import { execFileSync as execFileSync12 } from "child_process";
15933
16164
  import { createHash as createHash8 } from "crypto";
15934
- import { existsSync as existsSync34, mkdirSync as mkdirSync25, readFileSync as readFileSync35, writeFileSync as writeFileSync26 } from "fs";
15935
- import { dirname as dirname19, join as join38 } from "path";
16165
+ import { existsSync as existsSync35, mkdirSync as mkdirSync26, readFileSync as readFileSync36, writeFileSync as writeFileSync27 } from "fs";
16166
+ import { dirname as dirname20, join as join39 } from "path";
15936
16167
  function machineIdPathFor(stateDir) {
15937
- return join38(stateDir, "machine-id");
16168
+ return join39(stateDir, "machine-id");
15938
16169
  }
15939
16170
  var sha256 = (s) => createHash8("sha256").update(s).digest("hex");
15940
16171
  function readRawMachineId(platform2 = process.platform) {
@@ -15947,8 +16178,8 @@ function readRawMachineId(platform2 = process.platform) {
15947
16178
  return /"IOPlatformUUID"\s*=\s*"([^"]+)"/.exec(out)?.[1];
15948
16179
  }
15949
16180
  for (const p of ["/etc/machine-id", "/var/lib/dbus/machine-id"]) {
15950
- if (existsSync34(p)) {
15951
- const id = readFileSync35(p, "utf8").trim();
16181
+ if (existsSync35(p)) {
16182
+ const id = readFileSync36(p, "utf8").trim();
15952
16183
  if (id) return id;
15953
16184
  }
15954
16185
  }
@@ -15959,15 +16190,15 @@ function readRawMachineId(platform2 = process.platform) {
15959
16190
  function ensureMachineId(stateDir, opts = {}) {
15960
16191
  if (opts.override?.trim()) return sha256(opts.override.trim());
15961
16192
  const path = machineIdPathFor(stateDir);
15962
- if (existsSync34(path)) {
15963
- const cached = readFileSync35(path, "utf8").trim();
16193
+ if (existsSync35(path)) {
16194
+ const cached = readFileSync36(path, "utf8").trim();
15964
16195
  if (/^[0-9a-f]{64}$/.test(cached)) return cached;
15965
16196
  }
15966
16197
  const raw = (opts.read ?? readRawMachineId)();
15967
16198
  if (!raw) return void 0;
15968
16199
  const hashed = sha256(raw);
15969
- mkdirSync25(dirname19(path), { recursive: true });
15970
- writeFileSync26(path, `${hashed}
16200
+ mkdirSync26(dirname20(path), { recursive: true });
16201
+ writeFileSync27(path, `${hashed}
15971
16202
  `, { mode: 384 });
15972
16203
  return hashed;
15973
16204
  }
@@ -15980,7 +16211,7 @@ function matchShipRows(ships, shipName2, machineId) {
15980
16211
 
15981
16212
  // src/provision.ts
15982
16213
  import { spawnSync as spawnSync9 } from "child_process";
15983
- import { existsSync as existsSync35, readFileSync as readFileSync36, writeFileSync as writeFileSync27 } from "fs";
16214
+ import { existsSync as existsSync36, readFileSync as readFileSync37, writeFileSync as writeFileSync28 } from "fs";
15984
16215
  import { hostname as hostname2 } from "os";
15985
16216
  import { parseDocument as parseDocument3, isMap as isMap2, isScalar } from "yaml";
15986
16217
 
@@ -15989,11 +16220,11 @@ import { parseDocument as parseDocument2 } from "yaml";
15989
16220
 
15990
16221
  // src/repos-cmd.ts
15991
16222
  import { homedir as homedir9 } from "os";
15992
- import { basename as basename10, join as join39, resolve as resolve4 } from "path";
16223
+ import { basename as basename10, join as join40, resolve as resolve4 } from "path";
15993
16224
  import { isMap, isSeq, parseDocument, stringify as stringify2 } from "yaml";
15994
16225
  var ReposError = class extends Error {
15995
16226
  };
15996
- function normalizeRemote(url) {
16227
+ function normalizeRemote2(url) {
15997
16228
  if (!url) return void 0;
15998
16229
  let s = url.trim();
15999
16230
  if (!s) return void 0;
@@ -16006,10 +16237,10 @@ function normalizeRemote(url) {
16006
16237
  return parts.slice(-2).join("/").toLowerCase();
16007
16238
  }
16008
16239
  function matchRepoName(origin, resolved) {
16009
- const want = normalizeRemote(origin);
16240
+ const want = normalizeRemote2(origin);
16010
16241
  if (!want || !resolved?.repoRemotes) return void 0;
16011
16242
  for (const [id, remote] of Object.entries(resolved.repoRemotes)) {
16012
- if (normalizeRemote(remote) === want) return resolved.repoNames?.[id];
16243
+ if (normalizeRemote2(remote) === want) return resolved.repoNames?.[id];
16013
16244
  }
16014
16245
  return void 0;
16015
16246
  }
@@ -16089,15 +16320,15 @@ function listRepoRows(i) {
16089
16320
  const originFor = (c, remote) => {
16090
16321
  const o = i.originOf(c.dir) ?? null;
16091
16322
  if (!o) return null;
16092
- return remote !== null && normalizeRemote(o) === normalizeRemote(remote) ? null : o;
16323
+ return remote !== null && normalizeRemote2(o) === normalizeRemote2(remote) ? null : o;
16093
16324
  };
16094
16325
  const rows = [];
16095
16326
  const names = i.resolved?.repoNames ?? {};
16096
16327
  const remotes = i.resolved?.repoRemotes ?? {};
16097
16328
  for (const [id, name] of Object.entries(names)) {
16098
16329
  const remote = remotes[id] ?? null;
16099
- const want = normalizeRemote(remote);
16100
- let idx = checkouts.findIndex((c2, n) => !claimed.has(n) && want !== void 0 && normalizeRemote(i.originOf(c2.dir)) === want);
16330
+ const want = normalizeRemote2(remote);
16331
+ let idx = checkouts.findIndex((c2, n) => !claimed.has(n) && want !== void 0 && normalizeRemote2(i.originOf(c2.dir)) === want);
16101
16332
  if (idx < 0) idx = checkouts.findIndex((c2, n) => !claimed.has(n) && c2.name === name);
16102
16333
  const c = idx >= 0 ? checkouts[idx] : void 0;
16103
16334
  if (idx >= 0) claimed.add(idx);
@@ -16150,11 +16381,11 @@ function planRepoAdd(i) {
16150
16381
  throw new ReposError(`${target} is already configured on route ${i.route}`);
16151
16382
  }
16152
16383
  const matched = matchRepoName(i.origin, i.resolved);
16153
- const name = matched ?? i.name ?? normalizeRemote(i.origin)?.split("/").pop() ?? basename10(target);
16384
+ const name = matched ?? i.name ?? normalizeRemote2(i.origin)?.split("/").pop() ?? basename10(target);
16154
16385
  let warning;
16155
16386
  if (!matched) {
16156
16387
  const known = Object.values(i.resolved?.repoNames ?? {});
16157
- warning = i.origin ? `the tracker has no Repos row for remote ${normalizeRemote(i.origin) ?? i.origin}${known.length ? ` (known: ${known.join(", ")})` : ""} \u2014 added anyway; create the row so ticket routing can find it` : "this checkout has no origin remote, so it cannot be matched to a Repos row \u2014 added anyway";
16388
+ warning = i.origin ? `the tracker has no Repos row for remote ${normalizeRemote2(i.origin) ?? i.origin}${known.length ? ` (known: ${known.join(", ")})` : ""} \u2014 added anyway; create the row so ticket routing can find it` : "this checkout has no origin remote, so it cannot be matched to a Repos row \u2014 added anyway";
16158
16389
  }
16159
16390
  const repos = m.get("repos", true);
16160
16391
  let mode;
@@ -16207,7 +16438,7 @@ function renderBlock(m) {
16207
16438
  }
16208
16439
  var LOCAL_RELEASE_MODES = /* @__PURE__ */ new Set(["integrate", "external"]);
16209
16440
  function planRepoRow(i) {
16210
- const remote = normalizeRemote(i.origin);
16441
+ const remote = normalizeRemote2(i.origin);
16211
16442
  if (!remote) throw new ReposError(`cannot derive an owner/repo from origin "${i.origin}"`);
16212
16443
  const mode = i.spec?.releaseMode;
16213
16444
  return {
@@ -16253,7 +16484,7 @@ function planRepoClone(i) {
16253
16484
  throw new ReposError(`the tracker has no Repos row named "${i.name}" for route ${i.route}${known.length ? ` (known: ${known.join(", ")})` : " \u2014 run `crew connect` to refresh them"}`);
16254
16485
  }
16255
16486
  const name = names[id];
16256
- const remote = normalizeRemote(i.resolved?.repoRemotes?.[id]);
16487
+ const remote = normalizeRemote2(i.resolved?.repoRemotes?.[id]);
16257
16488
  if (!remote) {
16258
16489
  throw new ReposError(
16259
16490
  `the Repos row "${name}" has no remote to clone from \u2014 attach an existing checkout with \`crew repos add ${i.route} ${name} <path>\`, or set the row's remote in the tracker and re-run \`crew connect\``
@@ -16267,7 +16498,7 @@ function planRepoClone(i) {
16267
16498
  }
16268
16499
  const ship = doc.get("ship", true);
16269
16500
  const basePath = String(m.get("reposBasePath") ?? (isMap(ship) ? ship.get("reposBasePath") : void 0) ?? "~/Crew");
16270
- const target = i.dir ? expandDir(i.dir, i.base) : join39(expandDir(basePath, i.base), i.route.split("/")[0], name);
16501
+ const target = i.dir ? expandDir(i.dir, i.base) : join40(expandDir(basePath, i.base), i.route.split("/")[0], name);
16271
16502
  const add = planRepoAdd({ text: i.text, base: i.base, route: i.route, path: target, origin: remote, resolved: i.resolved, name, isCheckout: i.isCheckout });
16272
16503
  const forgeHost = i.resolved?.repoForgeHosts?.[id];
16273
16504
  return { ...add, remote, target, ...forgeHost ? { forgeHost } : {} };
@@ -16598,7 +16829,7 @@ function realProvisionDeps(crewHome) {
16598
16829
  };
16599
16830
  const configFile = () => {
16600
16831
  const f = findConfigFile(crewHome);
16601
- return existsSync35(f) ? f : null;
16832
+ return existsSync36(f) ? f : null;
16602
16833
  };
16603
16834
  return {
16604
16835
  crew: spawnCrew,
@@ -16606,13 +16837,13 @@ function realProvisionDeps(crewHome) {
16606
16837
  enableRoute(route2) {
16607
16838
  const file = configFile();
16608
16839
  if (!file) return false;
16609
- const text2 = readFileSync36(file, "utf8");
16840
+ const text2 = readFileSync37(file, "utf8");
16610
16841
  const doc = parseDocument3(text2);
16611
16842
  const routes = doc.get("routes");
16612
16843
  const entry = routes?.items?.find((r) => r.get("route") === route2);
16613
16844
  if (!entry) throw new Error(`route ${route2} is not in ${file}`);
16614
16845
  if (entry.get("enabled") === true) return false;
16615
- writeFileSync27(file, planEnable(text2, route2));
16846
+ writeFileSync28(file, planEnable(text2, route2));
16616
16847
  return true;
16617
16848
  },
16618
16849
  installState() {
@@ -16632,14 +16863,14 @@ function realProvisionDeps(crewHome) {
16632
16863
  continue;
16633
16864
  }
16634
16865
  for (const p of plan.unitPaths) {
16635
- if (!existsSync35(p) || readFileSync36(p, "utf8") !== plan.unitContent[p]) unitsStale = true;
16866
+ if (!existsSync36(p) || readFileSync37(p, "utf8") !== plan.unitContent[p]) unitsStale = true;
16636
16867
  }
16637
16868
  }
16638
16869
  const label = labelFor(crewHome, "run");
16639
16870
  let running = false;
16640
16871
  let lingering = true;
16641
16872
  if (mechanism === "systemd") {
16642
- const system = ctx.root || existsSync35(systemUnitPathFor(label));
16873
+ const system = ctx.root || existsSync36(systemUnitPathFor(label));
16643
16874
  const ctl = system ? ["systemctl"] : ["systemctl", "--user"];
16644
16875
  running = spawnSync9(ctl[0], [...ctl.slice(1), "is-active", "--quiet", `${label}.service`], { env: withUserBusEnv() }).status === 0;
16645
16876
  if (!system) {
@@ -16656,18 +16887,18 @@ function realProvisionDeps(crewHome) {
16656
16887
  setShipSetting(key, value2) {
16657
16888
  const file = configFile();
16658
16889
  if (!file) return false;
16659
- const doc = parseDocument3(readFileSync36(file, "utf8"));
16890
+ const doc = parseDocument3(readFileSync37(file, "utf8"));
16660
16891
  if (doc.getIn(["ship", key]) === value2) return false;
16661
16892
  doc.setIn(["ship", key], value2);
16662
- writeFileSync27(file, doc.toString());
16893
+ writeFileSync28(file, doc.toString());
16663
16894
  return true;
16664
16895
  },
16665
16896
  applyManagedDefaults() {
16666
16897
  const file = configFile();
16667
16898
  if (!file) return [];
16668
- const doc = parseDocument3(readFileSync36(file, "utf8"));
16899
+ const doc = parseDocument3(readFileSync37(file, "utf8"));
16669
16900
  const wrote = applyManagedDefaultsToDoc(doc);
16670
- if (wrote.length) writeFileSync27(file, doc.toString());
16901
+ if (wrote.length) writeFileSync28(file, doc.toString());
16671
16902
  return wrote;
16672
16903
  },
16673
16904
  ensureGitIdentity(name, email) {
@@ -16717,7 +16948,7 @@ function realPoolMemberDeps(o) {
16717
16948
  crewVersion: crewVersion(o.crewHome),
16718
16949
  hostname: hostname3()
16719
16950
  },
16720
- hasShipConfig: () => existsSync36(findConfigFile(o.crewHome)),
16951
+ hasShipConfig: () => existsSync37(findConfigFile(o.crewHome)),
16721
16952
  async provision(lease, instanceClass, shipKind) {
16722
16953
  const hosts = lease.forges.map((f) => f.host.toLowerCase());
16723
16954
  const lines2 = [];
@@ -16766,6 +16997,16 @@ function realPoolMemberDeps(o) {
16766
16997
  }
16767
16998
  return { ok: true };
16768
16999
  },
17000
+ async applyRepositoryEnv(entries) {
17001
+ const cfg = loadShip(o.crewHome);
17002
+ if (!cfg) return { ok: false, reason: "no ship config to store the repository environment under" };
17003
+ try {
17004
+ writeRepositoryEnv(cfg.ship.stateDir, entries);
17005
+ } catch (e) {
17006
+ return { ok: false, reason: `repository environment: ${e.message}` };
17007
+ }
17008
+ return { ok: true };
17009
+ },
16769
17010
  async reconcile() {
16770
17011
  const before = provisionDeps.installState();
16771
17012
  if (before.unitsStale || !before.running || !before.lingering) {
@@ -17595,7 +17836,7 @@ ${waiting.map((t) => `| ${displayKey2(t)} | ${t.status} | ${blockers(t, i)} |`).
17595
17836
 
17596
17837
  // src/sandbox-hygiene.ts
17597
17838
  import { execFile as execFile3 } from "child_process";
17598
- import { existsSync as existsSync37, statfsSync as statfsSync2 } from "fs";
17839
+ import { existsSync as existsSync38, statfsSync as statfsSync2 } from "fs";
17599
17840
  import { promisify as promisify3 } from "util";
17600
17841
  var execFileP3 = promisify3(execFile3);
17601
17842
  var REAP_MIN_AGE_MS = 5 * 6e4;
@@ -17738,7 +17979,7 @@ async function realDiskReadings(ship) {
17738
17979
  const paths = ["/"];
17739
17980
  try {
17740
17981
  const root = (await run3(ship.sandbox?.engine ?? DEFAULT_CACHE_SETTINGS.engine, ["info", "--format", "{{.DockerRootDir}}"])).trim();
17741
- if (root && existsSync37(root)) paths.push(root);
17982
+ if (root && existsSync38(root)) paths.push(root);
17742
17983
  } catch {
17743
17984
  }
17744
17985
  return paths.flatMap((path) => {
@@ -17779,8 +18020,8 @@ function diskFullStop(state) {
17779
18020
  }
17780
18021
 
17781
18022
  // src/poll.ts
17782
- import { writeFileSync as writeFileSync28 } from "fs";
17783
- import { join as join40 } from "path";
18023
+ import { writeFileSync as writeFileSync29 } from "fs";
18024
+ import { join as join41 } from "path";
17784
18025
 
17785
18026
  // src/stalled.ts
17786
18027
  var STALLED_AFTER_CYCLES = 30;
@@ -18094,7 +18335,7 @@ async function decideCycle(o) {
18094
18335
  }
18095
18336
  return decision;
18096
18337
  }
18097
- var digestPath = (stateDir, route2, role, runId) => join40(stateDir, `digest-${route2}-${role}${runId ? `-${runId}` : ""}.md`);
18338
+ var digestPath = (stateDir, route2, role, runId) => join41(stateDir, `digest-${route2}-${role}${runId ? `-${runId}` : ""}.md`);
18098
18339
  function otherRunsRemoved(tickets, own) {
18099
18340
  if (!own) return tickets;
18100
18341
  return tickets.filter((t) => t.id === own.ticket.id || !own.inFlight(t.id));
@@ -18178,7 +18419,7 @@ function writeDigest(o, d, role, stateDir, runId, own) {
18178
18419
 
18179
18420
  ${body}` : body;
18180
18421
  const path = digestPath(stateDir, routeSlug(o.route.route), role, runId);
18181
- writeFileSync28(path, text2);
18422
+ writeFileSync29(path, text2);
18182
18423
  o.emit.emit(`queue digest written for ${role} (${Buffer.byteLength(text2)} bytes)`, {
18183
18424
  data: { role, bytes: Buffer.byteLength(text2) }
18184
18425
  });
@@ -18301,8 +18542,8 @@ async function claimStillHeld(tracker, t, buildingStatus, affinity) {
18301
18542
  }
18302
18543
 
18303
18544
  // src/repo-refresh.ts
18304
- import { existsSync as existsSync38, mkdirSync as mkdirSync26, readFileSync as readFileSync37, writeFileSync as writeFileSync29 } from "fs";
18305
- import { dirname as dirname21 } from "path";
18545
+ import { existsSync as existsSync39, mkdirSync as mkdirSync27, readFileSync as readFileSync38, writeFileSync as writeFileSync30 } from "fs";
18546
+ import { dirname as dirname22 } from "path";
18306
18547
  var REFRESH_COOLDOWN_MS = 2 * 6e4;
18307
18548
  var UNSERVABLE_PASSES_BEFORE_ATTENTION = 3;
18308
18549
  var lastAsked = /* @__PURE__ */ new Map();
@@ -18331,11 +18572,11 @@ function applyRepoRows(resolved, rows) {
18331
18572
  }
18332
18573
  function persistRepoRows(stateDir, routeName, rows) {
18333
18574
  const path = resolvedPathFor(stateDir, routeName);
18334
- if (!existsSync38(path)) return;
18335
- const raw = JSON.parse(readFileSync37(path, "utf8"));
18575
+ if (!existsSync39(path)) return;
18576
+ const raw = JSON.parse(readFileSync38(path, "utf8"));
18336
18577
  applyRepoRows(raw, rows);
18337
- mkdirSync26(dirname21(path), { recursive: true });
18338
- writeFileSync29(path, `${JSON.stringify(raw, null, 2)}
18578
+ mkdirSync27(dirname22(path), { recursive: true });
18579
+ writeFileSync30(path, `${JSON.stringify(raw, null, 2)}
18339
18580
  `);
18340
18581
  }
18341
18582
  async function refreshUnknownRepos(o) {
@@ -18784,14 +19025,42 @@ Ship ${shipName2} found: ${problem}. The release refuses to squash a ref nobody
18784
19025
  }
18785
19026
  var localRefSkipReported = (ticket, problem, events) => events.some((e) => e.record_id === ticket.id && e.event_type === "local_ref_skip" && (e.message ?? "").includes(problem));
18786
19027
 
19028
+ // src/platform-gate.ts
19029
+ import { join as join42 } from "path";
19030
+ function platformAdmitters(dir, baseRef, ship, tickets, locate) {
19031
+ const out = [];
19032
+ for (const t of tickets) {
19033
+ const branch = locate(t);
19034
+ if (!branch) continue;
19035
+ const changed2 = gitOk(dir, ["diff", "--name-only", `${baseRef}...${branch}`, "--", ...REPO_CONFIG_FILENAMES]);
19036
+ const file = changed2?.split("\n").find((f) => f.trim() !== "");
19037
+ if (!file) continue;
19038
+ const text2 = gitOk(dir, ["show", `${branch}:${file}`]);
19039
+ if (text2 === null) continue;
19040
+ try {
19041
+ const { platform: platform2 } = parseRepoConfig(text2, join42(dir, file));
19042
+ if (satisfies(ship, platform2)) out.push({ issueId: t.issue_id, branch, platform: platform2 });
19043
+ } catch (e) {
19044
+ if (e instanceof RepoConfigError) continue;
19045
+ throw e;
19046
+ }
19047
+ }
19048
+ return out;
19049
+ }
19050
+ function platformStuckNote(repo, required, ship, issueIds) {
19051
+ const who2 = eligibleShips(required).join(", ");
19052
+ const stuck = issueIds.length ? `${issueIds.join(", ")} verified but cannot be released by this ${ship} ship` : `this ${ship} ship cannot release it`;
19053
+ return `${repo}: its contract requires ${required}, so ${stuck}; only a ${who2} ship can (and no verified branch changes platform to admit this one)`;
19054
+ }
19055
+
18787
19056
  // src/connect-wizard.ts
18788
- import { delimiter, dirname as dirname22, join as join41 } from "path";
18789
- import { accessSync as accessSync3, constants as constants3, existsSync as existsSync39, mkdirSync as mkdirSync27, writeFileSync as writeFileSync30 } from "fs";
19057
+ import { delimiter, dirname as dirname23, join as join43 } from "path";
19058
+ import { accessSync as accessSync3, constants as constants3, existsSync as existsSync40, mkdirSync as mkdirSync28, writeFileSync as writeFileSync31 } from "fs";
18790
19059
  import { stringify as stringify3 } from "yaml";
18791
19060
  var HOST_PASSENGERS_DOCS_URL = "https://crew.tablation.dev/host-passengers";
18792
19061
  function shouldRunWizard(opts) {
18793
19062
  if (!opts.isTTY) return false;
18794
- const exists = opts.configExists ?? existsSync39;
19063
+ const exists = opts.configExists ?? existsSync40;
18795
19064
  return !configSearchPath(opts.crewHome).some((p) => exists(p));
18796
19065
  }
18797
19066
  function firstRunConfigPath() {
@@ -18808,7 +19077,7 @@ function defaultIsExecutable(p) {
18808
19077
  function findOnPath2(name, pathEnv, isExecutable = defaultIsExecutable) {
18809
19078
  for (const dir of pathEnv.split(delimiter)) {
18810
19079
  if (!dir) continue;
18811
- const candidate = join41(dir, name);
19080
+ const candidate = join43(dir, name);
18812
19081
  if (isExecutable(candidate)) return candidate;
18813
19082
  }
18814
19083
  return void 0;
@@ -18834,9 +19103,9 @@ async function runWizard(p, env) {
18834
19103
  if (entered && isExec(entered)) agentBin = entered;
18835
19104
  else p.say(entered ? `${entered} is not an executable file.` : "A path is required.");
18836
19105
  }
18837
- const nodeDir = dirname22(env.nodePath);
19106
+ const nodeDir = dirname23(env.nodePath);
18838
19107
  const pnpmPath = findOnPath2("pnpm", env.pathEnv, isExec);
18839
- const baseDirs = [nodeDir, pnpmPath ? dirname22(pnpmPath) : void 0];
19108
+ const baseDirs = [nodeDir, pnpmPath ? dirname23(pnpmPath) : void 0];
18840
19109
  p.say(
18841
19110
  `
18842
19111
  Host Passengers lets this machine run the agent sessions that other people's
@@ -18847,7 +19116,7 @@ Tablation workspaces ask for, in a container. More: ${HOST_PASSENGERS_DOCS_URL}`
18847
19116
  p.say("Docker is not available here, so nothing will be hosted until it is. Your answer is recorded anyway.");
18848
19117
  }
18849
19118
  const dockerPath = hostPassengers ? findOnPath2("docker", env.pathEnv, isExec) : void 0;
18850
- const extraPath = deriveExtraPath([...baseDirs, dockerPath ? dirname22(dockerPath) : void 0]);
19119
+ const extraPath = deriveExtraPath([...baseDirs, dockerPath ? dirname23(dockerPath) : void 0]);
18851
19120
  if (extraPath) {
18852
19121
  p.say(`Hooks will get ${extraPath} on their PATH (where node, pnpm${dockerPath ? " and docker" : ""} live).`);
18853
19122
  }
@@ -18869,9 +19138,9 @@ routes:
18869
19138
  ${routeBlock}`;
18870
19139
  }
18871
19140
  function writeNewConfig(path, text2) {
18872
- mkdirSync27(dirname22(path), { recursive: true });
19141
+ mkdirSync28(dirname23(path), { recursive: true });
18873
19142
  try {
18874
- writeFileSync30(path, text2, { mode: 384, flag: "wx" });
19143
+ writeFileSync31(path, text2, { mode: 384, flag: "wx" });
18875
19144
  return true;
18876
19145
  } catch (e) {
18877
19146
  if (e.code === "EEXIST") return false;
@@ -18905,7 +19174,7 @@ Wrote ${o.configPath}.
18905
19174
  // src/connect-json.ts
18906
19175
  import { accessSync as accessSync4, constants as constants4 } from "fs";
18907
19176
  import { homedir as homedir10 } from "os";
18908
- import { dirname as dirname23, join as join42 } from "path";
19177
+ import { dirname as dirname24, join as join44 } from "path";
18909
19178
  import { delimiter as delimiter2 } from "path";
18910
19179
  var CHOICE_EXIT_CODE = 3;
18911
19180
  function createEmitter(json2, write) {
@@ -18944,12 +19213,12 @@ function agentBinSearchDirs(home, pathEnv, extraPath) {
18944
19213
  const dirs = [
18945
19214
  ...pathEnv.split(delimiter2),
18946
19215
  ...(extraPath ?? "").split(delimiter2),
18947
- join42(home, ".local/bin"),
18948
- join42(home, ".claude/local"),
19216
+ join44(home, ".local/bin"),
19217
+ join44(home, ".claude/local"),
18949
19218
  "/opt/homebrew/bin",
18950
19219
  "/usr/local/bin",
18951
- join42(home, ".npm-global/bin"),
18952
- join42(home, ".volta/bin")
19220
+ join44(home, ".npm-global/bin"),
19221
+ join44(home, ".volta/bin")
18953
19222
  ];
18954
19223
  return [...new Set(dirs.filter(Boolean))];
18955
19224
  }
@@ -18971,7 +19240,7 @@ function flagWizardAnswers(f, env) {
18971
19240
  const agentBin = f.agentBin ?? found?.bin;
18972
19241
  const pnpmPath = findOnPath2("pnpm", env.pathEnv, isExec);
18973
19242
  const dockerPath = f.hostPassengers ? findOnPath2("docker", env.pathEnv, isExec) : void 0;
18974
- const extraPath = f.extraPath ?? deriveExtraPath([dirname23(env.nodePath), pnpmPath ? dirname23(pnpmPath) : void 0, dockerPath ? dirname23(dockerPath) : void 0]);
19243
+ const extraPath = f.extraPath ?? deriveExtraPath([dirname24(env.nodePath), pnpmPath ? dirname24(pnpmPath) : void 0, dockerPath ? dirname24(dockerPath) : void 0]);
18975
19244
  return {
18976
19245
  answers: {
18977
19246
  name: f.shipName?.trim() || env.hostname,
@@ -19070,8 +19339,8 @@ async function collectDiagnostics(d) {
19070
19339
  }
19071
19340
 
19072
19341
  // src/release-run.ts
19073
- import { readFileSync as readFileSync38, writeFileSync as writeFileSync31, existsSync as existsSync40, copyFileSync, mkdirSync as mkdirSync28, mkdtempSync as mkdtempSync3, rmSync as rmSync19 } from "fs";
19074
- import { dirname as dirname24, join as join43 } from "path";
19342
+ import { readFileSync as readFileSync39, writeFileSync as writeFileSync32, existsSync as existsSync41, copyFileSync, mkdirSync as mkdirSync29, mkdtempSync as mkdtempSync3, rmSync as rmSync20 } from "fs";
19343
+ import { dirname as dirname25, join as join45 } from "path";
19075
19344
  import { tmpdir as tmpdir6, hostname as hostname4 } from "os";
19076
19345
 
19077
19346
  // src/release.ts
@@ -19853,13 +20122,13 @@ async function bump(o, size) {
19853
20122
  }
19854
20123
  return printed;
19855
20124
  }
19856
- const files = o.repo.release.versionFiles.map((f) => join43(o.cwd, f));
20125
+ const files = o.repo.release.versionFiles.map((f) => join45(o.cwd, f));
19857
20126
  const first = files[0];
19858
- if (!existsAt(first, existsSync40)) {
20127
+ if (!existsAt(first, existsSync41)) {
19859
20128
  o.emit.error(`no ${o.repo.release.versionFiles[0]} to read a version from`);
19860
20129
  return null;
19861
20130
  }
19862
- const firstText = readTextAt(first, (p) => readFileSync38(p, "utf8"));
20131
+ const firstText = readTextAt(first, (p) => readFileSync39(p, "utf8"));
19863
20132
  const problem = versionFileProblem(o.repo.release.versionFiles[0], firstText);
19864
20133
  if (problem) {
19865
20134
  o.emit.error(problem);
@@ -19878,27 +20147,27 @@ async function bump(o, size) {
19878
20147
  return version;
19879
20148
  }
19880
20149
  for (const f of files) {
19881
- const src = readTextAt(f, (p) => readFileSync38(p, "utf8"));
20150
+ const src = readTextAt(f, (p) => readFileSync39(p, "utf8"));
19882
20151
  const out = src.replace(/("version"\s*:\s*")[^"]*(")/, `$1${version}$2`);
19883
20152
  if (out === src) {
19884
20153
  o.emit.error(`no version field in ${f}`);
19885
20154
  return null;
19886
20155
  }
19887
- writeTextAt(f, out, writeFileSync31);
20156
+ writeTextAt(f, out, writeFileSync32);
19888
20157
  }
19889
20158
  return version;
19890
20159
  }
19891
20160
  function writeChangelog(o, version, entries) {
19892
20161
  const file = o.repo.release.changelog;
19893
20162
  if (!file || entries.length === 0) return;
19894
- const path = join43(o.cwd, file);
20163
+ const path = join45(o.cwd, file);
19895
20164
  const section = renderChangelogSection(version, (/* @__PURE__ */ new Date()).toISOString().slice(0, 10), entries);
19896
20165
  if (o.dryRun) {
19897
20166
  o.emit.emit(`would prepend ${entries.length} entr(ies) to ${file}`);
19898
20167
  return;
19899
20168
  }
19900
- const existing = existsAt(path, existsSync40) ? readTextAt(path, (p) => readFileSync38(p, "utf8")) : "# Changelog\n";
19901
- writeTextAt(path, insertChangelogSection(existing, section), writeFileSync31);
20169
+ const existing = existsAt(path, existsSync41) ? readTextAt(path, (p) => readFileSync39(p, "utf8")) : "# Changelog\n";
20170
+ writeTextAt(path, insertChangelogSection(existing, section), writeFileSync32);
19902
20171
  }
19903
20172
  async function confirm(o, expected) {
19904
20173
  if (!o.repo.hooks.released) return void 0;
@@ -19981,7 +20250,7 @@ function closeReleaseCheckout(cwd, root, dir, branch, run4 = gitOk) {
19981
20250
  run4(cwd, ["worktree", "remove", "--force", dir]);
19982
20251
  } finally {
19983
20252
  try {
19984
- rmSync19(root, { recursive: true, force: true });
20253
+ rmSync20(root, { recursive: true, force: true });
19985
20254
  } finally {
19986
20255
  run4(cwd, ["worktree", "prune"]);
19987
20256
  run4(cwd, ["branch", "-D", branch]);
@@ -19991,8 +20260,8 @@ function closeReleaseCheckout(cwd, root, dir, branch, run4 = gitOk) {
19991
20260
  function openReleaseCheckout(o) {
19992
20261
  const { remote, base } = o.repo.branch;
19993
20262
  const branch = `crew/release-${Date.now()}`;
19994
- const root = mkdtempSync3(join43(tmpdir6(), "crew-release-"));
19995
- const dir = join43(root, "checkout");
20263
+ const root = mkdtempSync3(join45(tmpdir6(), "crew-release-"));
20264
+ const dir = join45(root, "checkout");
19996
20265
  o.emit.emit(`release checkout: ${dir}`, { step: "release" });
19997
20266
  const close = () => closeReleaseCheckout(o.cwd, root, dir, branch);
19998
20267
  try {
@@ -20002,10 +20271,10 @@ function openReleaseCheckout(o) {
20002
20271
  throw e;
20003
20272
  }
20004
20273
  for (const f of o.repo.worktrees.copy) {
20005
- const src = join43(o.cwd, f);
20006
- if (!existsSync40(src)) continue;
20007
- mkdirSync28(dirname24(join43(dir, f)), { recursive: true });
20008
- copyFileSync(src, join43(dir, f));
20274
+ const src = join45(o.cwd, f);
20275
+ if (!existsSync41(src)) continue;
20276
+ mkdirSync29(dirname25(join45(dir, f)), { recursive: true });
20277
+ copyFileSync(src, join45(dir, f));
20009
20278
  }
20010
20279
  return { dir, branch, close };
20011
20280
  }
@@ -20731,11 +21000,11 @@ Passed: ${passed}.${willClose ? " Closing this alert." : ""}`,
20731
21000
  }
20732
21001
 
20733
21002
  // src/daemon-liveness.ts
20734
- import { existsSync as existsSync47, readFileSync as readFileSync44 } from "fs";
21003
+ import { existsSync as existsSync48, readFileSync as readFileSync45 } from "fs";
20735
21004
 
20736
21005
  // src/daemon.ts
20737
- import { existsSync as existsSync46, mkdirSync as mkdirSync34, readFileSync as readFileSync43, readdirSync as readdirSync14, rmSync as rmSync21, statSync as statSync13, writeFileSync as writeFileSync35 } from "fs";
20738
- import { join as join48 } from "path";
21006
+ import { existsSync as existsSync47, mkdirSync as mkdirSync35, readFileSync as readFileSync44, readdirSync as readdirSync14, rmSync as rmSync22, statSync as statSync13, writeFileSync as writeFileSync36 } from "fs";
21007
+ import { join as join50 } from "path";
20739
21008
  import { randomBytes } from "crypto";
20740
21009
 
20741
21010
  // src/fleet.ts
@@ -20825,27 +21094,27 @@ function nextRoles(decision, ran) {
20825
21094
  }
20826
21095
 
20827
21096
  // src/noop-runs.ts
20828
- import { existsSync as existsSync41, mkdirSync as mkdirSync29, readFileSync as readFileSync39, renameSync as renameSync5, writeFileSync as writeFileSync32 } from "fs";
20829
- import { join as join44 } from "path";
21097
+ import { existsSync as existsSync42, mkdirSync as mkdirSync30, readFileSync as readFileSync40, renameSync as renameSync6, writeFileSync as writeFileSync33 } from "fs";
21098
+ import { join as join46 } from "path";
20830
21099
  var NOOP_DELAYS_MS = [5, 15, 60].map((m) => m * 6e4);
20831
21100
  var DEFAULT_NOOP_REPEATS = 3;
20832
21101
  var NOOP_BOUNCED_MARKER = calloutHeader("WARNING", "Runs Changed Nothing");
20833
- var noopRunsPath = (stateDir) => join44(stateDir, "noop-runs.json");
21102
+ var noopRunsPath = (stateDir) => join46(stateDir, "noop-runs.json");
20834
21103
  var noopRunsKey = (issueId) => `noop_runs:${issueId}`;
20835
21104
  function readNoopRuns(stateDir) {
20836
21105
  try {
20837
- const v = JSON.parse(readFileSync39(noopRunsPath(stateDir), "utf8"));
21106
+ const v = JSON.parse(readFileSync40(noopRunsPath(stateDir), "utf8"));
20838
21107
  return v && typeof v === "object" && !Array.isArray(v) ? v : {};
20839
21108
  } catch {
20840
21109
  return {};
20841
21110
  }
20842
21111
  }
20843
21112
  function writeNoopRuns(stateDir, state) {
20844
- mkdirSync29(stateDir, { recursive: true });
21113
+ mkdirSync30(stateDir, { recursive: true });
20845
21114
  const file = noopRunsPath(stateDir);
20846
- writeFileSync32(`${file}.tmp`, `${JSON.stringify(state, null, 2)}
21115
+ writeFileSync33(`${file}.tmp`, `${JSON.stringify(state, null, 2)}
20847
21116
  `);
20848
- renameSync5(`${file}.tmp`, file);
21117
+ renameSync6(`${file}.tmp`, file);
20849
21118
  }
20850
21119
  function noopBackedOff(stateDir, recordId, now = Date.now()) {
20851
21120
  const e = readNoopRuns(stateDir)[recordId];
@@ -20860,7 +21129,7 @@ function recordNoopRun(stateDir, recordId, repeats, now = Date.now()) {
20860
21129
  return { count, nextAt, bounce: count >= repeats };
20861
21130
  }
20862
21131
  function clearNoopRuns(stateDir, recordId) {
20863
- if (!existsSync41(noopRunsPath(stateDir))) return;
21132
+ if (!existsSync42(noopRunsPath(stateDir))) return;
20864
21133
  const state = readNoopRuns(stateDir);
20865
21134
  if (!(recordId in state)) return;
20866
21135
  delete state[recordId];
@@ -20920,8 +21189,8 @@ async function settleNoopRun(o) {
20920
21189
  }
20921
21190
 
20922
21191
  // src/ship-name.ts
20923
- import { existsSync as existsSync42, mkdirSync as mkdirSync30, readFileSync as readFileSync40, renameSync as renameSync6, writeFileSync as writeFileSync33 } from "fs";
20924
- import { dirname as dirname25 } from "path";
21192
+ import { existsSync as existsSync43, mkdirSync as mkdirSync31, readFileSync as readFileSync41, renameSync as renameSync7, writeFileSync as writeFileSync34 } from "fs";
21193
+ import { dirname as dirname26 } from "path";
20925
21194
  import { parseDocument as parseDocument4 } from "yaml";
20926
21195
  var ShipNameError = class extends Error {
20927
21196
  };
@@ -20982,34 +21251,34 @@ async function syncRouteName(i) {
20982
21251
  return { status: "ok", ...base, action, name: i.local };
20983
21252
  }
20984
21253
  function readSyncedName(resolvedFile) {
20985
- if (!existsSync42(resolvedFile)) return void 0;
21254
+ if (!existsSync43(resolvedFile)) return void 0;
20986
21255
  try {
20987
- const v = JSON.parse(readFileSync40(resolvedFile, "utf8")).shipName;
21256
+ const v = JSON.parse(readFileSync41(resolvedFile, "utf8")).shipName;
20988
21257
  return typeof v === "string" ? v : void 0;
20989
21258
  } catch {
20990
21259
  return void 0;
20991
21260
  }
20992
21261
  }
20993
21262
  function writeSyncedName(resolvedFile, name) {
20994
- if (!existsSync42(resolvedFile)) return;
21263
+ if (!existsSync43(resolvedFile)) return;
20995
21264
  let raw;
20996
21265
  try {
20997
- raw = JSON.parse(readFileSync40(resolvedFile, "utf8"));
21266
+ raw = JSON.parse(readFileSync41(resolvedFile, "utf8"));
20998
21267
  } catch {
20999
21268
  return;
21000
21269
  }
21001
21270
  if (raw.shipName === name) return;
21002
21271
  raw.shipName = name;
21003
- mkdirSync30(dirname25(resolvedFile), { recursive: true });
21272
+ mkdirSync31(dirname26(resolvedFile), { recursive: true });
21004
21273
  const tmp = `${resolvedFile}.tmp${process.pid}`;
21005
- writeFileSync33(tmp, `${JSON.stringify(raw, null, 2)}
21274
+ writeFileSync34(tmp, `${JSON.stringify(raw, null, 2)}
21006
21275
  `);
21007
- renameSync6(tmp, resolvedFile);
21276
+ renameSync7(tmp, resolvedFile);
21008
21277
  }
21009
21278
  async function reconcileShipName(i) {
21010
21279
  let local = i.ship.name;
21011
21280
  try {
21012
- local = shipNameOfYaml(readFileSync40(i.configFile, "utf8")) ?? local;
21281
+ local = shipNameOfYaml(readFileSync41(i.configFile, "utf8")) ?? local;
21013
21282
  } catch {
21014
21283
  }
21015
21284
  const resolvedFile = resolvedPathFor(i.stateDir, i.route);
@@ -21033,8 +21302,8 @@ async function reconcileShipName(i) {
21033
21302
  }
21034
21303
  if (result.status !== "ok") return result;
21035
21304
  if (result.action === "adopt" || result.action === "row-wins") {
21036
- const text2 = readFileSync40(i.configFile, "utf8");
21037
- writeFileSync33(i.configFile, setShipNameInYaml(text2, result.name));
21305
+ const text2 = readFileSync41(i.configFile, "utf8");
21306
+ writeFileSync34(i.configFile, setShipNameInYaml(text2, result.name));
21038
21307
  i.ship.name = result.name;
21039
21308
  if (result.action === "row-wins") {
21040
21309
  i.emit?.warn(
@@ -21079,11 +21348,11 @@ async function reconcileRouteShipName(o) {
21079
21348
  }
21080
21349
 
21081
21350
  // src/mirror-contract.ts
21082
- import { existsSync as existsSync43 } from "fs";
21351
+ import { existsSync as existsSync44 } from "fs";
21083
21352
 
21084
21353
  // src/passenger-mirror.ts
21085
- import { mkdirSync as mkdirSync31 } from "fs";
21086
- import { dirname as dirname26 } from "path";
21354
+ import { mkdirSync as mkdirSync32 } from "fs";
21355
+ import { dirname as dirname27 } from "path";
21087
21356
  function mirrorRepoOf(spec) {
21088
21357
  const fromOrigin = spec.originUrl ? parseRemote(spec.originUrl) : null;
21089
21358
  if (fromOrigin) return fromOrigin;
@@ -21101,9 +21370,9 @@ async function materializeMirrorCheckouts(specs, cacheFor = (s) => new SandboxCa
21101
21370
  continue;
21102
21371
  }
21103
21372
  try {
21104
- const parent = dirname26(spec.dir);
21105
- mkdirSync31(parent, { recursive: true });
21106
- mkdirSync31(spec.dir, { recursive: true });
21373
+ const parent = dirname27(spec.dir);
21374
+ mkdirSync32(parent, { recursive: true });
21375
+ mkdirSync32(spec.dir, { recursive: true });
21107
21376
  const r = await cacheFor(spec).materialize(repo, spec.base, parent, spec.name);
21108
21377
  out.push({ ...base, action: r.changed ? "updated" : "unchanged", detail: r.tip });
21109
21378
  } catch (e) {
@@ -21120,7 +21389,7 @@ function mirrorOutcome(m) {
21120
21389
 
21121
21390
  // src/mirror-contract.ts
21122
21391
  function lacksCheckout(ship, dir) {
21123
- return ship.runner === "sandbox" && !existsSync43(dir) && !remoteOf(dir);
21392
+ return ship.runner === "sandbox" && !existsSync44(dir) && !remoteOf(dir);
21124
21393
  }
21125
21394
  function skipsHostCheckout(ship) {
21126
21395
  return ship.runner === "sandbox";
@@ -21201,18 +21470,18 @@ function explainRefusal(readable, unreadable) {
21201
21470
 
21202
21471
  // src/ssh-keys.ts
21203
21472
  import { execFileSync as execFileSync13 } from "child_process";
21204
- import { existsSync as existsSync44, mkdirSync as mkdirSync32, readFileSync as readFileSync41, chmodSync as chmodSync3 } from "fs";
21205
- import { dirname as dirname27, join as join45 } from "path";
21473
+ import { existsSync as existsSync45, mkdirSync as mkdirSync33, readFileSync as readFileSync42, chmodSync as chmodSync3 } from "fs";
21474
+ import { dirname as dirname28, join as join47 } from "path";
21206
21475
  var SshKeyError = class extends Error {
21207
21476
  };
21208
21477
  function shipSshKeyPathFor(stateDir) {
21209
- return join45(stateDir, "ssh", "id_ed25519");
21478
+ return join47(stateDir, "ssh", "id_ed25519");
21210
21479
  }
21211
21480
  function ensureShipSshKeypair(stateDir) {
21212
21481
  const privateKeyPath = shipSshKeyPathFor(stateDir);
21213
21482
  const publicKeyPath = `${privateKeyPath}.pub`;
21214
- if (!existsSync44(privateKeyPath)) {
21215
- mkdirSync32(dirname27(privateKeyPath), { recursive: true });
21483
+ if (!existsSync45(privateKeyPath)) {
21484
+ mkdirSync33(dirname28(privateKeyPath), { recursive: true });
21216
21485
  try {
21217
21486
  execFileSync13("ssh-keygen", [
21218
21487
  "-t",
@@ -21232,10 +21501,10 @@ function ensureShipSshKeypair(stateDir) {
21232
21501
  }
21233
21502
  chmodSync3(privateKeyPath, 384);
21234
21503
  }
21235
- if (!existsSync44(publicKeyPath)) {
21504
+ if (!existsSync45(publicKeyPath)) {
21236
21505
  throw new SshKeyError(`${privateKeyPath} exists but ${publicKeyPath} does not \u2014 regenerate or restore it`);
21237
21506
  }
21238
- const publicKey = readFileSync41(publicKeyPath, "utf8").trim();
21507
+ const publicKey = readFileSync42(publicKeyPath, "utf8").trim();
21239
21508
  return { privateKeyPath, publicKeyPath, publicKey };
21240
21509
  }
21241
21510
  function sshKeygenAvailable() {
@@ -21250,7 +21519,7 @@ function sshKeygenAvailable() {
21250
21519
  // src/periscope-idle.ts
21251
21520
  import { execFileSync as execFileSync14 } from "child_process";
21252
21521
  import { statSync as statSync12 } from "fs";
21253
- import { join as join46 } from "path";
21522
+ import { join as join48 } from "path";
21254
21523
  var MAX_SCANNED_FILES = 2e4;
21255
21524
  function newestWorktreeMtime(root) {
21256
21525
  const a = newestTrackedMtime(root);
@@ -21275,7 +21544,7 @@ function newestTrackedMtime(root) {
21275
21544
  if (!rel) continue;
21276
21545
  if (++scanned > MAX_SCANNED_FILES) break;
21277
21546
  try {
21278
- const m = statSync12(join46(root, rel)).mtimeMs;
21547
+ const m = statSync12(join48(root, rel)).mtimeMs;
21279
21548
  if (newest === null || m > newest) newest = m;
21280
21549
  } catch {
21281
21550
  }
@@ -21349,8 +21618,8 @@ async function runPeriscopeIdlePass(d) {
21349
21618
  }
21350
21619
 
21351
21620
  // src/periscope-cmd.ts
21352
- import { existsSync as existsSync45, mkdirSync as mkdirSync33, readFileSync as readFileSync42, rmSync as rmSync20, writeFileSync as writeFileSync34 } from "fs";
21353
- import { join as join47 } from "path";
21621
+ import { existsSync as existsSync46, mkdirSync as mkdirSync34, readFileSync as readFileSync43, rmSync as rmSync21, writeFileSync as writeFileSync35 } from "fs";
21622
+ import { join as join49 } from "path";
21354
21623
  var PeriscopeError = class extends Error {
21355
21624
  };
21356
21625
  var LivePeriscopeError = class extends PeriscopeError {
@@ -21360,22 +21629,22 @@ var LivePeriscopeError = class extends PeriscopeError {
21360
21629
  this.data = { refused: "live_periscope_exists", ...live };
21361
21630
  }
21362
21631
  };
21363
- var priorDir = (stateDir) => join47(stateDir, "periscope-priors");
21364
- var priorPath = (stateDir, ticketRecordId) => join47(priorDir(stateDir), `${ticketRecordId}.json`);
21632
+ var priorDir = (stateDir) => join49(stateDir, "periscope-priors");
21633
+ var priorPath = (stateDir, ticketRecordId) => join49(priorDir(stateDir), `${ticketRecordId}.json`);
21365
21634
  function removePeriscopePrior(stateDir, ticketRecordId) {
21366
- rmSync20(priorPath(stateDir, ticketRecordId), { force: true });
21635
+ rmSync21(priorPath(stateDir, ticketRecordId), { force: true });
21367
21636
  }
21368
21637
  function writePeriscopePrior(stateDir, ticketRecordId, prior) {
21369
21638
  try {
21370
- mkdirSync33(priorDir(stateDir), { recursive: true });
21371
- writeFileSync34(priorPath(stateDir, ticketRecordId), JSON.stringify(prior));
21639
+ mkdirSync34(priorDir(stateDir), { recursive: true });
21640
+ writeFileSync35(priorPath(stateDir, ticketRecordId), JSON.stringify(prior));
21372
21641
  } catch {
21373
21642
  }
21374
21643
  }
21375
21644
  function readPeriscopePrior(stateDir, ticketRecordId) {
21376
21645
  try {
21377
21646
  const p = priorPath(stateDir, ticketRecordId);
21378
- return existsSync45(p) ? JSON.parse(readFileSync42(p, "utf8")) : void 0;
21647
+ return existsSync46(p) ? JSON.parse(readFileSync43(p, "utf8")) : void 0;
21379
21648
  } catch {
21380
21649
  return void 0;
21381
21650
  }
@@ -21944,7 +22213,7 @@ function latestMtime(path) {
21944
22213
  if (!stat2.isDirectory()) return 0;
21945
22214
  let latest = stat2.mtimeMs;
21946
22215
  for (const entry of readdirSync14(path, { withFileTypes: true })) {
21947
- latest = Math.max(latest, latestMtime(join48(path, entry.name)));
22216
+ latest = Math.max(latest, latestMtime(join50(path, entry.name)));
21948
22217
  }
21949
22218
  return latest;
21950
22219
  }
@@ -21953,10 +22222,10 @@ function computeTreeSignature(paths) {
21953
22222
  }
21954
22223
  function makeStaleChecker(paths, opts = {}) {
21955
22224
  const initial = computeTreeSignature(paths);
21956
- return () => computeTreeSignature(paths) !== initial || opts.reloadSentinel !== void 0 && existsSync46(opts.reloadSentinel);
22225
+ return () => computeTreeSignature(paths) !== initial || opts.reloadSentinel !== void 0 && existsSync47(opts.reloadSentinel);
21957
22226
  }
21958
22227
  function reloadSentinelFor(stateDir) {
21959
- return join48(stateDir, "reload-requested");
22228
+ return join50(stateDir, "reload-requested");
21960
22229
  }
21961
22230
  function readReloadRequestedAt(stateDir) {
21962
22231
  try {
@@ -21966,17 +22235,17 @@ function readReloadRequestedAt(stateDir) {
21966
22235
  }
21967
22236
  }
21968
22237
  function daemonStampFor(stateDir) {
21969
- return join48(stateDir, "daemon.started");
22238
+ return join50(stateDir, "daemon.started");
21970
22239
  }
21971
22240
  function noteDaemonStarted(stateDir, now = Date.now()) {
21972
- mkdirSync34(stateDir, { recursive: true });
21973
- rmSync21(reloadSentinelFor(stateDir), { force: true });
21974
- writeFileSync35(daemonStampFor(stateDir), `${JSON.stringify({ pid: process.pid, startedAt: now })}
22241
+ mkdirSync35(stateDir, { recursive: true });
22242
+ rmSync22(reloadSentinelFor(stateDir), { force: true });
22243
+ writeFileSync36(daemonStampFor(stateDir), `${JSON.stringify({ pid: process.pid, startedAt: now })}
21975
22244
  `);
21976
22245
  }
21977
22246
  function readDaemonStarted(stateDir) {
21978
22247
  try {
21979
- const v = JSON.parse(readFileSync43(daemonStampFor(stateDir), "utf8")).startedAt;
22248
+ const v = JSON.parse(readFileSync44(daemonStampFor(stateDir), "utf8")).startedAt;
21980
22249
  return typeof v === "number" ? v : null;
21981
22250
  } catch {
21982
22251
  return null;
@@ -22832,7 +23101,7 @@ function parseSystemctlShow(text2) {
22832
23101
  }
22833
23102
  function lastLogLine(path, read = (p) => {
22834
23103
  try {
22835
- return readFileSync44(p, "utf8");
23104
+ return readFileSync45(p, "utf8");
22836
23105
  } catch {
22837
23106
  return null;
22838
23107
  }
@@ -22859,7 +23128,7 @@ function probeDaemonUnit(o) {
22859
23128
  const r = spawnSync11(cmd[0], cmd.slice(1), { encoding: "utf8" });
22860
23129
  return r.error ? null : { status: r.status, stdout: r.stdout ?? "" };
22861
23130
  });
22862
- const installed = o.plan.unitPaths.some((p) => existsSync47(p));
23131
+ const installed = o.plan.unitPaths.some((p) => existsSync48(p));
22863
23132
  let reading = null;
22864
23133
  if (installed && o.plan.mechanism === "launchd") {
22865
23134
  const r = run4(["launchctl", "print", `gui/${o.uid}/${o.label}`]);
@@ -22909,7 +23178,7 @@ function daemonProblem(d, route2) {
22909
23178
  }
22910
23179
  function readDaemonStamp(stateDir) {
22911
23180
  try {
22912
- const v = JSON.parse(readFileSync44(daemonStampFor(stateDir), "utf8"));
23181
+ const v = JSON.parse(readFileSync45(daemonStampFor(stateDir), "utf8"));
22913
23182
  if (typeof v.startedAt !== "number") return null;
22914
23183
  return typeof v.pid === "number" ? { pid: v.pid, startedAt: v.startedAt } : { startedAt: v.startedAt };
22915
23184
  } catch {
@@ -22918,15 +23187,15 @@ function readDaemonStamp(stateDir) {
22918
23187
  }
22919
23188
 
22920
23189
  // src/daemon-start-failure.ts
22921
- import { existsSync as existsSync48, mkdirSync as mkdirSync35, readFileSync as readFileSync45, unlinkSync as unlinkSync4, writeFileSync as writeFileSync36 } from "fs";
22922
- import { dirname as dirname28, join as join49 } from "path";
23190
+ import { existsSync as existsSync49, mkdirSync as mkdirSync36, readFileSync as readFileSync46, unlinkSync as unlinkSync4, writeFileSync as writeFileSync37 } from "fs";
23191
+ import { dirname as dirname29, join as join51 } from "path";
22923
23192
  var DAEMON_START_FAILED_KEY = "daemon_start_failed";
22924
23193
  var START_FAILURE_BACKOFF_MS = 6e4;
22925
23194
  var BACKOFF_AFTER_FAILURES = 2;
22926
- var fileFor3 = (stateDir) => join49(stateDir, ".daemon-start-failure.json");
23195
+ var fileFor3 = (stateDir) => join51(stateDir, ".daemon-start-failure.json");
22927
23196
  function readStartFailure(stateDir) {
22928
23197
  try {
22929
- const parsed = JSON.parse(readFileSync45(fileFor3(stateDir), "utf8"));
23198
+ const parsed = JSON.parse(readFileSync46(fileFor3(stateDir), "utf8"));
22930
23199
  return typeof parsed.reason === "string" && typeof parsed.count === "number" ? { reason: parsed.reason, count: parsed.count, firstAt: String(parsed.firstAt), lastAt: String(parsed.lastAt) } : null;
22931
23200
  } catch {
22932
23201
  return null;
@@ -22942,8 +23211,8 @@ function noteStartFailure(stateDir, reason, nowMs = Date.now()) {
22942
23211
  firstAt: same ? previous.firstAt : nowIso,
22943
23212
  lastAt: nowIso
22944
23213
  };
22945
- mkdirSync35(stateDir, { recursive: true });
22946
- writeFileSync36(fileFor3(stateDir), JSON.stringify(record));
23214
+ mkdirSync36(stateDir, { recursive: true });
23215
+ writeFileSync37(fileFor3(stateDir), JSON.stringify(record));
22947
23216
  return record;
22948
23217
  }
22949
23218
  function startFailureDelayMs(count) {
@@ -22957,7 +23226,7 @@ function startFailureItem(record, o = {}) {
22957
23226
  return { kind: "daemon_start_failed", key: DAEMON_START_FAILED_KEY, message: parts.join(". ").replace(/\.\./g, "."), since: record.firstAt };
22958
23227
  }
22959
23228
  function clearStartFailure(state, stateDir) {
22960
- if (existsSync48(fileFor3(stateDir))) {
23229
+ if (existsSync49(fileFor3(stateDir))) {
22961
23230
  try {
22962
23231
  unlinkSync4(fileFor3(stateDir));
22963
23232
  } catch {
@@ -22984,7 +23253,7 @@ async function reportStartFailure(o) {
22984
23253
  return delay;
22985
23254
  }
22986
23255
  function fallbackStateDir(configFile) {
22987
- return join49(dirname28(configFile), "state");
23256
+ return join51(dirname29(configFile), "state");
22988
23257
  }
22989
23258
 
22990
23259
  // src/projects-cmd.ts
@@ -23098,8 +23367,8 @@ function runForge(a, io) {
23098
23367
 
23099
23368
  // src/release-sandbox.ts
23100
23369
  import { execFile as execFile5 } from "child_process";
23101
- import { mkdirSync as mkdirSync36, writeFileSync as writeFileSync37 } from "fs";
23102
- import { dirname as dirname29 } from "path";
23370
+ import { mkdirSync as mkdirSync37, writeFileSync as writeFileSync38 } from "fs";
23371
+ import { dirname as dirname30 } from "path";
23103
23372
  import { promisify as promisify4 } from "util";
23104
23373
  var execFileP4 = promisify4(execFile5);
23105
23374
  var RELEASE_CLONE_DEPTH = 50;
@@ -23145,8 +23414,8 @@ async function openReleaseSandbox(o) {
23145
23414
  if (!policyFile) {
23146
23415
  generated = generateSandboxPolicy({ mirrorDir: cfg.mirrorDir, workDir: cfg.workDir, ...o.policy });
23147
23416
  policyFile = o.policyFile;
23148
- mkdirSync36(dirname29(policyFile), { recursive: true });
23149
- writeFileSync37(policyFile, generated.yaml, { mode: 384 });
23417
+ mkdirSync37(dirname30(policyFile), { recursive: true });
23418
+ writeFileSync38(policyFile, generated.yaml, { mode: 384 });
23150
23419
  }
23151
23420
  const secrets = { ...process.env };
23152
23421
  const secretKeys = [];
@@ -23312,7 +23581,7 @@ function missingReleaserWarning(repo, release, ships, now = Date.now()) {
23312
23581
  }
23313
23582
 
23314
23583
  // src/watch.ts
23315
- import { watch as watchFile, existsSync as existsSync49, statSync as statSync14, openSync as openSync5, readSync as readSync2, closeSync as closeSync5 } from "fs";
23584
+ import { watch as watchFile, existsSync as existsSync50, statSync as statSync14, openSync as openSync5, readSync as readSync2, closeSync as closeSync5 } from "fs";
23316
23585
  var E = "\x1B[";
23317
23586
  var dim = (s) => `${E}2m${s}${E}0m`;
23318
23587
  var bold = (s) => `${E}1m${s}${E}0m`;
@@ -23413,7 +23682,7 @@ function renderHeaders(states, now = Date.now()) {
23413
23682
  return states.map((s) => renderHeader(s, now)).join("");
23414
23683
  }
23415
23684
  function readFrom(file, from) {
23416
- if (!existsSync49(file)) return { events: [], offset: from };
23685
+ if (!existsSync50(file)) return { events: [], offset: from };
23417
23686
  const size = statSync14(file).size;
23418
23687
  if (size < from) return readFrom(file, 0);
23419
23688
  if (size === from) return { events: [], offset: from };
@@ -24184,8 +24453,8 @@ function describeCapability(i) {
24184
24453
  }
24185
24454
 
24186
24455
  // src/agents-sync-run.ts
24187
- import { existsSync as existsSync50, mkdirSync as mkdirSync37, readFileSync as readFileSync46, writeFileSync as writeFileSync38 } from "fs";
24188
- import { dirname as dirname30 } from "path";
24456
+ import { existsSync as existsSync51, mkdirSync as mkdirSync38, readFileSync as readFileSync47, writeFileSync as writeFileSync39 } from "fs";
24457
+ import { dirname as dirname31 } from "path";
24189
24458
  async function runAgentsSync(target, o) {
24190
24459
  const dryRun = o.dryRun ?? false;
24191
24460
  const force = o.force ?? false;
@@ -24220,12 +24489,12 @@ async function runAgentsSync(target, o) {
24220
24489
  for (const w of skillResult?.warnings ?? []) o.warn(`warning: ${w}`);
24221
24490
  if (!dryRun) {
24222
24491
  const resolvedPath = resolvedPathFor(o.stateDir, target.route);
24223
- const raw = existsSync50(resolvedPath) ? JSON.parse(readFileSync46(resolvedPath, "utf8")) : {};
24492
+ const raw = existsSync51(resolvedPath) ? JSON.parse(readFileSync47(resolvedPath, "utf8")) : {};
24224
24493
  raw.agentPersonas = personaResult.agentPersonas;
24225
24494
  if (skillResult) raw.agentSkills = skillResult.agentSkills;
24226
24495
  if (personaResult.releaseAgentId) raw.releaseAgentId = personaResult.releaseAgentId;
24227
- mkdirSync37(dirname30(resolvedPath), { recursive: true });
24228
- writeFileSync38(resolvedPath, `${JSON.stringify(raw, null, 2)}
24496
+ mkdirSync38(dirname31(resolvedPath), { recursive: true });
24497
+ writeFileSync39(resolvedPath, `${JSON.stringify(raw, null, 2)}
24229
24498
  `);
24230
24499
  if (target.resolved) {
24231
24500
  target.resolved.agentPersonas = personaResult.agentPersonas;
@@ -24362,7 +24631,7 @@ async function showLogEntry(route2, entryId, opts = {}) {
24362
24631
 
24363
24632
  // src/repos-check.ts
24364
24633
  import { spawnSync as spawnSync12 } from "child_process";
24365
- import { readFileSync as readFileSync47 } from "fs";
24634
+ import { readFileSync as readFileSync48 } from "fs";
24366
24635
  import { basename as basename11 } from "path";
24367
24636
  var POSIX_SHELL = /^(?:ba|z|da|k|a|mk)?sh$|^fish$/;
24368
24637
  function checkHookSyntax(script, shell) {
@@ -24403,7 +24672,7 @@ function checkRepoSpec(dir, opts = {}) {
24403
24672
  }
24404
24673
  let parsed;
24405
24674
  try {
24406
- parsed = parseRepoConfig(readFileSync47(file, "utf8"), file);
24675
+ parsed = parseRepoConfig(readFileSync48(file, "utf8"), file);
24407
24676
  } catch (e) {
24408
24677
  if (!(e instanceof RepoConfigError)) throw e;
24409
24678
  return { ...empty, file, error: e.message, exitCode: 1 };
@@ -24867,7 +25136,7 @@ ${run4.err}` });
24867
25136
  }
24868
25137
 
24869
25138
  // src/sample-ticket.ts
24870
- import { basename as basename12, dirname as dirname31, join as join50 } from "path";
25139
+ import { basename as basename12, dirname as dirname32, join as join52 } from "path";
24871
25140
  var SAMPLE_REPO = "crew-sample";
24872
25141
  var SAMPLE_REMOTE = `local/${SAMPLE_REPO}`;
24873
25142
  var SAMPLE_MARKER = "sample: true";
@@ -24890,8 +25159,8 @@ has something safe to work on: its test and build hooks always pass, it has no
24890
25159
  remote, and \`crew sample-ticket --remove\` deletes it.
24891
25160
  `;
24892
25161
  function sampleDir(existing, reposBase, workspace) {
24893
- if (existing.length > 0) return join50(dirname31(existing[0]), SAMPLE_REPO);
24894
- return join50(reposBase, workspace, SAMPLE_REPO);
25162
+ if (existing.length > 0) return join52(dirname32(existing[0]), SAMPLE_REPO);
25163
+ return join52(reposBase, workspace, SAMPLE_REPO);
24895
25164
  }
24896
25165
  var SAMPLE_TITLE = "Sample: add a documented `greet` function with a test";
24897
25166
  function sampleDescription() {
@@ -24935,8 +25204,8 @@ function planSampleTicket(i) {
24935
25204
  }
24936
25205
 
24937
25206
  // src/worktree-sweep.ts
24938
- import { existsSync as existsSync51, readFileSync as readFileSync48, readdirSync as readdirSync15 } from "fs";
24939
- import { basename as basename13, dirname as dirname32, join as join51, resolve as resolve5 } from "path";
25207
+ import { existsSync as existsSync52, readFileSync as readFileSync49, readdirSync as readdirSync15 } from "fs";
25208
+ import { basename as basename13, dirname as dirname33, join as join53, resolve as resolve5 } from "path";
24940
25209
  function planWorktreeSweep(target, tickets, contract) {
24941
25210
  const terminal = new Set(contract.statuses.resolved.filter((s) => s !== contract.statuses.verified));
24942
25211
  const verified = contract.statuses.verified;
@@ -25000,7 +25269,7 @@ function worktreeTicketNumbers(target) {
25000
25269
  return [...nums];
25001
25270
  }
25002
25271
  function siblingWorktreeDirs(target) {
25003
- const parent = dirname32(target.dir.replace(/[/\\]+$/, ""));
25272
+ const parent = dirname33(target.dir.replace(/[/\\]+$/, ""));
25004
25273
  const stem = `${basename13(target.dir.replace(/[/\\]+$/, ""))}-`;
25005
25274
  const registered = new Set(worktrees(target.dir).map((w) => resolve5(w.path)));
25006
25275
  let names;
@@ -25013,7 +25282,7 @@ function siblingWorktreeDirs(target) {
25013
25282
  for (const name of names) {
25014
25283
  if (!name.startsWith(stem)) continue;
25015
25284
  const m = DIR_NUMBER_SUFFIXED.exec(name);
25016
- const path = join51(parent, name);
25285
+ const path = join53(parent, name);
25017
25286
  if (m && !registered.has(resolve5(path))) out.push({ path, number: m[1] });
25018
25287
  }
25019
25288
  return out;
@@ -25048,7 +25317,7 @@ async function applyWorktreeSweep(cwd, actions, dryRun, log, remote = "origin",
25048
25317
  let removed = 0;
25049
25318
  let keptBranches = 0;
25050
25319
  for (const a of actions) {
25051
- if (!dryRun && base && !a.keepBranch && existsSync51(a.path) && isHandBackMerge(a.path, base)) {
25320
+ if (!dryRun && base && !a.keepBranch && existsSync52(a.path) && isHandBackMerge(a.path, base)) {
25052
25321
  if (gitOk(a.path, ["merge", "--abort"]) !== null) {
25053
25322
  log.emit(
25054
25323
  `abandoned the hand-back merge of ${base} in ${a.path}: ${a.ticket.issue_id} deployed without it`,
@@ -25056,7 +25325,7 @@ async function applyWorktreeSweep(cwd, actions, dryRun, log, remote = "origin",
25056
25325
  );
25057
25326
  }
25058
25327
  }
25059
- if (!dryRun && existsSync51(a.path)) {
25328
+ if (!dryRun && existsSync52(a.path)) {
25060
25329
  let dirty = false;
25061
25330
  try {
25062
25331
  dirty = status(a.path).length > 0;
@@ -25067,7 +25336,7 @@ async function applyWorktreeSweep(cwd, actions, dryRun, log, remote = "origin",
25067
25336
  continue;
25068
25337
  }
25069
25338
  }
25070
- if (!dryRun && a.requirePushed && a.branch && existsSync51(a.path) && remoteConfigured(cwd, remote) && worktreeHoldsUnpushed(a.path, remote)) {
25339
+ if (!dryRun && a.requirePushed && a.branch && existsSync52(a.path) && remoteConfigured(cwd, remote) && worktreeHoldsUnpushed(a.path, remote)) {
25071
25340
  refuse2(a, "unpushed commits", `${a.branch} has commits that are not on ${remote}`);
25072
25341
  continue;
25073
25342
  }
@@ -25116,7 +25385,7 @@ function isHandBackMerge(path, base) {
25116
25385
  if (!msgPath) return false;
25117
25386
  let first;
25118
25387
  try {
25119
- first = readFileSync48(resolve5(path, msgPath), "utf8").split("\n")[0] ?? "";
25388
+ first = readFileSync49(resolve5(path, msgPath), "utf8").split("\n")[0] ?? "";
25120
25389
  } catch {
25121
25390
  return false;
25122
25391
  }
@@ -25221,14 +25490,14 @@ function applyRemoteBranchCleanup(cwd, remote, branches2, dryRun, log) {
25221
25490
  }
25222
25491
 
25223
25492
  // src/stream-sweep.ts
25224
- import { existsSync as existsSync52, readdirSync as readdirSync16, rmSync as rmSync22, statSync as statSync15 } from "fs";
25225
- import { join as join52 } from "path";
25493
+ import { existsSync as existsSync53, readdirSync as readdirSync16, rmSync as rmSync23, statSync as statSync15 } from "fs";
25494
+ import { join as join54 } from "path";
25226
25495
  var DAY_MS2 = 24 * 60 * 60 * 1e3;
25227
25496
  function planStreamSweep(stateDir, retentionDays, now = Date.now()) {
25228
- const dir = join52(stateDir, "streams");
25229
- if (!existsSync52(dir)) return [];
25497
+ const dir = join54(stateDir, "streams");
25498
+ if (!existsSync53(dir)) return [];
25230
25499
  const cutoff = now - retentionDays * DAY_MS2;
25231
- return readdirSync16(dir).map((name) => join52(dir, name)).filter((path) => {
25500
+ return readdirSync16(dir).map((name) => join54(dir, name)).filter((path) => {
25232
25501
  try {
25233
25502
  return statSync15(path).mtimeMs < cutoff;
25234
25503
  } catch {
@@ -25244,7 +25513,7 @@ function applyStreamSweep(paths, dryRun, log) {
25244
25513
  continue;
25245
25514
  }
25246
25515
  try {
25247
- rmSync22(path, { force: true });
25516
+ rmSync23(path, { force: true });
25248
25517
  removed++;
25249
25518
  log.emit(`removed stream artifact ${path}`, { step: "worktree" });
25250
25519
  } catch (e) {
@@ -25254,9 +25523,9 @@ function applyStreamSweep(paths, dryRun, log) {
25254
25523
  return removed;
25255
25524
  }
25256
25525
  function planEventsSweep(stateDir, retentionDays, now = Date.now()) {
25257
- if (!existsSync52(stateDir)) return [];
25526
+ if (!existsSync53(stateDir)) return [];
25258
25527
  const cutoff = now - retentionDays * DAY_MS2;
25259
- return readdirSync16(stateDir).filter((name) => ROTATED_EVENTS_RE.test(name)).map((name) => join52(stateDir, name)).filter((path) => {
25528
+ return readdirSync16(stateDir).filter((name) => ROTATED_EVENTS_RE.test(name)).map((name) => join54(stateDir, name)).filter((path) => {
25260
25529
  try {
25261
25530
  return statSync15(path).mtimeMs < cutoff;
25262
25531
  } catch {
@@ -25266,7 +25535,7 @@ function planEventsSweep(stateDir, retentionDays, now = Date.now()) {
25266
25535
  }
25267
25536
 
25268
25537
  // src/cli.ts
25269
- import { realpathSync as realpathSync3, readFileSync as readFileSync51, existsSync as existsSync56, mkdirSync as mkdirSync41, writeFileSync as writeFileSync41, rmSync as rmSync25, unlinkSync as unlinkSync6, copyFileSync as copyFileSync2, renameSync as renameSync7, statSync as statSync17, readdirSync as readdirSync20 } from "fs";
25538
+ import { realpathSync as realpathSync3, readFileSync as readFileSync52, existsSync as existsSync57, mkdirSync as mkdirSync42, writeFileSync as writeFileSync42, rmSync as rmSync26, unlinkSync as unlinkSync6, copyFileSync as copyFileSync2, renameSync as renameSync8, statSync as statSync17, readdirSync as readdirSync20 } from "fs";
25270
25539
  import { createInterface } from "readline/promises";
25271
25540
 
25272
25541
  // src/periscope-resume.ts
@@ -25493,8 +25762,8 @@ async function unregisterEndpoint(workspaceId, info, d) {
25493
25762
  import { createServer as createHttpServer } from "http";
25494
25763
  import { spawn as spawn9 } from "child_process";
25495
25764
  import { randomBytes as randomBytes2 } from "crypto";
25496
- import { existsSync as existsSync53, mkdirSync as mkdirSync38, readFileSync as readFileSync49, writeFileSync as writeFileSync39, unlinkSync as unlinkSync5, readdirSync as readdirSync17 } from "fs";
25497
- import { join as join53 } from "path";
25765
+ import { existsSync as existsSync54, mkdirSync as mkdirSync39, readFileSync as readFileSync50, writeFileSync as writeFileSync40, unlinkSync as unlinkSync5, readdirSync as readdirSync17 } from "fs";
25766
+ import { join as join55 } from "path";
25498
25767
 
25499
25768
  // src/secret-compare.ts
25500
25769
  import { timingSafeEqual } from "crypto";
@@ -25587,21 +25856,21 @@ var defaultSpawn2 = (cmd, args, env) => {
25587
25856
  return child;
25588
25857
  };
25589
25858
  function syncDaemonStatePath(stateDir, workspaceId) {
25590
- return join53(stateDir, "passengers", `${workspaceId}-sync.json`);
25859
+ return join55(stateDir, "passengers", `${workspaceId}-sync.json`);
25591
25860
  }
25592
25861
  function readPersistedSyncDaemon(stateDir, workspaceId) {
25593
25862
  const path = syncDaemonStatePath(stateDir, workspaceId);
25594
- if (!existsSync53(path)) return void 0;
25863
+ if (!existsSync54(path)) return void 0;
25595
25864
  try {
25596
- return JSON.parse(readFileSync49(path, "utf8"));
25865
+ return JSON.parse(readFileSync50(path, "utf8"));
25597
25866
  } catch {
25598
25867
  return void 0;
25599
25868
  }
25600
25869
  }
25601
25870
  function writePersistedSyncDaemon(stateDir, state) {
25602
25871
  const path = syncDaemonStatePath(stateDir, state.workspaceId);
25603
- mkdirSync38(join53(stateDir, "passengers"), { recursive: true });
25604
- writeFileSync39(path, `${JSON.stringify(state, null, 2)}
25872
+ mkdirSync39(join55(stateDir, "passengers"), { recursive: true });
25873
+ writeFileSync40(path, `${JSON.stringify(state, null, 2)}
25605
25874
  `);
25606
25875
  }
25607
25876
  function removePersistedSyncDaemon(stateDir, workspaceId) {
@@ -25621,8 +25890,8 @@ function waitForExit(pid, alive, timeoutMs = 5e3) {
25621
25890
  }
25622
25891
  }
25623
25892
  function readAllPersistedSyncWorkspaceIds(stateDir) {
25624
- const dir = join53(stateDir, "passengers");
25625
- if (!existsSync53(dir)) return [];
25893
+ const dir = join55(stateDir, "passengers");
25894
+ if (!existsSync54(dir)) return [];
25626
25895
  const suffix = "-sync.json";
25627
25896
  return readdirSync17(dir).filter((f) => f.endsWith(suffix)).map((f) => f.slice(0, -suffix.length));
25628
25897
  }
@@ -25680,12 +25949,12 @@ function syncPassengerSyncDaemons(plans, cfg, stateDir, deps = {}) {
25680
25949
 
25681
25950
  // src/periscope-proxy.ts
25682
25951
  import { spawn as spawn10 } from "child_process";
25683
- import { appendFileSync as appendFileSync3, mkdirSync as mkdirSync39 } from "fs";
25952
+ import { appendFileSync as appendFileSync3, mkdirSync as mkdirSync40 } from "fs";
25684
25953
  import { createServer, request as httpRequest } from "http";
25685
25954
  import { request as httpsRequest } from "https";
25686
25955
  import { connect as netConnect } from "net";
25687
25956
  import { connect as tlsConnect } from "tls";
25688
- import { dirname as dirname33, isAbsolute as isAbsolute4 } from "path";
25957
+ import { dirname as dirname34, isAbsolute as isAbsolute4 } from "path";
25689
25958
  import { brotliDecompressSync, gunzipSync, inflateSync } from "zlib";
25690
25959
 
25691
25960
  // src/periscope-inspector.ts
@@ -25799,7 +26068,7 @@ function parsePointedBody(raw) {
25799
26068
  return entry;
25800
26069
  }
25801
26070
  function appendPointed(file, entry, now = /* @__PURE__ */ new Date()) {
25802
- mkdirSync39(dirname33(file), { recursive: true });
26071
+ mkdirSync40(dirname34(file), { recursive: true });
25803
26072
  appendFileSync3(file, `${JSON.stringify({ ...entry, at: now.toISOString() })}
25804
26073
  `);
25805
26074
  }
@@ -26088,7 +26357,7 @@ async function startWorktreeIntel(d) {
26088
26357
  }
26089
26358
 
26090
26359
  // src/contract-refusal.ts
26091
- import { join as join54 } from "path";
26360
+ import { join as join56 } from "path";
26092
26361
  function contractFixers(dir, baseRef, tickets, locate) {
26093
26362
  const out = [];
26094
26363
  for (const t of tickets) {
@@ -26100,7 +26369,7 @@ function contractFixers(dir, baseRef, tickets, locate) {
26100
26369
  const text2 = gitOk(dir, ["show", `${branch}:${file}`]);
26101
26370
  if (text2 === null) continue;
26102
26371
  try {
26103
- parseRepoConfig(text2, join54(dir, file));
26372
+ parseRepoConfig(text2, join56(dir, file));
26104
26373
  } catch (e) {
26105
26374
  if (e instanceof RepoConfigError) continue;
26106
26375
  throw e;
@@ -26115,18 +26384,18 @@ import { createHash as createHash11 } from "crypto";
26115
26384
  import {
26116
26385
  chmodSync as chmodSync4,
26117
26386
  closeSync as closeSync6,
26118
- existsSync as existsSync54,
26387
+ existsSync as existsSync55,
26119
26388
  fstatSync,
26120
26389
  openSync as openSync6,
26121
26390
  readSync as readSync3,
26122
26391
  readdirSync as readdirSync18,
26123
- rmSync as rmSync23,
26392
+ rmSync as rmSync24,
26124
26393
  statSync as statSync16,
26125
26394
  watch
26126
26395
  } from "fs";
26127
26396
  import { createConnection } from "net";
26128
26397
  import { createServer as createServer2 } from "http";
26129
- import { basename as basename14, dirname as dirname34, join as join55 } from "path";
26398
+ import { basename as basename14, dirname as dirname35, join as join57 } from "path";
26130
26399
  import { execFile as execFile6, spawn as spawn12 } from "child_process";
26131
26400
 
26132
26401
  // src/periscope-control.ts
@@ -26363,7 +26632,7 @@ function runCrew(args, onLine, timeoutMs = 20 * 6e4) {
26363
26632
  // src/control-api.ts
26364
26633
  var PAUSABLE = ["dev", "design", "qa"];
26365
26634
  var CONTROL_SOCKET_NAME = "control.sock";
26366
- var controlSocketFor = (stateDir) => join55(stateDir, CONTROL_SOCKET_NAME);
26635
+ var controlSocketFor = (stateDir) => join57(stateDir, CONTROL_SOCKET_NAME);
26367
26636
  var MAX_SOCKET_PATH = 100;
26368
26637
  var MAX_TAIL_BYTES = 1024 * 1024;
26369
26638
  var MAX_WAIT_SECONDS = 30;
@@ -26450,7 +26719,7 @@ function candidates(live, rotated) {
26450
26719
  const out = [live];
26451
26720
  if (!rotated) return out;
26452
26721
  try {
26453
- for (const n of readdirSync18(dirname34(live))) if (ROTATED_EVENTS_RE.test(n)) out.push(join55(dirname34(live), n));
26722
+ for (const n of readdirSync18(dirname35(live))) if (ROTATED_EVENTS_RE.test(n)) out.push(join57(dirname35(live), n));
26454
26723
  } catch {
26455
26724
  }
26456
26725
  return out;
@@ -26494,7 +26763,7 @@ function lastLines2(path, n) {
26494
26763
  }
26495
26764
  function readTail(live, opts) {
26496
26765
  const max = opts.maxBytes ?? MAX_TAIL_BYTES;
26497
- if (!existsSync54(live)) {
26766
+ if (!existsSync55(live)) {
26498
26767
  return { lines: [], cursor: opts.after ?? encodeCursor({ dev: 0, ino: 0, off: 0 }), reset: false };
26499
26768
  }
26500
26769
  const cur = opts.after ? decodeCursor(opts.after) : null;
@@ -26610,7 +26879,7 @@ async function tailReply(path, q2, rotated, abort) {
26610
26879
  const deadline = Date.now() + Math.min(wait, MAX_WAIT_SECONDS) * 1e3;
26611
26880
  let r = readTail(path, { after, tail: tail3, rotated });
26612
26881
  while (after && !r.lines.length && !r.reset && Date.now() < deadline && !abort.aborted) {
26613
- await waitForChange(dirname34(path), deadline - Date.now(), abort);
26882
+ await waitForChange(dirname35(path), deadline - Date.now(), abort);
26614
26883
  r = readTail(path, { after: r.cursor, rotated });
26615
26884
  }
26616
26885
  return reply2(200, r);
@@ -26650,8 +26919,8 @@ async function route(deps, method, url, req, abort) {
26650
26919
  if (p.startsWith("/streams/") && get2) {
26651
26920
  const run4 = decodeURIComponent(p.slice("/streams/".length));
26652
26921
  if (!RUN_NAME_RE.test(run4) || run4.includes("..") || /\.(pid|meta\.json|events\.jsonl)$/.test(run4)) return err2(400, "not a run name");
26653
- const file = join55(deps.stateDir, "streams", run4.endsWith(".jsonl") ? run4 : `${run4}.jsonl`);
26654
- if (!existsSync54(file)) return err2(404, "no such run");
26922
+ const file = join57(deps.stateDir, "streams", run4.endsWith(".jsonl") ? run4 : `${run4}.jsonl`);
26923
+ if (!existsSync55(file)) return err2(404, "no such run");
26655
26924
  return tailReply(file, url.searchParams, false, abort);
26656
26925
  }
26657
26926
  if ((p === "/pause" || p === "/resume") && post3) {
@@ -26681,7 +26950,7 @@ async function route(deps, method, url, req, abort) {
26681
26950
  if (known.includes(p) || p.startsWith("/streams/") || sched) return err2(405, "method not allowed");
26682
26951
  return err2(404, "not found");
26683
26952
  }
26684
- function send(res, r) {
26953
+ function send2(res, r) {
26685
26954
  if (r.stream) {
26686
26955
  res.writeHead(200, { "Content-Type": "application/x-ndjson", "Cache-Control": "no-store" });
26687
26956
  return r.stream((ev) => {
@@ -26696,7 +26965,7 @@ function send(res, r) {
26696
26965
  res.end(body);
26697
26966
  }
26698
26967
  async function socketIsStale(path) {
26699
- if (!existsSync54(path)) return false;
26968
+ if (!existsSync55(path)) return false;
26700
26969
  return new Promise((resolve8) => {
26701
26970
  const c = createConnection(path);
26702
26971
  c.once("connect", () => {
@@ -26714,8 +26983,8 @@ async function startControlServer(deps) {
26714
26983
  log(`control API not started: socket path is too long for a unix socket (${path})`);
26715
26984
  return null;
26716
26985
  }
26717
- if (await socketIsStale(path)) rmSync23(path, { force: true });
26718
- else if (existsSync54(path)) {
26986
+ if (await socketIsStale(path)) rmSync24(path, { force: true });
26987
+ else if (existsSync55(path)) {
26719
26988
  log(`control API not started: ${path} is in use by another process`);
26720
26989
  return null;
26721
26990
  }
@@ -26726,21 +26995,21 @@ async function startControlServer(deps) {
26726
26995
  try {
26727
26996
  const mcp = /^\/periscopes\/([^/]+)\/mcp\/?$/.exec(new URL(req.url ?? "/", "http://ship").pathname);
26728
26997
  if (mcp) {
26729
- if (!deps.periscopeMcp) return send(res, err2(404, "not found"));
26998
+ if (!deps.periscopeMcp) return send2(res, err2(404, "not found"));
26730
26999
  return await deps.periscopeMcp(req, res, decodeURIComponent(mcp[1]));
26731
27000
  }
26732
27001
  if (isPeriscopePath(new URL(req.url ?? "/", "http://ship").pathname.replace(/\/+$/, "") || "/")) {
26733
- return await send(res, await route(deps, req.method ?? "GET", new URL(req.url ?? "/", "http://ship"), req, abort.signal));
27002
+ return await send2(res, await route(deps, req.method ?? "GET", new URL(req.url ?? "/", "http://ship"), req, abort.signal));
26734
27003
  }
26735
27004
  const m = /^Bearer (.+)$/.exec(req.headers.authorization ?? "");
26736
27005
  const verdict = await deps.auth.verify(m?.[1]?.trim() ?? "");
26737
- if (verdict === "unauthorized") return send(res, err2(401, "invalid or revoked key"));
26738
- if (verdict === "forbidden") return send(res, err2(403, "this key does not belong to a workspace this ship serves"));
26739
- if (verdict === "unavailable") return send(res, err2(503, "could not verify the key right now"));
26740
- await send(res, await route(deps, req.method ?? "GET", new URL(req.url ?? "/", "http://ship"), req, abort.signal));
27006
+ if (verdict === "unauthorized") return send2(res, err2(401, "invalid or revoked key"));
27007
+ if (verdict === "forbidden") return send2(res, err2(403, "this key does not belong to a workspace this ship serves"));
27008
+ if (verdict === "unavailable") return send2(res, err2(503, "could not verify the key right now"));
27009
+ await send2(res, await route(deps, req.method ?? "GET", new URL(req.url ?? "/", "http://ship"), req, abort.signal));
26741
27010
  } catch (e) {
26742
27011
  log(`control API request failed: ${e.message}`);
26743
- if (!res.headersSent) send(res, err2(500, "internal error"));
27012
+ if (!res.headersSent) send2(res, err2(500, "internal error"));
26744
27013
  else res.end();
26745
27014
  }
26746
27015
  })();
@@ -26761,7 +27030,7 @@ async function startControlServer(deps) {
26761
27030
  path,
26762
27031
  close: () => new Promise((done) => {
26763
27032
  server.close(() => {
26764
- rmSync23(path, { force: true });
27033
+ rmSync24(path, { force: true });
26765
27034
  done();
26766
27035
  });
26767
27036
  })
@@ -26801,57 +27070,57 @@ function crewJson(args, timeoutMs = 6e4) {
26801
27070
 
26802
27071
  // src/periscope-mcp.ts
26803
27072
  import { lstat, mkdir, readdir, readFile, readlink, realpath, rm, stat, writeFile } from "fs/promises";
26804
- import { basename as basename15, dirname as dirname35, isAbsolute as isAbsolute5, join as join57, relative as relative2, resolve as resolve6, sep } from "path";
27073
+ import { basename as basename15, dirname as dirname36, isAbsolute as isAbsolute5, join as join59, relative as relative2, resolve as resolve6, sep } from "path";
26805
27074
  import { z } from "zod";
26806
27075
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
26807
27076
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
26808
27077
 
26809
27078
  // src/periscope-endpoints.ts
26810
27079
  import { randomBytes as randomBytes3 } from "crypto";
26811
- import { chmodSync as chmodSync5, existsSync as existsSync55, mkdirSync as mkdirSync40, readdirSync as readdirSync19, readFileSync as readFileSync50, rmSync as rmSync24, writeFileSync as writeFileSync40 } from "fs";
26812
- import { join as join56 } from "path";
26813
- var secretDir = (stateDir) => join56(stateDir, "periscope-mcp");
26814
- var secretFile = (stateDir, id) => join56(secretDir(stateDir), `${id}.json`);
26815
- var endpointDir = (stateDir) => join56(stateDir, "periscope-endpoints");
26816
- var endpointFile = (stateDir, id) => join56(endpointDir(stateDir), `${id}.json`);
27080
+ import { chmodSync as chmodSync5, existsSync as existsSync56, mkdirSync as mkdirSync41, readdirSync as readdirSync19, readFileSync as readFileSync51, rmSync as rmSync25, writeFileSync as writeFileSync41 } from "fs";
27081
+ import { join as join58 } from "path";
27082
+ var secretDir = (stateDir) => join58(stateDir, "periscope-mcp");
27083
+ var secretFile = (stateDir, id) => join58(secretDir(stateDir), `${id}.json`);
27084
+ var endpointDir = (stateDir) => join58(stateDir, "periscope-endpoints");
27085
+ var endpointFile = (stateDir, id) => join58(endpointDir(stateDir), `${id}.json`);
26817
27086
  function mintPeriscopeSecret(stateDir, ticketRecordId) {
26818
- mkdirSync40(secretDir(stateDir), { recursive: true, mode: 448 });
27087
+ mkdirSync41(secretDir(stateDir), { recursive: true, mode: 448 });
26819
27088
  const secret = randomBytes3(32).toString("base64url");
26820
27089
  const file = secretFile(stateDir, ticketRecordId);
26821
- writeFileSync40(file, `${JSON.stringify({ secret })}
27090
+ writeFileSync41(file, `${JSON.stringify({ secret })}
26822
27091
  `, { mode: 384 });
26823
27092
  chmodSync5(file, 384);
26824
27093
  return secret;
26825
27094
  }
26826
27095
  function readPeriscopeSecret(stateDir, ticketRecordId) {
26827
27096
  try {
26828
- const v = JSON.parse(readFileSync50(secretFile(stateDir, ticketRecordId), "utf8"));
27097
+ const v = JSON.parse(readFileSync51(secretFile(stateDir, ticketRecordId), "utf8"));
26829
27098
  return typeof v.secret === "string" && v.secret ? v.secret : void 0;
26830
27099
  } catch {
26831
27100
  return void 0;
26832
27101
  }
26833
27102
  }
26834
27103
  function removePeriscopeSecret(stateDir, ticketRecordId) {
26835
- rmSync24(secretFile(stateDir, ticketRecordId), { force: true });
27104
+ rmSync25(secretFile(stateDir, ticketRecordId), { force: true });
26836
27105
  }
26837
27106
  function readPeriscopeEndpoint(stateDir, ticketRecordId) {
26838
27107
  try {
26839
- return JSON.parse(readFileSync50(endpointFile(stateDir, ticketRecordId), "utf8"));
27108
+ return JSON.parse(readFileSync51(endpointFile(stateDir, ticketRecordId), "utf8"));
26840
27109
  } catch {
26841
27110
  return void 0;
26842
27111
  }
26843
27112
  }
26844
27113
  function writePeriscopeEndpoint(stateDir, rec) {
26845
- mkdirSync40(endpointDir(stateDir), { recursive: true });
26846
- writeFileSync40(endpointFile(stateDir, rec.ticketRecordId), `${JSON.stringify(rec, null, 2)}
27114
+ mkdirSync41(endpointDir(stateDir), { recursive: true });
27115
+ writeFileSync41(endpointFile(stateDir, rec.ticketRecordId), `${JSON.stringify(rec, null, 2)}
26847
27116
  `);
26848
27117
  }
26849
27118
  function removePeriscopeEndpointRecord(stateDir, ticketRecordId) {
26850
- rmSync24(endpointFile(stateDir, ticketRecordId), { force: true });
27119
+ rmSync25(endpointFile(stateDir, ticketRecordId), { force: true });
26851
27120
  }
26852
27121
  function listPeriscopeEndpoints(stateDir) {
26853
27122
  const dir = endpointDir(stateDir);
26854
- if (!existsSync55(dir)) return [];
27123
+ if (!existsSync56(dir)) return [];
26855
27124
  const out = [];
26856
27125
  for (const name of readdirSync19(dir)) {
26857
27126
  if (!name.endsWith(".json")) continue;
@@ -26939,10 +27208,10 @@ async function realAncestor(p) {
26939
27208
  }
26940
27209
  if (isLink) {
26941
27210
  if (++hops > 40) throw new PathRefusal(`too many symbolic links resolving ${p}`);
26942
- cur = resolve6(dirname35(cur), await readlink(cur));
27211
+ cur = resolve6(dirname36(cur), await readlink(cur));
26943
27212
  continue;
26944
27213
  }
26945
- const parent = dirname35(cur);
27214
+ const parent = dirname36(cur);
26946
27215
  if (parent === cur) throw new PathRefusal(`cannot resolve ${p}`);
26947
27216
  tail3.push(basename15(cur));
26948
27217
  cur = parent;
@@ -26954,13 +27223,13 @@ async function resolveInWorktree(root, requested) {
26954
27223
  let abs;
26955
27224
  if (isAbsolute5(requested)) {
26956
27225
  abs = resolve6(requested);
26957
- if (isInside(root, abs)) abs = join57(realRoot, relative2(root, abs));
27226
+ if (isInside(root, abs)) abs = join59(realRoot, relative2(root, abs));
26958
27227
  } else {
26959
27228
  abs = resolve6(realRoot, requested);
26960
27229
  }
26961
27230
  if (!isInside(realRoot, abs)) throw new PathRefusal(`${requested} is outside this periscope's worktree`);
26962
27231
  const { real, rest } = await realAncestor(abs);
26963
- const final = rest ? join57(real, rest) : real;
27232
+ const final = rest ? join59(real, rest) : real;
26964
27233
  if (!isInside(realRoot, final)) throw new PathRefusal(`${requested} is outside this periscope's worktree`);
26965
27234
  if (relative2(realRoot, final).split(sep).includes(".git")) throw new PathRefusal(".git is not reachable from a periscope");
26966
27235
  return final;
@@ -27028,7 +27297,7 @@ function createPeriscopeMcpServer(d, sc) {
27028
27297
  const entries = (await readdir(abs, { withFileTypes: true })).filter((e) => e.name !== ".git");
27029
27298
  const lines2 = await Promise.all(entries.map(async (e) => {
27030
27299
  if (e.isDirectory()) return `[DIR] ${e.name}`;
27031
- const size = (await lstat(join57(abs, e.name))).size;
27300
+ const size = (await lstat(join59(abs, e.name))).size;
27032
27301
  return `[FILE] ${e.name} (${size} bytes)`;
27033
27302
  }));
27034
27303
  return text(lines2.join("\n") || "(empty)");
@@ -27053,7 +27322,7 @@ function createPeriscopeMcpServer(d, sc) {
27053
27322
  if (Buffer.byteLength(content) > MAX_WRITE_BYTES) return text(`content exceeds ${MAX_WRITE_BYTES} bytes`, true);
27054
27323
  const abs = await inTree(path);
27055
27324
  if (abs === await realpath(root)) return text("path must name a file", true);
27056
- await mkdir(dirname35(abs), { recursive: true });
27325
+ await mkdir(dirname36(abs), { recursive: true });
27057
27326
  await inTree(path);
27058
27327
  await writeFile(abs, content);
27059
27328
  return text(`Wrote ${Buffer.byteLength(content)} bytes to ${await rel(abs)}`);
@@ -27093,8 +27362,8 @@ function createPeriscopeMcpServer(d, sc) {
27093
27362
  inputSchema: { path: z.string() },
27094
27363
  annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: false }
27095
27364
  }, async ({ path }) => {
27096
- const parent = await inTree(dirname35(path) === "" ? "." : dirname35(path));
27097
- const abs = join57(parent, basename15(path));
27365
+ const parent = await inTree(dirname36(path) === "" ? "." : dirname36(path));
27366
+ const abs = join59(parent, basename15(path));
27098
27367
  if (basename15(path) === ".git" || abs === parent) return text("path must name a file", true);
27099
27368
  const st = await lstat(abs).catch(() => void 0);
27100
27369
  if (!st) return text(`${path} does not exist`, true);
@@ -27215,7 +27484,7 @@ function findPeriscope(sidecars, segment) {
27215
27484
  }
27216
27485
 
27217
27486
  // src/cli.ts
27218
- var CREW_HOME = isCompiledBinary(import.meta.url) ? dirname36(process.execPath) : resolve7(dirname36(fileURLToPath2(import.meta.url)), "..");
27487
+ var CREW_HOME = isCompiledBinary(import.meta.url) ? dirname37(process.execPath) : resolve7(dirname37(fileURLToPath2(import.meta.url)), "..");
27219
27488
  var RELEASE_LOCK_TTL_MS = 20 * 60 * 1e3;
27220
27489
  var CYCLE_SECONDS2 = 120;
27221
27490
  var STALE_CYCLES = 3;
@@ -27585,7 +27854,7 @@ if (command === "provision") {
27585
27854
  process.exit(outcome.code);
27586
27855
  }
27587
27856
  if (command === "pool-member") {
27588
- const pool = poolConfigFrom(argv, process.env, () => readFileSync51(0, "utf8"));
27857
+ const pool = poolConfigFrom(argv, process.env, () => readFileSync52(0, "utf8"));
27589
27858
  if (typeof pool === "string") {
27590
27859
  process.stderr.write(`crew pool-member: ${pool}
27591
27860
  `);
@@ -27906,7 +28175,7 @@ if (command === "passenger-sync-daemon") {
27906
28175
  } else {
27907
28176
  const toleratesNoRoutes = command === "credential" || command === "forge" || command === "repos" || command === "ship" || command === "disconnect" && flag("reset") || command === "deprovision" || command === "connect" && flag("sign-out");
27908
28177
  const configless = command === "connect" && flag("sign-out") || command === "disconnect" && flag("reset") || command === "deprovision";
27909
- if (configless && !existsSync56(findConfigFile(CREW_HOME))) {
28178
+ if (configless && !existsSync57(findConfigFile(CREW_HOME))) {
27910
28179
  cfg = loadConfig(CREW_HOME, firstRunConfigPath(), { text: "ship: {}\n", allowNoRoutes: true });
27911
28180
  } else {
27912
28181
  cfg = loadConfig(CREW_HOME, void 0, toleratesNoRoutes ? { allowNoRoutes: true } : {});
@@ -27929,7 +28198,7 @@ if (command === "passenger-sync-daemon") {
27929
28198
  throw e;
27930
28199
  }
27931
28200
  if (command === "credential") {
27932
- const r = runCredential(positional[1], readFileSync51(0, "utf8"), cfg.ship.forges, cfg.ship.stateDir, process.env, !flag("no-miss"));
28201
+ const r = runCredential(positional[1], readFileSync52(0, "utf8"), cfg.ship.forges, cfg.ship.stateDir, process.env, !flag("no-miss"));
27933
28202
  process.stdout.write(r.out);
27934
28203
  process.stderr.write(r.err);
27935
28204
  process.exit(r.code);
@@ -27941,9 +28210,9 @@ if (command === "passenger-sync-daemon") {
27941
28210
  forges: cfg.ship.forges,
27942
28211
  stateDir: cfg.ship.stateDir,
27943
28212
  configFile: cfg.configFile,
27944
- readFile: (p) => readFileSync51(p, "utf8"),
27945
- writeFile: (p, t) => writeFileSync41(p, t),
27946
- stdin: () => readFileSync51(0, "utf8"),
28213
+ readFile: (p) => readFileSync52(p, "utf8"),
28214
+ writeFile: (p, t) => writeFileSync42(p, t),
28215
+ stdin: () => readFileSync52(0, "utf8"),
27947
28216
  env: process.env
27948
28217
  }
27949
28218
  );
@@ -28277,8 +28546,8 @@ if (command === "passenger-sync-daemon") {
28277
28546
  }
28278
28547
  if (host === "linux" && hasSystemd) {
28279
28548
  const label = labelFor(CREW_HOME, "run");
28280
- const staleTimer = join58(homedir11(), ".config", "systemd", "user", `${label}.timer`);
28281
- if (existsSync56(staleTimer)) {
28549
+ const staleTimer = join60(homedir11(), ".config", "systemd", "user", `${label}.timer`);
28550
+ if (existsSync57(staleTimer)) {
28282
28551
  process.stdout.write(
28283
28552
  `removing stale run timer from before the persistent-service cutover: ${staleTimer}${dryRun ? " (dry run)" : ""}
28284
28553
  `
@@ -28307,7 +28576,7 @@ if (command === "passenger-sync-daemon") {
28307
28576
  const { settled: doctorRepos, errors: refusedRepos } = await settleRepos(reposOf(c), (t) => t.name, (t) => resolveOneRepo(c, t));
28308
28577
  for (const e of refusedRepos) problems.push(`repo ${e.repo}: ${e.detail}`);
28309
28578
  for (const r of doctorRepos) {
28310
- if (!existsSync56(r.dir)) problems.push(`repo ${r.name}: ${r.dir} is missing on disk`);
28579
+ if (!existsSync57(r.dir)) problems.push(`repo ${r.name}: ${r.dir} is missing on disk`);
28311
28580
  if (!satisfies(host, r.config.platform)) problems.push(`repo ${r.name}: requires ${r.config.platform}, this host is ${host}`);
28312
28581
  readiness.push(...validateEffective(r.config).map((p) => `repo ${r.name}: ${p}`));
28313
28582
  }
@@ -28317,6 +28586,14 @@ if (command === "passenger-sync-daemon") {
28317
28586
  const mine = matchShipRows(ships, cfg.ship.name, doctorMachineId(cfg.ship.stateDir)).rows;
28318
28587
  if (mine.length !== 1) problems.push(`ship record: ${mine.length} rows named "${cfg.ship.name}"`);
28319
28588
  else if (mine[0].platform && mine[0].platform !== host) problems.push(`ship record: declares ${mine[0].platform}, this host is ${host}`);
28589
+ const fleet = ships.map((x) => x.platform ?? "").filter(isShipPlatform);
28590
+ if (fleet.length > 0) {
28591
+ for (const r of doctorRepos) {
28592
+ if (!fleet.some((p) => satisfies(p, r.config.platform))) {
28593
+ problems.push(`repo ${r.name}: requires ${r.config.platform}, but no registered ship satisfies it (ships: ${[...new Set(fleet)].join(", ")})`);
28594
+ }
28595
+ }
28596
+ }
28320
28597
  }
28321
28598
  } catch (e) {
28322
28599
  problems.push(`tracker unreachable: ${e instanceof Error ? e.message : String(e)}`);
@@ -28334,7 +28611,7 @@ if (command === "passenger-sync-daemon") {
28334
28611
  }
28335
28612
  async function doctorFix(o) {
28336
28613
  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))));
28337
- const unitExists = (p) => existsSync56(p);
28614
+ const unitExists = (p) => existsSync57(p);
28338
28615
  const crontab = o.host === "linux" ? spawnSync13("crontab", ["-l"], { encoding: "utf8" }).stdout ?? "" : "";
28339
28616
  const schedulerAbsent = o.host !== "windows" ? !schedulerInstalled(planInstall(cfg.ship, CREW_HOME, o.host, detectSystemd(), "run", installContext()), unitExists, crontab) : true;
28340
28617
  const plan = planFix({ routes, schedulerAbsent, host: o.host });
@@ -28351,7 +28628,7 @@ if (command === "passenger-sync-daemon") {
28351
28628
  for (const a of plan.actions) {
28352
28629
  if (a.kind === "enable") {
28353
28630
  if (prompter && !await prompter.confirm(`Route ${a.route} passes every check \u2014 set enabled: true in ${cfg.configFile}?`, false)) continue;
28354
- writeFileSync41(cfg.configFile, planEnable(readFileSync51(cfg.configFile, "utf8"), a.route));
28631
+ writeFileSync42(cfg.configFile, planEnable(readFileSync52(cfg.configFile, "utf8"), a.route));
28355
28632
  enabledSound.add(a.route);
28356
28633
  changed2.push(`enabled route ${a.route} in ${cfg.configFile}`);
28357
28634
  } else {
@@ -28580,7 +28857,7 @@ ${changed2.map((c) => ` - ${c}
28580
28857
  harnessBin: "claude",
28581
28858
  ...contract.sandboxNetwork ? { extraHosts: contract.sandboxNetwork.hosts, toolchains: contract.sandboxNetwork.toolchains } : {}
28582
28859
  },
28583
- policyFile: join58(cfg.ship.stateDir, "release", `${target.name}.policy.yaml`),
28860
+ policyFile: join60(cfg.ship.stateDir, "release", `${target.name}.policy.yaml`),
28584
28861
  repo: mirror,
28585
28862
  origin: forgeDescriptorFor(forgeHost).httpsUrl(mirror.host, mirror.path),
28586
28863
  base: effective.branch.base,
@@ -28648,11 +28925,18 @@ ${changed2.map((c) => ` - ${c}
28648
28925
  }, target.dir);
28649
28926
  const problems = validateEffective(repo);
28650
28927
  for (const p of problems) remit.warn(`${scope}: ${p}`);
28651
- if (!satisfies(cfg.ship.platform, repo.platform)) {
28928
+ const baseAdmitsShip = satisfies(cfg.ship.platform, repo.platform);
28929
+ if (!baseAdmitsShip && dryRun) {
28652
28930
  const detail = explain(cfg.ship.platform, repo.platform);
28653
28931
  remit.emit(`${scope}: skipping \u2014 ${detail}`, { step: "release" });
28654
28932
  return { scope, tests: "skipped", outcome: "skipped", detail };
28655
28933
  }
28934
+ if (baseAdmitsShip) {
28935
+ try {
28936
+ clearShipAttention(new State(cfg.ship.stateDir), repoPlatformUnreleasableKey(target.name));
28937
+ } catch {
28938
+ }
28939
+ }
28656
28940
  const who2 = releaserFor(repo.release, cfg.ship.name);
28657
28941
  if (!who2.releases) {
28658
28942
  const note = nonReleaserNote(target.name, who2.releaser);
@@ -28694,6 +28978,45 @@ ${changed2.map((c) => ` - ${c}
28694
28978
  );
28695
28979
  reportUnplaceable(c.route, preUnplaceable, tracker.contract.statuses.verified, remit);
28696
28980
  const remoteBase = remoteBranchExists(target.dir, repo.branch.remote, repo.branch.base);
28981
+ if (!baseAdmitsShip) {
28982
+ const baseRef = remoteBase ? `${repo.branch.remote}/${repo.branch.base}` : repo.branch.base;
28983
+ const verifiedPre = pre.filter((t) => t.status === tracker.contract.statuses.verified);
28984
+ const admitters = platformAdmitters(
28985
+ target.dir,
28986
+ baseRef,
28987
+ cfg.ship.platform,
28988
+ verifiedPre,
28989
+ (t) => locateBranchForTicket(target.dir, repo, t)?.branch ?? null
28990
+ );
28991
+ if (admitters.length === 0) {
28992
+ const detail = explain(cfg.ship.platform, repo.platform);
28993
+ const ids = verifiedPre.map((t) => t.issue_id);
28994
+ if (firstReport(`${scope}:platform:${ids.join(",")}`)) remit.emit(`${scope}: skipping \u2014 ${detail}`, { step: "release" });
28995
+ if (ids.length) {
28996
+ try {
28997
+ await raiseShipAttention(
28998
+ { state, emit: remit, route: c, ship: cfg.ship },
28999
+ repoPlatformUnreleasableItem(target.name, platformStuckNote(target.name, repo.platform, cfg.ship.platform, ids))
29000
+ );
29001
+ } catch {
29002
+ }
29003
+ } else {
29004
+ try {
29005
+ clearShipAttention(state, repoPlatformUnreleasableKey(target.name));
29006
+ } catch {
29007
+ }
29008
+ }
29009
+ return { scope, tests: "skipped", outcome: "skipped", detail };
29010
+ }
29011
+ try {
29012
+ clearShipAttention(state, repoPlatformUnreleasableKey(target.name));
29013
+ } catch {
29014
+ }
29015
+ remit.emit(
29016
+ `${scope}: the base contract requires ${repo.platform}, but ${admitters.map((a) => a.issueId).join(", ")} change${admitters.length === 1 ? "s" : ""} platform to ${admitters[0].platform}, which this ship satisfies \u2014 releasing`,
29017
+ { step: "release" }
29018
+ );
29019
+ }
28697
29020
  const d = decideRelease(target.dir, pre, tracker.contract, {
28698
29021
  tagPattern: repo.release.tagPattern ?? "v*",
28699
29022
  base: repo.branch.base,
@@ -29736,7 +30059,7 @@ ${cu.tail.trimEnd()}
29736
30059
  logFile: cfg.ship.logFile
29737
30060
  });
29738
30061
  }
29739
- const watchPaths = isCompiledBinary(import.meta.url) ? [process.execPath] : [join58(CREW_HOME, "src"), join58(CREW_HOME, "dist"), join58(CREW_HOME, "bin")];
30062
+ const watchPaths = isCompiledBinary(import.meta.url) ? [process.execPath] : [join60(CREW_HOME, "src"), join60(CREW_HOME, "dist"), join60(CREW_HOME, "bin")];
29740
30063
  const configPaths = daemonConfigPaths(cfg);
29741
30064
  watchPaths.push(...configPaths);
29742
30065
  noteDaemonStarted(cfg.ship.stateDir);
@@ -30054,10 +30377,10 @@ ${cu.tail.trimEnd()}
30054
30377
  `);
30055
30378
  if (!dryRun) {
30056
30379
  const resolvedPath = resolvedPathFor(cfg.ship.stateDir, target.route);
30057
- const raw = existsSync56(resolvedPath) ? JSON.parse(readFileSync51(resolvedPath, "utf8")) : {};
30380
+ const raw = existsSync57(resolvedPath) ? JSON.parse(readFileSync52(resolvedPath, "utf8")) : {};
30058
30381
  raw.agentSkills = result.agentSkills;
30059
- mkdirSync41(dirOf2(resolvedPath), { recursive: true });
30060
- writeFileSync41(resolvedPath, `${JSON.stringify(raw, null, 2)}
30382
+ mkdirSync42(dirOf2(resolvedPath), { recursive: true });
30383
+ writeFileSync42(resolvedPath, `${JSON.stringify(raw, null, 2)}
30061
30384
  `);
30062
30385
  }
30063
30386
  if (result.outcomes.some((o) => o.action === "diverged")) process.exitCode = 1;
@@ -30080,7 +30403,7 @@ ${cu.tail.trimEnd()}
30080
30403
  throw e;
30081
30404
  }
30082
30405
  const oldName = cfg.ship.name;
30083
- writeFileSync41(cfg.configFile, setShipNameInYaml(readFileSync51(cfg.configFile, "utf8"), newName));
30406
+ writeFileSync42(cfg.configFile, setShipNameInYaml(readFileSync52(cfg.configFile, "utf8"), newName));
30084
30407
  cfg.ship.name = newName;
30085
30408
  let renameMachineId;
30086
30409
  try {
@@ -30127,14 +30450,14 @@ ${cu.tail.trimEnd()}
30127
30450
  process.exit(2);
30128
30451
  };
30129
30452
  if (sub !== "add" && sub !== "list" && sub !== "clone" && sub !== "hooks" && sub !== "check") usage2();
30130
- const configText = readFileSync51(cfg.configFile, "utf8");
30453
+ const configText = readFileSync52(cfg.configFile, "utf8");
30131
30454
  if (sub === "check") {
30132
30455
  try {
30133
30456
  const routeArg = value("route") ?? positional[2];
30134
30457
  const found = cfg.routes.find((r) => r.route === routeArg);
30135
30458
  if (!found) throw new ReposError(`no route "${routeArg}" in the config (have: ${cfg.routes.map((r) => r.route).join(", ") || "none"})`);
30136
30459
  const named2 = value("route") ? void 0 : positional[3];
30137
- const dir = named2 ? repoDirOf(configText, dirname36(cfg.configFile), found.route, named2) : resolvePath(positional[value("route") ? 2 : 3] ?? ".");
30460
+ const dir = named2 ? repoDirOf(configText, dirname37(cfg.configFile), found.route, named2) : resolvePath(positional[value("route") ? 2 : 3] ?? ".");
30138
30461
  const target = reposOf(found).find((t) => resolvePath(t.dir) === dir || t.name === named2);
30139
30462
  const o = target ? found.repoOverrides[target.name] : void 0;
30140
30463
  runReposCheck(dir, {
@@ -30158,9 +30481,9 @@ ${cu.tail.trimEnd()}
30158
30481
  if (sub === "hooks") {
30159
30482
  try {
30160
30483
  const a = parseHooksArgs(positional.slice(2), routeNamesOf(configText));
30161
- const dir = repoDirOf(configText, dirname36(cfg.configFile), a.route, a.name);
30162
- if (!existsSync56(dir)) throw new ReposError(`${dir} does not exist on disk`);
30163
- const files = { exists: (r) => existsSync56(resolvePath(dir, r)), list: (r) => {
30484
+ const dir = repoDirOf(configText, dirname37(cfg.configFile), a.route, a.name);
30485
+ if (!existsSync57(dir)) throw new ReposError(`${dir} does not exist on disk`);
30486
+ const files = { exists: (r) => existsSync57(resolvePath(dir, r)), list: (r) => {
30164
30487
  try {
30165
30488
  return readdirSync20(resolvePath(dir, r));
30166
30489
  } catch {
@@ -30168,7 +30491,7 @@ ${cu.tail.trimEnd()}
30168
30491
  }
30169
30492
  }, read: (r) => {
30170
30493
  try {
30171
- return readFileSync51(resolvePath(dir, r), "utf8");
30494
+ return readFileSync52(resolvePath(dir, r), "utf8");
30172
30495
  } catch {
30173
30496
  return void 0;
30174
30497
  }
@@ -30210,19 +30533,19 @@ ${cu.tail.trimEnd()}
30210
30533
  let cleared;
30211
30534
  if (clear2) {
30212
30535
  const plan = clearRouteHooks(configText, a.route, a.name);
30213
- if (plan.removed.length > 0) writeFileSync41(cfg.configFile, plan.text);
30536
+ if (plan.removed.length > 0) writeFileSync42(cfg.configFile, plan.text);
30214
30537
  cleared = { file: cfg.configFile, removed: plan.removed };
30215
30538
  }
30216
30539
  if (write && suggestion.source === null && recipeIds.length === 0 && hookSpecs.length === 0) throw new ReposError(`nothing to write: ${suggestion.notes[0]}`);
30217
30540
  if (write === "route") {
30218
30541
  const plan = planRouteHooks(configText, a.route, a.name, picked.hooks, { replace: flag("replace") });
30219
- writeFileSync41(cfg.configFile, plan.text);
30542
+ writeFileSync42(cfg.configFile, plan.text);
30220
30543
  written = { target: "route", file: cfg.configFile, hooks: plan.written, kept: plan.kept, replaced: plan.replaced };
30221
30544
  } else if (write === "repo") {
30222
30545
  const have = existingRepoConfig(files);
30223
30546
  if (have) throw new ReposError(`${resolvePath(dir, have)} already exists; not overwriting it`);
30224
30547
  const file = resolvePath(dir, ".crew.yaml");
30225
- writeFileSync41(file, starterRepoConfig(picked.hooks, picked.release), { flag: "wx" });
30548
+ writeFileSync42(file, starterRepoConfig(picked.hooks, picked.release), { flag: "wx" });
30226
30549
  written = { target: "repo", file, hooks: Object.keys(picked.hooks), kept: [], replaced: [] };
30227
30550
  }
30228
30551
  if (flag("json")) {
@@ -30278,7 +30601,7 @@ ${cu.tail.trimEnd()}
30278
30601
  if (sub === "list" && !routeName) usage2();
30279
30602
  if (sub === "add") {
30280
30603
  try {
30281
- const a = parseAddArgs(positional.slice(2), routeNamesOf(configText), (p) => existsSync56(resolvePath(p.replace(/^~(?=\/|$)/, homedir11()))));
30604
+ const a = parseAddArgs(positional.slice(2), routeNamesOf(configText), (p) => existsSync57(resolvePath(p.replace(/^~(?=\/|$)/, homedir11()))));
30282
30605
  routeName = a.route;
30283
30606
  addPath = a.path;
30284
30607
  addName = a.name;
@@ -30308,7 +30631,7 @@ ${cu.tail.trimEnd()}
30308
30631
  const resolvedFile = resolvedPathFor(cfg.ship.stateDir, routeName);
30309
30632
  if (sub === "list" || sub === "add") {
30310
30633
  const liveRoute = cfg.routes.find((r) => r.route === routeName);
30311
- if (liveRoute?.resolved?.reposModelId && existsSync56(resolvedFile) && !dryRun) {
30634
+ if (liveRoute?.resolved?.reposModelId && existsSync57(resolvedFile) && !dryRun) {
30312
30635
  try {
30313
30636
  await hydrateApiKeys([liveRoute]);
30314
30637
  persistRepoRows(cfg.ship.stateDir, liveRoute.route, await new Tracker(liveRoute, cfg.ship).repoRowsForMap());
@@ -30317,16 +30640,16 @@ ${cu.tail.trimEnd()}
30317
30640
  }
30318
30641
  }
30319
30642
  let resolvedRemotes;
30320
- if (existsSync56(resolvedFile)) {
30643
+ if (existsSync57(resolvedFile)) {
30321
30644
  try {
30322
- resolvedRemotes = JSON.parse(readFileSync51(resolvedFile, "utf8"));
30645
+ resolvedRemotes = JSON.parse(readFileSync52(resolvedFile, "utf8"));
30323
30646
  } catch {
30324
30647
  }
30325
30648
  }
30326
30649
  const originOf = (dir) => gitOk(dir, ["remote", "get-url", "origin"]) ?? void 0;
30327
30650
  const text2 = configText;
30328
- const base = dirname36(cfg.configFile);
30329
- const isCheckout = (d) => existsSync56(`${d}/.git`);
30651
+ const base = dirname37(cfg.configFile);
30652
+ const isCheckout = (d) => existsSync57(`${d}/.git`);
30330
30653
  try {
30331
30654
  if (sub === "list") {
30332
30655
  if (flag("json")) {
@@ -30336,12 +30659,12 @@ ${cu.tail.trimEnd()}
30336
30659
  base,
30337
30660
  resolved: resolvedRemotes,
30338
30661
  originOf,
30339
- exists: (d) => existsSync56(d),
30662
+ exists: (d) => existsSync57(d),
30340
30663
  isCheckout,
30341
30664
  repoHasHooks: (d) => REPO_CONFIG_FILENAMES.some((f) => {
30342
30665
  try {
30343
30666
  const path = resolvePath(d, f);
30344
- return Object.keys(parseRepoConfig(readFileSync51(path, "utf8"), path).hooks).length > 0;
30667
+ return Object.keys(parseRepoConfig(readFileSync52(path, "utf8"), path).hooks).length > 0;
30345
30668
  } catch {
30346
30669
  return false;
30347
30670
  }
@@ -30358,7 +30681,7 @@ ${cu.tail.trimEnd()}
30358
30681
  for (const r of repos) {
30359
30682
  const origin2 = originOf(r.dir);
30360
30683
  const row = matchRepoName(origin2, resolvedRemotes);
30361
- const note = !existsSync56(r.dir) ? "missing on disk" : row ? `Repos row: ${row}` : `no Repos row matches ${normalizeRemote(origin2) ?? "this checkout (no origin remote)"}`;
30684
+ const note = !existsSync57(r.dir) ? "missing on disk" : row ? `Repos row: ${row}` : `no Repos row matches ${normalizeRemote2(origin2) ?? "this checkout (no origin remote)"}`;
30362
30685
  process.stdout.write(`${r.name} ${r.dir} ${note}
30363
30686
  `);
30364
30687
  }
@@ -30370,9 +30693,9 @@ ${cu.tail.trimEnd()}
30370
30693
  ` : `${human}
30371
30694
  `);
30372
30695
  const plan2 = planRepoClone({ text: text2, base, route: routeName, name: addName, resolved: resolvedRemotes, dir: value("dir"), isCheckout });
30373
- if (existsSync56(plan2.target) && (existsSync56(`${plan2.target}/.git`) || readdirSync20(plan2.target).length > 0)) {
30696
+ if (existsSync57(plan2.target) && (existsSync57(`${plan2.target}/.git`) || readdirSync20(plan2.target).length > 0)) {
30374
30697
  throw new ReposError(
30375
- existsSync56(`${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`
30698
+ existsSync57(`${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`
30376
30699
  );
30377
30700
  }
30378
30701
  if (dryRun) {
@@ -30390,14 +30713,14 @@ ${cu.tail.trimEnd()}
30390
30713
  throw new ReposError(`${e.message}${authHint}
30391
30714
  crew.yaml was not changed`);
30392
30715
  }
30393
- writeFileSync41(cfg.configFile, plan2.text);
30716
+ writeFileSync42(cfg.configFile, plan2.text);
30394
30717
  if (plan2.droppedDir) process.stderr.write(`crew repos: dropped dir: ${plan2.droppedDir} from route ${routeName} \u2014 it is not a checkout (the clone base); checkouts now live under repos:
30395
30718
  `);
30396
30719
  say("attached", { route: routeName, name: plan2.name, dir: plan2.target, mode: plan2.mode }, `cloned and attached ${plan2.target} to ${routeName} as ${plan2.mode === "dir" ? "dir" : `repos.${plan2.name}`} in ${cfg.configFile}`);
30397
30720
  break;
30398
30721
  }
30399
30722
  const target = resolvePath(addPath.replace(/^~(?=\/|$)/, homedir11()));
30400
- const top = existsSync56(target) ? gitOk(target, ["rev-parse", "--show-toplevel"]) : null;
30723
+ const top = existsSync57(target) ? gitOk(target, ["rev-parse", "--show-toplevel"]) : null;
30401
30724
  if (!top) throw new ReposError(`${target} is not a git checkout`);
30402
30725
  const origin = originOf(top);
30403
30726
  const plan = planRepoAdd({
@@ -30449,15 +30772,15 @@ ${cu.tail.trimEnd()}
30449
30772
  const created = await rowTracker.createRepoRow(rowPayload);
30450
30773
  process.stdout.write(`created Repos row ${String(rowPayload.name)} (${String(rowPayload.remote)}) ${created.id}
30451
30774
  `);
30452
- if (existsSync56(resolvedFile)) {
30453
- const raw = JSON.parse(readFileSync51(resolvedFile, "utf8"));
30775
+ if (existsSync57(resolvedFile)) {
30776
+ const raw = JSON.parse(readFileSync52(resolvedFile, "utf8"));
30454
30777
  raw.repoNames = { ...raw.repoNames, [created.id]: String(rowPayload.name) };
30455
30778
  raw.repoRemotes = { ...raw.repoRemotes, [created.id]: String(rowPayload.remote) };
30456
- writeFileSync41(resolvedFile, `${JSON.stringify(raw, null, 2)}
30779
+ writeFileSync42(resolvedFile, `${JSON.stringify(raw, null, 2)}
30457
30780
  `);
30458
30781
  }
30459
30782
  }
30460
- writeFileSync41(cfg.configFile, plan.text);
30783
+ writeFileSync42(cfg.configFile, plan.text);
30461
30784
  process.stdout.write(`added ${top} to ${routeName} as ${plan.mode === "dir" ? "dir" : `repos.${plan.name}`} in ${cfg.configFile}
30462
30785
  `);
30463
30786
  } catch (e) {
@@ -30832,7 +31155,7 @@ Signed in as ${result.identity.email} \u2014 minted an API key in workspace "${r
30832
31155
  process.exit(2);
30833
31156
  }
30834
31157
  if (found.shipNameAdopted && !dryRun) {
30835
- writeFileSync41(cfg.configFile, setShipNameInYaml(readFileSync51(cfg.configFile, "utf8"), found.shipNameAdopted));
31158
+ writeFileSync42(cfg.configFile, setShipNameInYaml(readFileSync52(cfg.configFile, "utf8"), found.shipNameAdopted));
30836
31159
  cfg.ship.name = found.shipNameAdopted;
30837
31160
  }
30838
31161
  if (found.shipRow) {
@@ -30875,10 +31198,10 @@ Signed in as ${result.identity.email} \u2014 minted an API key in workspace "${r
30875
31198
  }
30876
31199
  }
30877
31200
  let previous;
30878
- const hadPreviousFile = existsSync56(resolvedPath);
31201
+ const hadPreviousFile = existsSync57(resolvedPath);
30879
31202
  if (hadPreviousFile) {
30880
31203
  try {
30881
- previous = JSON.parse(readFileSync51(resolvedPath, "utf8"));
31204
+ previous = JSON.parse(readFileSync52(resolvedPath, "utf8"));
30882
31205
  } catch {
30883
31206
  }
30884
31207
  }
@@ -31008,12 +31331,12 @@ Signed in as ${result.identity.email} \u2014 minted an API key in workspace "${r
31008
31331
  process.stderr.write(`(dry run) would write resolved ids to ${resolvedPath}
31009
31332
  `);
31010
31333
  } else {
31011
- mkdirSync41(dirname36(resolvedPath), { recursive: true });
31334
+ mkdirSync42(dirname37(resolvedPath), { recursive: true });
31012
31335
  if (hadPreviousFile) copyFileSync2(resolvedPath, `${resolvedPath}.bak`);
31013
31336
  const tmpPath = `${resolvedPath}.tmp${process.pid}`;
31014
- writeFileSync41(tmpPath, `${JSON.stringify(resolved, null, 2)}
31337
+ writeFileSync42(tmpPath, `${JSON.stringify(resolved, null, 2)}
31015
31338
  `);
31016
- renameSync7(tmpPath, resolvedPath);
31339
+ renameSync8(tmpPath, resolvedPath);
31017
31340
  process.stderr.write(`Resolved ids written to ${resolvedPath}
31018
31341
  `);
31019
31342
  }
@@ -31057,8 +31380,8 @@ Signed in as ${result.identity.email} \u2014 minted an API key in workspace "${r
31057
31380
  process.stderr.write(`(dry run) would write the minted API key to ${apiKeyFile}
31058
31381
  `);
31059
31382
  } else {
31060
- mkdirSync41(dirname36(apiKeyFile), { recursive: true });
31061
- writeFileSync41(apiKeyFile, `${apiKeyVar}=${apiKey}
31383
+ mkdirSync42(dirname37(apiKeyFile), { recursive: true });
31384
+ writeFileSync42(apiKeyFile, `${apiKeyVar}=${apiKey}
31062
31385
  `, { mode: 384 });
31063
31386
  process.stderr.write(`API key written to ${apiKeyFile}
31064
31387
  `);
@@ -31773,10 +32096,10 @@ Signed in as ${result.identity.email} \u2014 minted an API key in workspace "${r
31773
32096
  startupSeconds: cfg.ship.intelStartupSeconds,
31774
32097
  prepare: async (path) => {
31775
32098
  for (const f of repoWt.config.worktrees.copy) {
31776
- const src = join58(repoWt.dir, f);
31777
- if (!existsSync56(src) || existsSync56(join58(path, f))) continue;
31778
- mkdirSync41(dirOf2(join58(path, f)), { recursive: true });
31779
- copyFileSync2(src, join58(path, f));
32099
+ const src = join60(repoWt.dir, f);
32100
+ if (!existsSync57(src) || existsSync57(join60(path, f))) continue;
32101
+ mkdirSync42(dirOf2(join60(path, f)), { recursive: true });
32102
+ copyFileSync2(src, join60(path, f));
31780
32103
  }
31781
32104
  const setup = repoWt.config.hooks.setup;
31782
32105
  return setup ? runScript(setup, { cwd: path, shell: shellWt }) : null;
@@ -32002,7 +32325,7 @@ Signed in as ${result.identity.email} \u2014 minted an API key in workspace "${r
32002
32325
  const shellR = hit && resolveShell(hit.repo.config.shell ?? cfg.ship.shell);
32003
32326
  const resumed = await runPeriscopeResume({
32004
32327
  find: async () => hit && { row: hit.row, tag: hit.tag },
32005
- worktreeExists: (p) => existsSync56(p),
32328
+ worktreeExists: (p) => existsSync57(p),
32006
32329
  prepareDropFile,
32007
32330
  startProxy: (wt, url, n) => launchProxy(crewInvocation(CREW_HOME), wt, url, Number(n), { host: hit.row.host || "localhost", inject: hit.repo.config.periscope?.inspector !== "repo" }),
32008
32331
  relay: hit && previewRelayFor(hit.route) && {
@@ -32105,10 +32428,10 @@ ${where.join("\n")}`);
32105
32428
  },
32106
32429
  prepare: async (path) => {
32107
32430
  for (const f of repoP.config.worktrees.copy) {
32108
- const src = join58(repoP.dir, f);
32109
- if (!existsSync56(src)) continue;
32110
- mkdirSync41(dirOf2(join58(path, f)), { recursive: true });
32111
- copyFileSync2(src, join58(path, f));
32431
+ const src = join60(repoP.dir, f);
32432
+ if (!existsSync57(src)) continue;
32433
+ mkdirSync42(dirOf2(join60(path, f)), { recursive: true });
32434
+ copyFileSync2(src, join60(path, f));
32112
32435
  }
32113
32436
  const setup = repoP.config.hooks.setup;
32114
32437
  return setup ? runScript(setup, { cwd: path, shell: shellP, onLine: (l) => {
@@ -32420,7 +32743,7 @@ ${where.join("\n")}`);
32420
32743
  };
32421
32744
  const droppedRoutes = [];
32422
32745
  try {
32423
- const rawCfg = parseYaml3(readFileSync51(cfg.configFile, "utf8"));
32746
+ const rawCfg = parseYaml3(readFileSync52(cfg.configFile, "utf8"));
32424
32747
  for (const r of rawCfg?.routes ?? []) {
32425
32748
  if (typeof r?.route !== "string" || cfg.routes.some((x) => x.route === r.route)) continue;
32426
32749
  try {
@@ -32484,8 +32807,8 @@ ${where.join("\n")}`);
32484
32807
  process.stdout.write("crew reload: no daemon unit is running \u2014 nothing to reload (the next run reads crew.yaml fresh)\n");
32485
32808
  break;
32486
32809
  }
32487
- mkdirSync41(cfg.ship.stateDir, { recursive: true });
32488
- writeFileSync41(sentinel, `${(/* @__PURE__ */ new Date()).toISOString()}
32810
+ mkdirSync42(cfg.ship.stateDir, { recursive: true });
32811
+ writeFileSync42(sentinel, `${(/* @__PURE__ */ new Date()).toISOString()}
32489
32812
  `);
32490
32813
  process.stdout.write(
32491
32814
  "crew reload: requested \u2014 the daemon relaunches with the new config once its running agents end (it starts no new work meanwhile); if it is busy, `crew reload --now` forces the relaunch and interrupts them\n"
@@ -32550,7 +32873,7 @@ ${where.join("\n")}`);
32550
32873
  }
32551
32874
  case "log": {
32552
32875
  try {
32553
- const text2 = readFileSync51(cfg.ship.logFile, "utf8").split("\n");
32876
+ const text2 = readFileSync52(cfg.ship.logFile, "utf8").split("\n");
32554
32877
  process.stdout.write(`${text2.slice(-(Number(value("tail")) || 40)).join("\n")}
32555
32878
  `);
32556
32879
  } catch {
@@ -32573,8 +32896,8 @@ ${where.join("\n")}`);
32573
32896
  };
32574
32897
  if (!route2.resolved) fail2(`route ${route2.route} is not connected \u2014 run \`crew connect\` first`);
32575
32898
  const tracker = new Tracker(route2, cfg.ship);
32576
- const configText = readFileSync51(cfg.configFile, "utf8");
32577
- const cfgBase = dirname36(cfg.configFile);
32899
+ const configText = readFileSync52(cfg.configFile, "utf8");
32900
+ const cfgBase = dirname37(cfg.configFile);
32578
32901
  const configured2 = configuredRepos(configText, route2.route, cfgBase);
32579
32902
  const dir = configured2.find((r) => r.name === SAMPLE_REPO)?.dir ?? sampleDir(configured2.map((r) => r.dir), route2.reposBasePath, route2.route.split("/")[0]);
32580
32903
  const resolvedFile = resolvedPathFor(cfg.ship.stateDir, route2.route);
@@ -32602,7 +32925,7 @@ ${where.join("\n")}`);
32602
32925
  }
32603
32926
  if (configured2.some((r) => r.dir === dir)) {
32604
32927
  try {
32605
- writeFileSync41(cfg.configFile, planRepoRemove(configText, cfgBase, route2.route, dir).text);
32928
+ writeFileSync42(cfg.configFile, planRepoRemove(configText, cfgBase, route2.route, dir).text);
32606
32929
  } catch (e) {
32607
32930
  if (e instanceof ReposError) fail2(e.message);
32608
32931
  throw e;
@@ -32610,29 +32933,29 @@ ${where.join("\n")}`);
32610
32933
  }
32611
32934
  if (row) {
32612
32935
  await tracker.deleteRepoRow(row.id);
32613
- if (existsSync56(resolvedFile)) {
32614
- const raw = JSON.parse(readFileSync51(resolvedFile, "utf8"));
32936
+ if (existsSync57(resolvedFile)) {
32937
+ const raw = JSON.parse(readFileSync52(resolvedFile, "utf8"));
32615
32938
  if (raw.repoNames) delete raw.repoNames[row.id];
32616
32939
  if (raw.repoRemotes) delete raw.repoRemotes[row.id];
32617
- writeFileSync41(resolvedFile, `${JSON.stringify(raw, null, 2)}
32940
+ writeFileSync42(resolvedFile, `${JSON.stringify(raw, null, 2)}
32618
32941
  `);
32619
32942
  }
32620
32943
  }
32621
- if (existsSync56(join58(dir, ".git")) && basename16(dir) === SAMPLE_REPO) rmSync25(dir, { recursive: true, force: true });
32944
+ if (existsSync57(join60(dir, ".git")) && basename16(dir) === SAMPLE_REPO) rmSync26(dir, { recursive: true, force: true });
32622
32945
  say("removed", { dir, closed }, `removed the sample repo${closed.length ? `, closed ${closed.join(", ")}` : ""}`);
32623
32946
  break;
32624
32947
  }
32625
32948
  const projectId = route2.resolved.areaId ?? resolveRepoProject(await tracker.projectRows(), value("project"));
32626
- const fresh = !existsSync56(join58(dir, ".git"));
32627
- if (existsSync56(dir) && fresh && readdirSync20(dir).length > 0) fail2(`${dir} exists and is not a git checkout \u2014 move it aside`);
32949
+ const fresh = !existsSync57(join60(dir, ".git"));
32950
+ if (existsSync57(dir) && fresh && readdirSync20(dir).length > 0) fail2(`${dir} exists and is not a git checkout \u2014 move it aside`);
32628
32951
  if (dryRun) {
32629
32952
  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`);
32630
32953
  break;
32631
32954
  }
32632
32955
  if (fresh) {
32633
- mkdirSync41(dir, { recursive: true });
32634
- writeFileSync41(join58(dir, "README.md"), SAMPLE_README);
32635
- writeFileSync41(join58(dir, ".crew.yaml"), SAMPLE_CREW_YAML);
32956
+ mkdirSync42(dir, { recursive: true });
32957
+ writeFileSync42(join60(dir, "README.md"), SAMPLE_README);
32958
+ writeFileSync42(join60(dir, ".crew.yaml"), SAMPLE_CREW_YAML);
32636
32959
  const g = (...a) => {
32637
32960
  const r = spawnSync13("git", a, { cwd: dir, encoding: "utf8" });
32638
32961
  if (r.status !== 0) fail2(`git ${a[0]} failed in ${dir}: ${(r.stderr || r.stdout).trim()}`);
@@ -32650,17 +32973,17 @@ ${where.join("\n")}`);
32650
32973
  spec: { platform: "unix", releaseMode: "integrate", ciProvider: "none" }
32651
32974
  });
32652
32975
  repoId = (await tracker.createRepoRow(payload)).id;
32653
- if (existsSync56(resolvedFile)) {
32654
- const raw = JSON.parse(readFileSync51(resolvedFile, "utf8"));
32976
+ if (existsSync57(resolvedFile)) {
32977
+ const raw = JSON.parse(readFileSync52(resolvedFile, "utf8"));
32655
32978
  raw.repoNames = { ...raw.repoNames, [repoId]: SAMPLE_REPO };
32656
32979
  raw.repoRemotes = { ...raw.repoRemotes, [repoId]: SAMPLE_REMOTE };
32657
- writeFileSync41(resolvedFile, `${JSON.stringify(raw, null, 2)}
32980
+ writeFileSync42(resolvedFile, `${JSON.stringify(raw, null, 2)}
32658
32981
  `);
32659
32982
  }
32660
32983
  }
32661
32984
  if (!configured2.some((r) => r.dir === dir)) {
32662
32985
  try {
32663
- writeFileSync41(cfg.configFile, planRepoAdd({ text: configText, base: cfgBase, route: route2.route, path: dir, name: SAMPLE_REPO }).text);
32986
+ writeFileSync42(cfg.configFile, planRepoAdd({ text: configText, base: cfgBase, route: route2.route, path: dir, name: SAMPLE_REPO }).text);
32664
32987
  } catch (e) {
32665
32988
  if (e instanceof ReposError) fail2(e.message);
32666
32989
  throw e;
@@ -32849,6 +33172,8 @@ ${where.join("\n")}`);
32849
33172
  model: x.model
32850
33173
  })),
32851
33174
  stateDir: cfg.ship.stateDir,
33175
+ // CREW-3084: how many repositories carry environment; never their names or values.
33176
+ repositoriesWithEnv: repositoryEnvCount(cfg.ship.stateDir),
32852
33177
  logFile: cfg.ship.logFile,
32853
33178
  eventFile: eventFileFor(cfg.ship.stateDir),
32854
33179
  // Additive (CREW-1373): open ship-level items, including the
@@ -33027,7 +33352,7 @@ watermark: ${state.watermark(routeSlug(route2.route))}
33027
33352
  plan,
33028
33353
  label,
33029
33354
  uid: process.getuid?.() ?? 0,
33030
- system: plan.mechanism === "systemd" && existsSync56(systemUnitPathFor(label)),
33355
+ system: plan.mechanism === "systemd" && existsSync57(systemUnitPathFor(label)),
33031
33356
  stamp: readDaemonStamp(cfg.ship.stateDir)
33032
33357
  });
33033
33358
  })();
@@ -33043,7 +33368,7 @@ watermark: ${state.watermark(routeSlug(route2.route))}
33043
33368
  }
33044
33369
  for (const r of repos) {
33045
33370
  const remote = r.config.branch.remote;
33046
- if (existsSync56(r.dir)) {
33371
+ if (existsSync57(r.dir)) {
33047
33372
  pushAuth.push({
33048
33373
  route: c.route,
33049
33374
  repo: r.name,
@@ -33125,7 +33450,7 @@ watermark: ${state.watermark(routeSlug(route2.route))}
33125
33450
  if (dp) problems.push(dp);
33126
33451
  else passed++;
33127
33452
  }
33128
- const runtimeDir = runtimeDirWarning(process.platform, process.getuid?.() ?? null, existsSync56, userInfo2().username);
33453
+ const runtimeDir = runtimeDirWarning(process.platform, process.getuid?.() ?? null, existsSync57, userInfo2().username);
33129
33454
  if (runtimeDir) problems.push({ severity: "attention", kind: "runtime_dir_missing", message: runtimeDir });
33130
33455
  if (!flag("offline")) {
33131
33456
  const shipKind = await doctorShipKind(route2, cfg.ship);
@@ -33190,7 +33515,7 @@ routes: ${cfg.routes.map((c) => c.route).join(", ")}
33190
33515
  }
33191
33516
  try {
33192
33517
  const evFile = eventFileFor(cfg.ship.stateDir);
33193
- const evSize = existsSync56(evFile) ? statSync17(evFile).size : 0;
33518
+ const evSize = existsSync57(evFile) ? statSync17(evFile).size : 0;
33194
33519
  process.stdout.write(
33195
33520
  evSize > cfg.ship.eventsRotateBytes * 4 ? `events log: WARN ${evFile} is ${Math.round(evSize / 1048576)} MB (> 4x eventsRotateBytes); run \`crew reap\` to rotate it
33196
33521
  ` : "events log: ok\n"
@@ -33201,7 +33526,7 @@ routes: ${cfg.routes.map((c) => c.route).join(", ")}
33201
33526
  const unitPlan = planInstall(cfg.ship, CREW_HOME, host, detectSystemd(), "run", installContext());
33202
33527
  const abandons = unitAbandonsAgents(unitPlan, (p) => {
33203
33528
  try {
33204
- return readFileSync51(p, "utf8");
33529
+ return readFileSync52(p, "utf8");
33205
33530
  } catch {
33206
33531
  return null;
33207
33532
  }
@@ -33216,7 +33541,7 @@ routes: ${cfg.routes.map((c) => c.route).join(", ")}
33216
33541
  const pPlan = planInstall(cfg.ship, CREW_HOME, host, true, "passengers", installContext());
33217
33542
  const keeps = unitAbandonsAgents(pPlan, (p) => {
33218
33543
  try {
33219
- return readFileSync51(p, "utf8");
33544
+ return readFileSync52(p, "utf8");
33220
33545
  } catch {
33221
33546
  return null;
33222
33547
  }
@@ -33230,7 +33555,7 @@ routes: ${cfg.routes.map((c) => c.route).join(", ")}
33230
33555
  if (host === "linux" && detectSystemd()) {
33231
33556
  const ctl = planDaemonControl(CREW_HOME, host, true);
33232
33557
  const unitPlan = planInstall(cfg.ship, CREW_HOME, host, true, "run", installContext());
33233
- if (ctl.statusCommand && unitPlan.unitPaths.some((p) => existsSync56(p))) {
33558
+ if (ctl.statusCommand && unitPlan.unitPaths.some((p) => existsSync57(p))) {
33234
33559
  const st = spawnSync13(ctl.statusCommand[0], ctl.statusCommand.slice(1), { cwd: CREW_HOME, encoding: "utf8" });
33235
33560
  if (!st.error && st.status !== 0) {
33236
33561
  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");