@tablation/crew 0.137.11 → 0.139.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.
package/dist/cli.js CHANGED
@@ -1673,9 +1673,12 @@ var claudeAdapter = {
1673
1673
  "the write profile (QA) withholds the Edit tool, not file writes \u2014 Bash can still write files",
1674
1674
  "git push is not blocked, only forced pushes"
1675
1675
  ],
1676
+ // CREW-3118: with `--input-format stream-json` stdin is NDJSON user messages, so a note can follow the prompt.
1677
+ userMessageLine: (text2) => JSON.stringify({ type: "user", message: { role: "user", content: [{ type: "text", text: text2 }] } }) + "\n",
1676
1678
  invocation(spec, o) {
1677
1679
  const args = [
1678
1680
  "-p",
1681
+ ...o.streamInput ? ["--input-format", "stream-json"] : [],
1679
1682
  "--allowedTools",
1680
1683
  ...allowedTools(o.role),
1681
1684
  "--disallowedTools",
@@ -6885,33 +6888,95 @@ import { promisify as promisify2 } from "util";
6885
6888
 
6886
6889
  // src/deprovision-host.ts
6887
6890
  import { spawnSync as spawnSync7 } from "child_process";
6888
- import { existsSync as existsSync31, readdirSync as readdirSync12 } from "fs";
6891
+ import { existsSync as existsSync32, readdirSync as readdirSync12 } from "fs";
6892
+
6893
+ // src/repo-env.ts
6894
+ import { existsSync as existsSync19, mkdirSync as mkdirSync14, readFileSync as readFileSync20, renameSync as renameSync3, rmSync as rmSync10, writeFileSync as writeFileSync15 } from "fs";
6895
+ import { dirname as dirname11, join as join22 } from "path";
6896
+ function repoEnvPathFor(stateDir) {
6897
+ return join22(stateDir, "repo-env.json");
6898
+ }
6899
+ function normalizeRemote(remote) {
6900
+ return remote.trim().toLowerCase().replace(/^[a-z+]+:\/\//, "").replace(/^[^@/]+@/, "").replace(":", "/").replace(/\.git$/, "").replace(/\/+$/, "");
6901
+ }
6902
+ function sanitizeRepositoryEnv(raw) {
6903
+ if (!Array.isArray(raw)) return [];
6904
+ const out = [];
6905
+ for (const e of raw) {
6906
+ if (!e || typeof e !== "object" || !e.env || typeof e.env !== "object") continue;
6907
+ const repoRowId = typeof e.repoRowId === "string" && e.repoRowId ? e.repoRowId : void 0;
6908
+ const remote = typeof e.remote === "string" && e.remote ? e.remote : void 0;
6909
+ if (!repoRowId && !remote) continue;
6910
+ const env = {};
6911
+ for (const [k, v] of Object.entries(e.env)) {
6912
+ if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(k) && typeof v === "string") env[k] = v;
6913
+ }
6914
+ if (Object.keys(env).length) out.push({ ...repoRowId ? { repoRowId } : {}, ...remote ? { remote } : {}, env });
6915
+ }
6916
+ return out;
6917
+ }
6918
+ function readRepositoryEnv(stateDir) {
6919
+ try {
6920
+ return sanitizeRepositoryEnv(JSON.parse(readFileSync20(repoEnvPathFor(stateDir), "utf8")));
6921
+ } catch {
6922
+ return [];
6923
+ }
6924
+ }
6925
+ function writeRepositoryEnv(stateDir, entries) {
6926
+ const file = repoEnvPathFor(stateDir);
6927
+ const clean = sanitizeRepositoryEnv(entries);
6928
+ if (!clean.length) {
6929
+ eraseRepositoryEnv(stateDir);
6930
+ return;
6931
+ }
6932
+ mkdirSync14(dirname11(file), { recursive: true, mode: 448 });
6933
+ const tmp = `${file}.tmp`;
6934
+ writeFileSync15(tmp, `${JSON.stringify(clean)}
6935
+ `, { mode: 384 });
6936
+ renameSync3(tmp, file);
6937
+ }
6938
+ function eraseRepositoryEnv(stateDir) {
6939
+ rmSync10(repoEnvPathFor(stateDir), { force: true });
6940
+ }
6941
+ function hasRepositoryEnv(stateDir) {
6942
+ return existsSync19(repoEnvPathFor(stateDir));
6943
+ }
6944
+ function repositoryEnvCount(stateDir) {
6945
+ return readRepositoryEnv(stateDir).length;
6946
+ }
6947
+ function envForRepository(entries, repo) {
6948
+ const byId = repo.repoRowId ? entries.find((e) => e.repoRowId === repo.repoRowId) : void 0;
6949
+ if (byId) return { ...byId.env };
6950
+ const want = repo.remote ? normalizeRemote(repo.remote) : "";
6951
+ const byRemote = want ? entries.find((e) => e.remote && normalizeRemote(e.remote) === want) : void 0;
6952
+ return byRemote ? { ...byRemote.env } : {};
6953
+ }
6889
6954
 
6890
6955
  // src/interrupted.ts
6891
- import { existsSync as existsSync29, readdirSync as readdirSync10, readFileSync as readFileSync30 } from "fs";
6892
- import { join as join32 } from "path";
6956
+ import { existsSync as existsSync30, readdirSync as readdirSync10, readFileSync as readFileSync31 } from "fs";
6957
+ import { join as join33 } from "path";
6893
6958
 
6894
6959
  // src/agent.ts
6895
6960
  import { spawnSync as spawnSync6 } from "child_process";
6896
- 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";
6961
+ 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";
6897
6962
  import { StringDecoder } from "string_decoder";
6898
6963
  import { finished } from "stream/promises";
6899
- import { join as join31, dirname as dirname15, basename as basename9 } from "path";
6964
+ import { join as join32, dirname as dirname16, basename as basename9 } from "path";
6900
6965
  import { createHash as createHash6, randomUUID } from "crypto";
6901
6966
 
6902
6967
  // src/state.ts
6903
- import { readFileSync as readFileSync20, writeFileSync as writeFileSync15, existsSync as existsSync19, mkdirSync as mkdirSync14, rmSync as rmSync10, statSync as statSync7, readdirSync as readdirSync6 } from "fs";
6904
- import { join as join22 } from "path";
6968
+ import { readFileSync as readFileSync21, writeFileSync as writeFileSync16, existsSync as existsSync20, mkdirSync as mkdirSync15, rmSync as rmSync11, statSync as statSync7, readdirSync as readdirSync6 } from "fs";
6969
+ import { join as join23 } from "path";
6905
6970
  var EPOCH = "1970-01-01T00:00:00.000Z";
6906
6971
  var watermarkFile = (scope) => scope ? `.poll-watermark-${scope}` : ".poll-watermark";
6907
6972
  var State = class _State {
6908
6973
  dir;
6909
6974
  constructor(dir) {
6910
6975
  this.dir = dir;
6911
- mkdirSync14(dir, { recursive: true });
6976
+ mkdirSync15(dir, { recursive: true });
6912
6977
  }
6913
6978
  path(...parts) {
6914
- return join22(this.dir, ...parts);
6979
+ return join23(this.dir, ...parts);
6915
6980
  }
6916
6981
  /**
6917
6982
  * The timestamp every "new since last poll" check is measured against.
@@ -6922,7 +6987,7 @@ var State = class _State {
6922
6987
  */
6923
6988
  watermark(scope) {
6924
6989
  try {
6925
- const v = readFileSync20(this.path(watermarkFile(scope)), "utf8").trim();
6990
+ const v = readFileSync21(this.path(watermarkFile(scope)), "utf8").trim();
6926
6991
  return v || EPOCH;
6927
6992
  } catch {
6928
6993
  if (scope) return this.watermark();
@@ -6930,7 +6995,7 @@ var State = class _State {
6930
6995
  }
6931
6996
  }
6932
6997
  setWatermark(at, scope) {
6933
- writeFileSync15(this.path(watermarkFile(scope)), `${at}
6998
+ writeFileSync16(this.path(watermarkFile(scope)), `${at}
6934
6999
  `);
6935
7000
  }
6936
7001
  /**
@@ -6948,19 +7013,19 @@ var State = class _State {
6948
7013
  }
6949
7014
  /** Whole-crew pause, and the per-role sentinels one level down. */
6950
7015
  isPaused() {
6951
- return existsSync19(this.path(".crew-paused"));
7016
+ return existsSync20(this.path(".crew-paused"));
6952
7017
  }
6953
7018
  isRolePaused(role) {
6954
- return existsSync19(this.path(`.role-paused-${role}`));
7019
+ return existsSync20(this.path(`.role-paused-${role}`));
6955
7020
  }
6956
7021
  pausedRoles(roles) {
6957
7022
  return new Set(roles.filter((r) => this.isRolePaused(r)));
6958
7023
  }
6959
7024
  pause(role) {
6960
- writeFileSync15(role ? this.path(`.role-paused-${role}`) : this.path(".crew-paused"), "");
7025
+ writeFileSync16(role ? this.path(`.role-paused-${role}`) : this.path(".crew-paused"), "");
6961
7026
  }
6962
7027
  resume(role) {
6963
- rmSync10(role ? this.path(`.role-paused-${role}`) : this.path(".crew-paused"), { force: true });
7028
+ rmSync11(role ? this.path(`.role-paused-${role}`) : this.path(".crew-paused"), { force: true });
6964
7029
  }
6965
7030
  /**
6966
7031
  * The release phase (merge, deploy, release) has its own sentinel, one
@@ -6968,11 +7033,11 @@ var State = class _State {
6968
7033
  * while agents keep working.
6969
7034
  */
6970
7035
  isReleasePaused() {
6971
- return existsSync19(this.path(".release-paused"));
7036
+ return existsSync20(this.path(".release-paused"));
6972
7037
  }
6973
7038
  setReleasePaused(paused) {
6974
- if (paused) writeFileSync15(this.path(".release-paused"), "");
6975
- else rmSync10(this.path(".release-paused"), { force: true });
7039
+ if (paused) writeFileSync16(this.path(".release-paused"), "");
7040
+ else rmSync11(this.path(".release-paused"), { force: true });
6976
7041
  }
6977
7042
  /**
6978
7043
  * Why a release cycle must not run right now, or null when it may. Every
@@ -7009,7 +7074,7 @@ var State = class _State {
7009
7074
  const name = _State.safe(rawName);
7010
7075
  const file = this.path(`.${name}.lock`);
7011
7076
  try {
7012
- const existing = Number.parseInt(readFileSync20(file, "utf8").trim(), 10);
7077
+ const existing = Number.parseInt(readFileSync21(file, "utf8").trim(), 10);
7013
7078
  if (Number.isFinite(existing) && existing > 0) {
7014
7079
  try {
7015
7080
  process.kill(existing, 0);
@@ -7019,13 +7084,13 @@ var State = class _State {
7019
7084
  }
7020
7085
  } catch {
7021
7086
  }
7022
- writeFileSync15(file, `${process.pid}
7087
+ writeFileSync16(file, `${process.pid}
7023
7088
  `);
7024
7089
  return {
7025
7090
  ok: true,
7026
7091
  release: () => {
7027
7092
  try {
7028
- rmSync10(file, { force: true });
7093
+ rmSync11(file, { force: true });
7029
7094
  } catch {
7030
7095
  }
7031
7096
  }
@@ -7047,7 +7112,7 @@ var State = class _State {
7047
7112
  if (!/^\.release-.+\.lock$/.test(n)) continue;
7048
7113
  let pid = 0;
7049
7114
  try {
7050
- pid = Number.parseInt(readFileSync20(this.path(n), "utf8").trim(), 10);
7115
+ pid = Number.parseInt(readFileSync21(this.path(n), "utf8").trim(), 10);
7051
7116
  } catch {
7052
7117
  continue;
7053
7118
  }
@@ -7133,7 +7198,7 @@ var State = class _State {
7133
7198
  ticketInFlight(recordId) {
7134
7199
  const file = this.path(`.${_State.safe(`crew-ticket-${recordId}`)}.lock`);
7135
7200
  try {
7136
- const pid = Number.parseInt(readFileSync20(file, "utf8").trim(), 10);
7201
+ const pid = Number.parseInt(readFileSync21(file, "utf8").trim(), 10);
7137
7202
  if (!Number.isFinite(pid) || pid <= 0) return false;
7138
7203
  process.kill(pid, 0);
7139
7204
  return true;
@@ -7167,7 +7232,7 @@ var State = class _State {
7167
7232
  const heldReported = `.release-held-${suffix}`;
7168
7233
  const read = (f) => {
7169
7234
  try {
7170
- return readFileSync20(this.path(f), "utf8").trim() || null;
7235
+ return readFileSync21(this.path(f), "utf8").trim() || null;
7171
7236
  } catch {
7172
7237
  return null;
7173
7238
  }
@@ -7176,12 +7241,12 @@ var State = class _State {
7176
7241
  blockedCount: () => Number.parseInt(read(blocked) ?? "", 10) || 0,
7177
7242
  noteBlocked: () => {
7178
7243
  const n = (Number.parseInt(read(blocked) ?? "", 10) || 0) + 1;
7179
- writeFileSync15(this.path(blocked), `${n}
7244
+ writeFileSync16(this.path(blocked), `${n}
7180
7245
  `);
7181
7246
  return n;
7182
7247
  },
7183
7248
  clearBlocked: () => {
7184
- rmSync10(this.path(blocked), { force: true });
7249
+ rmSync11(this.path(blocked), { force: true });
7185
7250
  },
7186
7251
  /**
7187
7252
  * The commit a deploy last failed on.
@@ -7193,11 +7258,11 @@ var State = class _State {
7193
7258
  */
7194
7259
  deployFailedSha: () => read(failed),
7195
7260
  noteDeployFailed: (sha) => {
7196
- writeFileSync15(this.path(failed), `${sha}
7261
+ writeFileSync16(this.path(failed), `${sha}
7197
7262
  `);
7198
7263
  },
7199
7264
  clearDeployFailed: () => {
7200
- rmSync10(this.path(failed), { force: true });
7265
+ rmSync11(this.path(failed), { force: true });
7201
7266
  },
7202
7267
  /**
7203
7268
  * Consecutive test-gate failures on the same head (CREW-1368). A failure
@@ -7207,31 +7272,31 @@ var State = class _State {
7207
7272
  noteTestGateFailed: (sha) => {
7208
7273
  const [prev, n] = (read(gateFailed) ?? "").split(" ");
7209
7274
  const next = prev === sha ? (Number.parseInt(n ?? "", 10) || 0) + 1 : 1;
7210
- writeFileSync15(this.path(gateFailed), `${sha} ${next}
7275
+ writeFileSync16(this.path(gateFailed), `${sha} ${next}
7211
7276
  `);
7212
7277
  return next;
7213
7278
  },
7214
7279
  clearTestGateFailed: () => {
7215
- rmSync10(this.path(gateFailed), { force: true });
7280
+ rmSync11(this.path(gateFailed), { force: true });
7216
7281
  },
7217
7282
  /** Whether the board was already told about this head's red gate. */
7218
7283
  heldReported: () => {
7219
7284
  try {
7220
- return readFileSync20(this.path(heldReported), "utf8").replace(/\n$/, "") || null;
7285
+ return readFileSync21(this.path(heldReported), "utf8").replace(/\n$/, "") || null;
7221
7286
  } catch {
7222
7287
  return null;
7223
7288
  }
7224
7289
  },
7225
7290
  noteHeldReported: (signature) => {
7226
- writeFileSync15(this.path(heldReported), `${signature}
7291
+ writeFileSync16(this.path(heldReported), `${signature}
7227
7292
  `);
7228
7293
  },
7229
7294
  clearHeldReported: () => {
7230
- rmSync10(this.path(heldReported), { force: true });
7295
+ rmSync11(this.path(heldReported), { force: true });
7231
7296
  },
7232
7297
  testGateReported: (sha) => read(gateReported) === sha,
7233
7298
  noteTestGateReported: (sha) => {
7234
- writeFileSync15(this.path(gateReported), `${sha}
7299
+ writeFileSync16(this.path(gateReported), `${sha}
7235
7300
  `);
7236
7301
  }
7237
7302
  };
@@ -7254,13 +7319,13 @@ var State = class _State {
7254
7319
  const ticketStreakFile = `.fairness-ticket-streak-${suffix}`;
7255
7320
  const read = (f) => {
7256
7321
  try {
7257
- return readFileSync20(this.path(f), "utf8").trim() || null;
7322
+ return readFileSync21(this.path(f), "utf8").trim() || null;
7258
7323
  } catch {
7259
7324
  return null;
7260
7325
  }
7261
7326
  };
7262
7327
  const clear2 = () => {
7263
- for (const f of [streakFile, ticketFile, sinceFile, ticketStreakFile]) rmSync10(this.path(f), { force: true });
7328
+ for (const f of [streakFile, ticketFile, sinceFile, ticketStreakFile]) rmSync11(this.path(f), { force: true });
7264
7329
  };
7265
7330
  return {
7266
7331
  /** Consecutive cycles this route had actionable work and did not win. */
@@ -7287,18 +7352,18 @@ var State = class _State {
7287
7352
  clear2();
7288
7353
  return;
7289
7354
  }
7290
- writeFileSync15(this.path(streakFile), `${this.readInt(streakFile) + 1}
7355
+ writeFileSync16(this.path(streakFile), `${this.readInt(streakFile) + 1}
7291
7356
  `);
7292
7357
  const prior = read(ticketFile);
7293
7358
  if (topTicket && topTicket === prior) {
7294
- writeFileSync15(this.path(ticketStreakFile), `${this.readInt(ticketStreakFile) + 1}
7359
+ writeFileSync16(this.path(ticketStreakFile), `${this.readInt(ticketStreakFile) + 1}
7295
7360
  `);
7296
7361
  } else if (topTicket) {
7297
- writeFileSync15(this.path(ticketFile), `${topTicket}
7362
+ writeFileSync16(this.path(ticketFile), `${topTicket}
7298
7363
  `);
7299
- writeFileSync15(this.path(sinceFile), `${(/* @__PURE__ */ new Date()).toISOString()}
7364
+ writeFileSync16(this.path(sinceFile), `${(/* @__PURE__ */ new Date()).toISOString()}
7300
7365
  `);
7301
- writeFileSync15(this.path(ticketStreakFile), "1\n");
7366
+ writeFileSync16(this.path(ticketStreakFile), "1\n");
7302
7367
  }
7303
7368
  }
7304
7369
  };
@@ -7319,14 +7384,14 @@ var State = class _State {
7319
7384
  return {
7320
7385
  previous: () => {
7321
7386
  try {
7322
- const parsed = JSON.parse(readFileSync20(this.path(file), "utf8"));
7387
+ const parsed = JSON.parse(readFileSync21(this.path(file), "utf8"));
7323
7388
  return parsed && typeof parsed === "object" ? parsed : {};
7324
7389
  } catch {
7325
7390
  return {};
7326
7391
  }
7327
7392
  },
7328
7393
  persist: (next) => {
7329
- writeFileSync15(this.path(file), JSON.stringify(next));
7394
+ writeFileSync16(this.path(file), JSON.stringify(next));
7330
7395
  }
7331
7396
  };
7332
7397
  }
@@ -7342,14 +7407,14 @@ var State = class _State {
7342
7407
  return {
7343
7408
  previous: () => {
7344
7409
  try {
7345
- const parsed = JSON.parse(readFileSync20(this.path(file), "utf8"));
7410
+ const parsed = JSON.parse(readFileSync21(this.path(file), "utf8"));
7346
7411
  return Array.isArray(parsed) ? parsed.filter((x) => typeof x === "string") : [];
7347
7412
  } catch {
7348
7413
  return [];
7349
7414
  }
7350
7415
  },
7351
7416
  persist: (next) => {
7352
- writeFileSync15(this.path(file), JSON.stringify(next));
7417
+ writeFileSync16(this.path(file), JSON.stringify(next));
7353
7418
  }
7354
7419
  };
7355
7420
  }
@@ -7363,14 +7428,14 @@ var State = class _State {
7363
7428
  return {
7364
7429
  previous: () => {
7365
7430
  try {
7366
- const parsed = JSON.parse(readFileSync20(this.path(file), "utf8"));
7431
+ const parsed = JSON.parse(readFileSync21(this.path(file), "utf8"));
7367
7432
  return Array.isArray(parsed) ? parsed : [];
7368
7433
  } catch {
7369
7434
  return [];
7370
7435
  }
7371
7436
  },
7372
7437
  persist: (next) => {
7373
- writeFileSync15(this.path(file), JSON.stringify(next));
7438
+ writeFileSync16(this.path(file), JSON.stringify(next));
7374
7439
  }
7375
7440
  };
7376
7441
  }
@@ -7383,7 +7448,7 @@ var State = class _State {
7383
7448
  const file = ".release-last-run";
7384
7449
  return {
7385
7450
  touch: () => {
7386
- writeFileSync15(this.path(file), (/* @__PURE__ */ new Date()).toISOString());
7451
+ writeFileSync16(this.path(file), (/* @__PURE__ */ new Date()).toISOString());
7387
7452
  },
7388
7453
  at: () => {
7389
7454
  try {
@@ -7396,7 +7461,7 @@ var State = class _State {
7396
7461
  }
7397
7462
  readInt(file) {
7398
7463
  try {
7399
- return Number.parseInt(readFileSync20(this.path(file), "utf8").trim(), 10) || 0;
7464
+ return Number.parseInt(readFileSync21(this.path(file), "utf8").trim(), 10) || 0;
7400
7465
  } catch {
7401
7466
  return 0;
7402
7467
  }
@@ -7404,7 +7469,7 @@ var State = class _State {
7404
7469
  };
7405
7470
 
7406
7471
  // src/signed-out.ts
7407
- import { readFileSync as readFileSync21 } from "fs";
7472
+ import { readFileSync as readFileSync22 } from "fs";
7408
7473
  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;
7409
7474
  function authModeOf(spec, hostEnv = process.env) {
7410
7475
  const env = { ...hostEnv, ...spec.env };
@@ -7451,7 +7516,7 @@ function eventsShowSignedOut(events) {
7451
7516
  function streamShowsSignedOut(streamPath) {
7452
7517
  let raw;
7453
7518
  try {
7454
- raw = readFileSync21(streamPath, "utf8");
7519
+ raw = readFileSync22(streamPath, "utf8");
7455
7520
  } catch {
7456
7521
  return false;
7457
7522
  }
@@ -7469,7 +7534,7 @@ function streamShowsSignedOut(streamPath) {
7469
7534
  function streamShowsRealTurn(streamPath) {
7470
7535
  let raw;
7471
7536
  try {
7472
- raw = readFileSync21(streamPath, "utf8");
7537
+ raw = readFileSync22(streamPath, "utf8");
7473
7538
  } catch {
7474
7539
  return false;
7475
7540
  }
@@ -8412,8 +8477,8 @@ function renderEnvironment(i) {
8412
8477
  }
8413
8478
 
8414
8479
  // src/intel-bridge.ts
8415
- import { existsSync as existsSync20, mkdirSync as mkdirSync15, readFileSync as readFileSync22, rmSync as rmSync11, writeFileSync as writeFileSync16 } from "fs";
8416
- import { dirname as dirname11, join as join23 } from "path";
8480
+ import { existsSync as existsSync21, mkdirSync as mkdirSync16, readFileSync as readFileSync23, rmSync as rmSync12, writeFileSync as writeFileSync17 } from "fs";
8481
+ import { dirname as dirname12, join as join24 } from "path";
8417
8482
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
8418
8483
  import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
8419
8484
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
@@ -8429,17 +8494,17 @@ var statusFailed = (reason) => `The symbol service did not start (${reason}). Ru
8429
8494
  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.";
8430
8495
  function intelDir(stateDir, route2, ticket) {
8431
8496
  const safe = (s) => s.replace(/[^A-Za-z0-9._-]+/g, "_");
8432
- return join23(stateDir, "intel", safe(route2), safe(ticket));
8497
+ return join24(stateDir, "intel", safe(route2), safe(ticket));
8433
8498
  }
8434
- var attachFilePath = (stateDir, route2, ticket) => join23(intelDir(stateDir, route2, ticket), "url");
8499
+ var attachFilePath = (stateDir, route2, ticket) => join24(intelDir(stateDir, route2, ticket), "url");
8435
8500
  function writeAttachFile(file, url) {
8436
- mkdirSync15(dirname11(file), { recursive: true });
8437
- writeFileSync16(file, `${url}
8501
+ mkdirSync16(dirname12(file), { recursive: true });
8502
+ writeFileSync17(file, `${url}
8438
8503
  `);
8439
8504
  }
8440
8505
  function readAttachFile(file) {
8441
8506
  try {
8442
- const url = readFileSync22(file, "utf8").trim();
8507
+ const url = readFileSync23(file, "utf8").trim();
8443
8508
  return /^https?:\/\/\S+$/i.test(url) ? url : void 0;
8444
8509
  } catch {
8445
8510
  return void 0;
@@ -8561,7 +8626,7 @@ function createBridge(o) {
8561
8626
  tryAttach,
8562
8627
  async start(transport) {
8563
8628
  await server.connect(transport);
8564
- if (existsSync20(o.attachFile)) await tryAttach();
8629
+ if (existsSync21(o.attachFile)) await tryAttach();
8565
8630
  timer = setInterval(() => {
8566
8631
  void tryAttach();
8567
8632
  }, o.pollMs ?? 1e3);
@@ -8818,14 +8883,14 @@ var BeforeFirstEditTracker = class {
8818
8883
  };
8819
8884
 
8820
8885
  // src/agent-log.ts
8821
- import { existsSync as existsSync24, mkdirSync as mkdirSync17, readdirSync as readdirSync8, readFileSync as readFileSync24, rmSync as rmSync13, writeFileSync as writeFileSync18 } from "fs";
8822
- import { join as join26 } from "path";
8886
+ import { existsSync as existsSync25, mkdirSync as mkdirSync18, readdirSync as readdirSync8, readFileSync as readFileSync25, rmSync as rmSync14, writeFileSync as writeFileSync19 } from "fs";
8887
+ import { join as join27 } from "path";
8823
8888
 
8824
8889
  // src/pending-backoff.ts
8825
8890
  var sleepBackoff = (attempts) => Math.min(6e4 * 2 ** Math.max(0, attempts - 1), 30 * 6e4);
8826
8891
 
8827
8892
  // src/handoff-guard.ts
8828
- import { existsSync as existsSync23 } from "fs";
8893
+ import { existsSync as existsSync24 } from "fs";
8829
8894
 
8830
8895
  // src/ticket-branch.ts
8831
8896
  import { basename as basename7 } from "path";
@@ -9911,23 +9976,23 @@ function materializeBranchForTicket(dir, cfg, t, role, onProblem, onReset) {
9911
9976
  }
9912
9977
 
9913
9978
  // src/pending-handoff.ts
9914
- import { existsSync as existsSync21, mkdirSync as mkdirSync16, readdirSync as readdirSync7, readFileSync as readFileSync23, rmSync as rmSync12, writeFileSync as writeFileSync17 } from "fs";
9915
- import { join as join24 } from "path";
9979
+ import { existsSync as existsSync22, mkdirSync as mkdirSync17, readdirSync as readdirSync7, readFileSync as readFileSync24, rmSync as rmSync13, writeFileSync as writeFileSync18 } from "fs";
9980
+ import { join as join25 } from "path";
9916
9981
  var PENDING_MAX_AGE_MS = 48 * 36e5;
9917
- var pendingDirFor = (stateDir) => join24(stateDir, "pending-handoffs");
9918
- var stateDirOfStream = (streamPath) => join24(streamPath, "..", "..");
9982
+ var pendingDirFor = (stateDir) => join25(stateDir, "pending-handoffs");
9983
+ var stateDirOfStream = (streamPath) => join25(streamPath, "..", "..");
9919
9984
  function writePendingHandoff(stateDir, rec) {
9920
9985
  const dir = pendingDirFor(stateDir);
9921
- mkdirSync16(dir, { recursive: true });
9922
- writeFileSync17(join24(dir, `${rec.ticketRecordId}.json`), JSON.stringify(rec, null, 2));
9986
+ mkdirSync17(dir, { recursive: true });
9987
+ writeFileSync18(join25(dir, `${rec.ticketRecordId}.json`), JSON.stringify(rec, null, 2));
9923
9988
  }
9924
9989
  function listPendingHandoffs(stateDir, route2) {
9925
9990
  const dir = pendingDirFor(stateDir);
9926
- if (!existsSync21(dir)) return [];
9991
+ if (!existsSync22(dir)) return [];
9927
9992
  const out = [];
9928
9993
  for (const f of readdirSync7(dir).filter((n) => n.endsWith(".json")).sort()) {
9929
9994
  try {
9930
- const rec = JSON.parse(readFileSync23(join24(dir, f), "utf8"));
9995
+ const rec = JSON.parse(readFileSync24(join25(dir, f), "utf8"));
9931
9996
  if (rec.version === 1 && rec.ticketRecordId && (!route2 || rec.route === route2)) out.push(rec);
9932
9997
  } catch {
9933
9998
  }
@@ -9935,7 +10000,7 @@ function listPendingHandoffs(stateDir, route2) {
9935
10000
  return out;
9936
10001
  }
9937
10002
  function removePendingHandoff(stateDir, ticketRecordId) {
9938
- rmSync12(join24(pendingDirFor(stateDir), `${ticketRecordId}.json`), { force: true });
10003
+ rmSync13(join25(pendingDirFor(stateDir), `${ticketRecordId}.json`), { force: true });
9939
10004
  }
9940
10005
  function pendingHandoffFor(stateDir, ticketRecordId) {
9941
10006
  return listPendingHandoffs(stateDir).find((r) => r.ticketRecordId === ticketRecordId);
@@ -10111,8 +10176,8 @@ function holdWarnings(tickets, ships, contract, humanHolds, now = Date.now()) {
10111
10176
  }
10112
10177
 
10113
10178
  // src/run-worktree.ts
10114
- import { existsSync as existsSync22 } from "fs";
10115
- import { dirname as dirname12, join as join25 } from "path";
10179
+ import { existsSync as existsSync23 } from "fs";
10180
+ import { dirname as dirname13, join as join26 } from "path";
10116
10181
  var describeRunWorktreePlan = (p) => {
10117
10182
  switch (p.action) {
10118
10183
  case "cut-remote":
@@ -10153,7 +10218,7 @@ function planRunWorktree(dir, cfg, t, role, opts = {}) {
10153
10218
  const existing = worktreeForNumber(dir, num2);
10154
10219
  const located = locateBranchForTicket(dir, cfg, t, role);
10155
10220
  const baseRef = hasRemote ? `${remote}/${base}` : base;
10156
- if (existing && !existing.prunable && existsSync22(existing.path)) {
10221
+ if (existing && !existing.prunable && existsSync23(existing.path)) {
10157
10222
  const branch = existing.branch;
10158
10223
  if (status(existing.path).length > 0) {
10159
10224
  return { action: opts.resumeInterrupted ? "resume-dirty" : "leave-dirty", path: existing.path, branch };
@@ -10169,7 +10234,7 @@ function planRunWorktree(dir, cfg, t, role, opts = {}) {
10169
10234
  if (countCommits(existing.path, `${baseRef}..HEAD`) > 0) return { action: "leave-unpushed", path: existing.path, branch };
10170
10235
  return { action: "recut", path: existing.path, branch, base: baseRef };
10171
10236
  }
10172
- const path = join25(dirname12(dir), worktreeForTicket(dir, cfg, t, role));
10237
+ const path = join26(dirname13(dir), worktreeForTicket(dir, cfg, t, role));
10173
10238
  if (located?.where === "remote" || located && hasRemote && remoteBranchExists(dir, remote, located.branch)) {
10174
10239
  return { action: "cut-remote", path, branch: located.branch };
10175
10240
  }
@@ -10223,7 +10288,7 @@ function dropEmptyRunBranch(dir, cfg, branch) {
10223
10288
  if (remoteConfigured(dir, remote) && remoteBranchExists(dir, remote, branch)) return false;
10224
10289
  if (countCommits(dir, `${baseRef}..${branch}`) !== 0) return false;
10225
10290
  const wt = worktrees(dir).find((w) => w.branch === branch && !w.prunable && w.path !== dir);
10226
- if (wt && existsSync22(wt.path)) {
10291
+ if (wt && existsSync23(wt.path)) {
10227
10292
  if (status(wt.path).length > 0) return false;
10228
10293
  if (gitOk(dir, ["worktree", "remove", wt.path]) === null) return false;
10229
10294
  }
@@ -10231,7 +10296,7 @@ function dropEmptyRunBranch(dir, cfg, branch) {
10231
10296
  }
10232
10297
  async function finishRunWorktree(dir, cfg, branch) {
10233
10298
  const wt = worktrees(dir).find((w) => w.branch === branch && !w.prunable && w.path !== dir);
10234
- if (!wt || !existsSync22(wt.path)) return { kind: "none" };
10299
+ if (!wt || !existsSync23(wt.path)) return { kind: "none" };
10235
10300
  if (cfg.hooks.handoff) return { kind: "kept-handoff", path: wt.path };
10236
10301
  if (status(wt.path).length > 0) return { kind: "kept-dirty", path: wt.path };
10237
10302
  if (remoteConfigured(dir, cfg.branch.remote) && worktreeHoldsUnpushed(wt.path, cfg.branch.remote)) {
@@ -10243,7 +10308,7 @@ async function finishRunWorktree(dir, cfg, branch) {
10243
10308
  if (pids.length) await killGently(pids);
10244
10309
  }
10245
10310
  gitOk(dir, ["worktree", "remove", wt.path]);
10246
- return existsSync22(wt.path) ? { kind: "kept-dirty", path: wt.path } : { kind: "removed", path: wt.path };
10311
+ return existsSync23(wt.path) ? { kind: "kept-dirty", path: wt.path } : { kind: "removed", path: wt.path };
10247
10312
  }
10248
10313
 
10249
10314
  // src/handoff-guard.ts
@@ -10301,7 +10366,7 @@ function inspectRemoteHandoff(origin, cfg, ticket, role) {
10301
10366
  function describeGuardError(e, dir) {
10302
10367
  const msg = e.message;
10303
10368
  if (!/ENOENT/.test(msg)) return msg;
10304
- return dir && !existsSync23(dir) ? `the run's clone at ${dir} is gone` : "git is not installed on this machine";
10369
+ return dir && !existsSync24(dir) ? `the run's clone at ${dir} is gone` : "git is not installed on this machine";
10305
10370
  }
10306
10371
  function inspectHandoff(dir, cfg, ticket, role) {
10307
10372
  const remote = cfg.branch.remote;
@@ -10859,9 +10924,12 @@ async function writeHandoffBounces(target, rowId, count) {
10859
10924
  }
10860
10925
  }
10861
10926
  async function post(target, path, body) {
10927
+ return send(target, "POST", path, body);
10928
+ }
10929
+ async function send(target, method, path, body) {
10862
10930
  const url = `${target.baseUrl.replace(/\/+$/, "")}/api/workspaces/${target.workspaceId}${path}`;
10863
10931
  const res = await fetch(url, {
10864
- method: "POST",
10932
+ method,
10865
10933
  headers: {
10866
10934
  Authorization: `Bearer ${target.apiKey}`,
10867
10935
  // Cloudflare 403s default agents on this host — same header connect.ts sends.
@@ -10873,24 +10941,41 @@ async function post(target, path, body) {
10873
10941
  if (!res.ok) throw new AgentLogHttpError(`${path}: ${res.status} ${res.statusText}`, res.status);
10874
10942
  return await res.json();
10875
10943
  }
10876
- var RUNNING_OUTCOME = "running";
10877
10944
  async function startAgentRunRow(target, s) {
10945
+ if (!target.actor && !s.runId) return void 0;
10946
+ const body = {
10947
+ agentId: target.agentId,
10948
+ ticketReference: s.ticketReference,
10949
+ startedAt: s.startedAt,
10950
+ source: "client",
10951
+ client: "crew",
10952
+ model: s.model,
10953
+ promptVersion: s.promptVersion,
10954
+ promptSha: s.promptSha,
10955
+ runId: s.runId,
10956
+ harness: s.harness,
10957
+ provider: s.provider
10958
+ };
10959
+ let actor = {};
10960
+ if (target.actor) {
10961
+ let label = s.actorLabel;
10962
+ try {
10963
+ const row = await request(target, "GET", `/data-models/${target.actor.table}/records/${target.actor.recordId}`);
10964
+ if (row.name) label = row.name;
10965
+ } catch {
10966
+ }
10967
+ actor = { actorTable: target.actor.table, actorRecordId: target.actor.recordId, ...label ? { actorLabel: label } : {} };
10968
+ }
10878
10969
  try {
10879
- const entry = await post(target, "/agents/log", {
10880
- agentId: target.agentId,
10881
- ticketReference: s.ticketReference,
10882
- outcome: RUNNING_OUTCOME,
10883
- startedAt: s.startedAt,
10884
- source: "client",
10885
- client: "crew",
10886
- model: s.model,
10887
- promptVersion: s.promptVersion,
10888
- promptSha: s.promptSha,
10889
- runId: s.runId,
10890
- harness: s.harness,
10891
- provider: s.provider
10892
- });
10893
- return entry.id;
10970
+ const entry = await post(target, "/agents/log", { ...body, ...actor });
10971
+ return { id: entry.id, live: target.actor !== void 0 };
10972
+ } catch (e) {
10973
+ if (!(e instanceof AgentLogHttpError) || e.status !== 400 || Object.keys(actor).length === 0) return void 0;
10974
+ }
10975
+ if (!s.runId) return void 0;
10976
+ try {
10977
+ const entry = await post(target, "/agents/log", body);
10978
+ return { id: entry.id, live: false };
10894
10979
  } catch {
10895
10980
  return void 0;
10896
10981
  }
@@ -10936,6 +11021,154 @@ async function updateStartedRow(target, rowId, body) {
10936
11021
  throw e;
10937
11022
  }
10938
11023
  }
11024
+ async function markMessage(target, rowId, messageId, state) {
11025
+ try {
11026
+ await send(target, "PATCH", `/agents/log/${rowId}/messages/${messageId}`, { deliveryState: state });
11027
+ return true;
11028
+ } catch {
11029
+ return false;
11030
+ }
11031
+ }
11032
+ async function fetchPendingMessages(target, workItem) {
11033
+ try {
11034
+ const res = await request(
11035
+ target,
11036
+ "GET",
11037
+ `/workspaces/${target.workspaceId}/agents/log/pending-messages?workItem=${encodeURIComponent(`${workItem.table}:${workItem.recordId}`)}`
11038
+ );
11039
+ return Array.isArray(res.messages) ? res.messages : [];
11040
+ } catch {
11041
+ return [];
11042
+ }
11043
+ }
11044
+ async function memberNames(target) {
11045
+ const names = /* @__PURE__ */ new Map();
11046
+ try {
11047
+ const rows = await request(target, "GET", `/workspaces/${target.workspaceId}/members`);
11048
+ for (const m of Array.isArray(rows) ? rows : []) {
11049
+ const n = m.name || m.email;
11050
+ if (n) names.set(m.id, n);
11051
+ }
11052
+ } catch {
11053
+ }
11054
+ return names;
11055
+ }
11056
+ function frameNote(m, author2) {
11057
+ return `Note from ${author2 ?? "the operator"} (operator): ${m.text}`;
11058
+ }
11059
+ function operatorNotesSection(notes, names) {
11060
+ if (notes.length === 0) return "";
11061
+ const lines2 = notes.map((m) => {
11062
+ const who2 = m.authorId && names.get(m.authorId) || "the operator";
11063
+ return `- ${m.occurredAt ?? "earlier"} \u2014 ${who2}: ${m.text.replace(/\n/g, "\n ")}`;
11064
+ });
11065
+ return [
11066
+ "## Operator notes since the last run",
11067
+ "",
11068
+ "A person responsible for this work left these notes while no run could read them. They carry the operator's authority, within the limits of your persona and the rules above; acknowledge them in your first text turn.",
11069
+ "",
11070
+ ...lines2
11071
+ ].join("\n");
11072
+ }
11073
+ var CYCLE_BODY_LIMIT_BYTES = 2048;
11074
+ var CYCLE_TRUNCATION_MARKER = " \u2026[truncated]";
11075
+ var MAX_CYCLES_PER_BATCH = 200;
11076
+ function capCycleText(text2) {
11077
+ if (Buffer.byteLength(text2) <= CYCLE_BODY_LIMIT_BYTES) return text2;
11078
+ const room = CYCLE_BODY_LIMIT_BYTES - Buffer.byteLength(CYCLE_TRUNCATION_MARKER);
11079
+ let out = text2.slice(0, room);
11080
+ while (Buffer.byteLength(out) > room) out = out.slice(0, -1);
11081
+ return out + CYCLE_TRUNCATION_MARKER;
11082
+ }
11083
+ var LiveRunReporter = class {
11084
+ /** Cycles delivered to the row, from the start of the run. */
11085
+ posted = 0;
11086
+ live = true;
11087
+ nextIndex = 0;
11088
+ pending = [];
11089
+ seenMessages = /* @__PURE__ */ new Set();
11090
+ lastSent = Date.now();
11091
+ timer;
11092
+ inFlight = Promise.resolve();
11093
+ windowMs;
11094
+ heartbeatMs;
11095
+ target;
11096
+ rowId;
11097
+ o;
11098
+ constructor(target, rowId, o = {}, alreadyPosted = 0) {
11099
+ this.target = target;
11100
+ this.rowId = rowId;
11101
+ this.o = o;
11102
+ this.windowMs = o.windowMs ?? 4e3;
11103
+ this.heartbeatMs = o.heartbeatMs ?? 3e4;
11104
+ this.posted = alreadyPosted;
11105
+ this.nextIndex = alreadyPosted;
11106
+ }
11107
+ start() {
11108
+ if (this.timer || !this.live) return;
11109
+ this.timer = setInterval(() => {
11110
+ void this.tick();
11111
+ }, this.windowMs);
11112
+ this.timer.unref?.();
11113
+ }
11114
+ /** Buffers one cycle for the next batch. A cycle already delivered or buffered is ignored. */
11115
+ add(c) {
11116
+ if (!this.live || c.cycleIndex < this.nextIndex) return;
11117
+ this.nextIndex = c.cycleIndex + 1;
11118
+ this.pending.push({ ...c, thinking: capCycleText(c.thinking) });
11119
+ }
11120
+ /** One window: send the buffered cycles, or a heartbeat when idle too long. Serialized. */
11121
+ tick() {
11122
+ this.inFlight = this.inFlight.then(() => this.step());
11123
+ return this.inFlight;
11124
+ }
11125
+ /** Stops the timer and waits out a send in flight. What is still buffered is left to the end-of-run report. */
11126
+ async stop() {
11127
+ if (this.timer) clearInterval(this.timer);
11128
+ this.timer = void 0;
11129
+ await this.inFlight;
11130
+ }
11131
+ /** Passes the response's not-yet-seen notes to `onMessages`. A failing callback never disturbs reporting. */
11132
+ async handOver(res) {
11133
+ const fresh = (Array.isArray(res?.pendingMessages) ? res.pendingMessages : []).filter((m) => m && typeof m.id === "string" && !this.seenMessages.has(m.id));
11134
+ if (fresh.length === 0 || !this.o.onMessages) return;
11135
+ for (const m of fresh) this.seenMessages.add(m.id);
11136
+ try {
11137
+ await this.o.onMessages(fresh);
11138
+ } catch {
11139
+ }
11140
+ }
11141
+ async step() {
11142
+ if (!this.live) return;
11143
+ try {
11144
+ if (this.pending.length > 0) {
11145
+ const batch = this.pending.slice(0, MAX_CYCLES_PER_BATCH);
11146
+ const res = await post(this.target, `/agents/log/${this.rowId}/cycles`, batch.map((c) => ({
11147
+ cycleIndex: c.cycleIndex,
11148
+ occurredAt: c.occurredAt,
11149
+ thinking: c.thinking,
11150
+ ...c.role ? { role: c.role } : {}
11151
+ })));
11152
+ this.pending.splice(0, batch.length);
11153
+ this.posted = batch[batch.length - 1].cycleIndex + 1;
11154
+ this.lastSent = Date.now();
11155
+ this.o.onPosted?.(this.posted);
11156
+ await this.handOver(res);
11157
+ } else if (Date.now() - this.lastSent >= this.heartbeatMs) {
11158
+ const res = await send(this.target, "PATCH", `/agents/log/${this.rowId}`, {});
11159
+ this.lastSent = Date.now();
11160
+ await this.handOver(res);
11161
+ }
11162
+ } catch (e) {
11163
+ if (e instanceof AgentLogHttpError && e.status < 500) {
11164
+ this.live = false;
11165
+ if (this.timer) clearInterval(this.timer);
11166
+ this.timer = void 0;
11167
+ this.pending.length = 0;
11168
+ }
11169
+ }
11170
+ }
11171
+ };
10939
11172
  async function reportAgentRun(target, run4) {
10940
11173
  let ticketRecordId;
10941
11174
  if (target.tickets && run4.ticketReference) {
@@ -10985,7 +11218,7 @@ async function reportAgentRun(target, run4) {
10985
11218
  }
10986
11219
  }
10987
11220
  }
10988
- for (const cycle of run4.cycles) {
11221
+ for (const cycle of run4.cycles.slice(run4.cyclesPosted ?? 0)) {
10989
11222
  await post(target, `/agents/log/${entry.id}/cycles`, {
10990
11223
  cycleIndex: cycle.cycleIndex,
10991
11224
  occurredAt: cycle.occurredAt,
@@ -11041,20 +11274,20 @@ async function addRunToTicket(target, t, recordId, run4) {
11041
11274
  };
11042
11275
  }
11043
11276
  }
11044
- var queueDir = (stateDir) => join26(stateDir, "pending-agent-logs");
11277
+ var queueDir = (stateDir) => join27(stateDir, "pending-agent-logs");
11045
11278
  function queueAgentRun(stateDir, name, q2) {
11046
- mkdirSync17(queueDir(stateDir), { recursive: true });
11047
- writeFileSync18(join26(queueDir(stateDir), `${name}.json`), JSON.stringify(q2));
11279
+ mkdirSync18(queueDir(stateDir), { recursive: true });
11280
+ writeFileSync19(join27(queueDir(stateDir), `${name}.json`), JSON.stringify(q2));
11048
11281
  }
11049
11282
  async function replayQueuedAgentRuns(stateDir, route2, keyFor, log, now = /* @__PURE__ */ new Date()) {
11050
11283
  const dir = queueDir(stateDir);
11051
- if (!existsSync24(dir)) return 0;
11284
+ if (!existsSync25(dir)) return 0;
11052
11285
  let sent = 0;
11053
11286
  for (const f of readdirSync8(dir).filter((n) => n.endsWith(".json")).sort()) {
11054
- const path = join26(dir, f);
11287
+ const path = join27(dir, f);
11055
11288
  let q2;
11056
11289
  try {
11057
- q2 = JSON.parse(readFileSync24(path, "utf8"));
11290
+ q2 = JSON.parse(readFileSync25(path, "utf8"));
11058
11291
  } catch {
11059
11292
  continue;
11060
11293
  }
@@ -11073,17 +11306,17 @@ async function replayQueuedAgentRuns(stateDir, route2, keyFor, log, now = /* @__
11073
11306
  attempts: 0,
11074
11307
  nextAttemptAt: (/* @__PURE__ */ new Date()).toISOString()
11075
11308
  });
11076
- rmSync13(path, { force: true });
11309
+ rmSync14(path, { force: true });
11077
11310
  sent += 1;
11078
11311
  log.emit(`sent a queued Agent Log report (${f})`);
11079
11312
  } catch (e) {
11080
11313
  if (!(e instanceof AgentLogUnreachableError)) {
11081
- rmSync13(path, { force: true });
11314
+ rmSync14(path, { force: true });
11082
11315
  log.warn(`dropped a queued Agent Log report (${f}): ${e.message}`);
11083
11316
  continue;
11084
11317
  }
11085
11318
  const attempts = q2.attempts + 1;
11086
- writeFileSync18(path, JSON.stringify({
11319
+ writeFileSync19(path, JSON.stringify({
11087
11320
  ...q2,
11088
11321
  attempts,
11089
11322
  warned: true,
@@ -11094,20 +11327,20 @@ async function replayQueuedAgentRuns(stateDir, route2, keyFor, log, now = /* @__
11094
11327
  }
11095
11328
  return sent;
11096
11329
  }
11097
- var countersDir = (stateDir) => join26(stateDir, "pending-ticket-counters");
11330
+ var countersDir = (stateDir) => join27(stateDir, "pending-ticket-counters");
11098
11331
  function queueTicketCounters(stateDir, name, q2) {
11099
- mkdirSync17(countersDir(stateDir), { recursive: true });
11100
- writeFileSync18(join26(countersDir(stateDir), `${name}.json`), JSON.stringify(q2));
11332
+ mkdirSync18(countersDir(stateDir), { recursive: true });
11333
+ writeFileSync19(join27(countersDir(stateDir), `${name}.json`), JSON.stringify(q2));
11101
11334
  }
11102
11335
  async function replayQueuedTicketCounters(stateDir, route2, keyFor, log, now = /* @__PURE__ */ new Date()) {
11103
11336
  const dir = countersDir(stateDir);
11104
- if (!existsSync24(dir)) return 0;
11337
+ if (!existsSync25(dir)) return 0;
11105
11338
  let sent = 0;
11106
11339
  for (const f of readdirSync8(dir).filter((n) => n.endsWith(".json")).sort()) {
11107
- const path = join26(dir, f);
11340
+ const path = join27(dir, f);
11108
11341
  let q2;
11109
11342
  try {
11110
- q2 = JSON.parse(readFileSync24(path, "utf8"));
11343
+ q2 = JSON.parse(readFileSync25(path, "utf8"));
11111
11344
  } catch {
11112
11345
  continue;
11113
11346
  }
@@ -11116,17 +11349,17 @@ async function replayQueuedTicketCounters(stateDir, route2, keyFor, log, now = /
11116
11349
  const apiKey = await keyFor(q2.role);
11117
11350
  if (!apiKey) continue;
11118
11351
  await writeCounters({ ...q2.target, apiKey }, q2.write);
11119
- rmSync13(path, { force: true });
11352
+ rmSync14(path, { force: true });
11120
11353
  sent += 1;
11121
11354
  log.emit(`added a queued run's spend to ${q2.write.ticketReference ?? q2.write.recordId} (${f})`);
11122
11355
  } catch (e) {
11123
11356
  if (!isRetryable(e)) {
11124
- rmSync13(path, { force: true });
11357
+ rmSync14(path, { force: true });
11125
11358
  log.warn(`dropped a queued ticket counter update (${f}): ${e.message}`);
11126
11359
  continue;
11127
11360
  }
11128
11361
  const attempts = q2.attempts + 1;
11129
- writeFileSync18(path, JSON.stringify({
11362
+ writeFileSync19(path, JSON.stringify({
11130
11363
  ...q2,
11131
11364
  attempts,
11132
11365
  warned: true,
@@ -11369,8 +11602,8 @@ var HandoffTranscriptTracker = class {
11369
11602
  import { createHash as createHash4 } from "crypto";
11370
11603
  import { spawn as spawn4 } from "child_process";
11371
11604
  import { execFileSync as execFileSync8 } from "child_process";
11372
- import { existsSync as existsSync25, mkdirSync as mkdirSync18, readFileSync as readFileSync25, renameSync as renameSync3, writeFileSync as writeFileSync19, rmSync as rmSync14, statSync as statSync8 } from "fs";
11373
- import { dirname as dirname13, join as join27 } from "path";
11605
+ import { existsSync as existsSync26, mkdirSync as mkdirSync19, readFileSync as readFileSync26, renameSync as renameSync4, writeFileSync as writeFileSync20, rmSync as rmSync15, statSync as statSync8 } from "fs";
11606
+ import { dirname as dirname14, join as join28 } from "path";
11374
11607
  import { fileURLToPath } from "url";
11375
11608
  import { tmpdir as tmpdir3 } from "os";
11376
11609
  var SANDBOX_BASE_IMAGE = "nvcr.io/nvidia/base/ubuntu:24.04";
@@ -11385,9 +11618,9 @@ var SANDBOX_UID = 1e3;
11385
11618
  var CREW_PREFIX = "/opt/crew";
11386
11619
  var SANDBOX_BRIDGE_PATH = `${CREW_PREFIX}/bin/intel-bridge`;
11387
11620
  function readBridgeBundle() {
11388
- const here = dirname13(fileURLToPath(import.meta.url));
11389
- for (const p of [join27(here, "sandbox-intel-bridge.cjs"), join27(here, "..", "dist", "sandbox-intel-bridge.cjs")]) {
11390
- if (existsSync25(p)) return readFileSync25(p, "utf8");
11621
+ const here = dirname14(fileURLToPath(import.meta.url));
11622
+ for (const p of [join28(here, "sandbox-intel-bridge.cjs"), join28(here, "..", "dist", "sandbox-intel-bridge.cjs")]) {
11623
+ if (existsSync26(p)) return readFileSync26(p, "utf8");
11391
11624
  }
11392
11625
  return void 0;
11393
11626
  }
@@ -11471,7 +11704,7 @@ var HOST_CA_BUNDLES = ["/etc/ssl/certs/ca-certificates.crt", "/etc/pki/tls/certs
11471
11704
  function readHostCaBundle(paths = HOST_CA_BUNDLES) {
11472
11705
  for (const path of paths) {
11473
11706
  try {
11474
- return readFileSync25(path, "utf8");
11707
+ return readFileSync26(path, "utf8");
11475
11708
  } catch {
11476
11709
  }
11477
11710
  }
@@ -11562,21 +11795,21 @@ function planSandbox(repo, decl, warm = {}, bridge) {
11562
11795
  }
11563
11796
  var SHIP_SANDBOX_KEY = "@ship";
11564
11797
  var shipSandboxRef = () => ({ name: SHIP_SANDBOX_KEY, decl: { packages: [], setup: [] } });
11565
- var sandboxStatePath = (stateDir) => join27(stateDir, "sandbox-images.json");
11798
+ var sandboxStatePath = (stateDir) => join28(stateDir, "sandbox-images.json");
11566
11799
  function readSandboxState(stateDir) {
11567
11800
  try {
11568
- const v = JSON.parse(readFileSync25(sandboxStatePath(stateDir), "utf8"));
11801
+ const v = JSON.parse(readFileSync26(sandboxStatePath(stateDir), "utf8"));
11569
11802
  return v && typeof v === "object" && !Array.isArray(v) ? v : {};
11570
11803
  } catch {
11571
11804
  return {};
11572
11805
  }
11573
11806
  }
11574
11807
  function writeSandboxState(stateDir, state) {
11575
- mkdirSync18(stateDir, { recursive: true });
11808
+ mkdirSync19(stateDir, { recursive: true });
11576
11809
  const file = sandboxStatePath(stateDir);
11577
- writeFileSync19(`${file}.tmp`, `${JSON.stringify(state, null, 2)}
11810
+ writeFileSync20(`${file}.tmp`, `${JSON.stringify(state, null, 2)}
11578
11811
  `);
11579
- renameSync3(`${file}.tmp`, file);
11812
+ renameSync4(`${file}.tmp`, file);
11580
11813
  }
11581
11814
  function sandboxImageFor(state, repo) {
11582
11815
  return state[repo]?.tags[0]?.tag ?? null;
@@ -11612,7 +11845,7 @@ var spawnBuildRunner = (engine = "docker") => (args, logPath) => new Promise((re
11612
11845
  child.stdout.on("data", (d) => chunks.push(d));
11613
11846
  child.stderr.on("data", (d) => chunks.push(d));
11614
11847
  const done = (code, extra = "") => {
11615
- writeFileSync19(logPath, `$ ${engine} ${args.join(" ")}
11848
+ writeFileSync20(logPath, `$ ${engine} ${args.join(" ")}
11616
11849
  ${Buffer.concat(chunks).toString("utf8")}${extra}`, { flag: "a" });
11617
11850
  resolve8(code);
11618
11851
  };
@@ -11634,7 +11867,7 @@ var engineRemoveImage = (engine = "docker", exec = realExec) => (tag) => {
11634
11867
  } catch {
11635
11868
  }
11636
11869
  };
11637
- var sandboxLogDir = (stateDir) => join27(stateDir, "sandbox-logs");
11870
+ var sandboxLogDir = (stateDir) => join28(stateDir, "sandbox-logs");
11638
11871
  async function buildSandboxImage(plan, deps) {
11639
11872
  const now = deps.now ?? (() => /* @__PURE__ */ new Date());
11640
11873
  const state = readSandboxState(deps.stateDir);
@@ -11643,21 +11876,21 @@ async function buildSandboxImage(plan, deps) {
11643
11876
  return { kind: "reused", tag: plan.tag };
11644
11877
  }
11645
11878
  const logDir = sandboxLogDir(deps.stateDir);
11646
- mkdirSync18(logDir, { recursive: true });
11647
- const logPath = join27(logDir, `${slug(plan.repo)}-${now().toISOString().replace(/[:.]/g, "-")}.log`);
11879
+ mkdirSync19(logDir, { recursive: true });
11880
+ const logPath = join28(logDir, `${slug(plan.repo)}-${now().toISOString().replace(/[:.]/g, "-")}.log`);
11648
11881
  const builtLayers = [];
11649
11882
  for (const layer of plan.layers) {
11650
11883
  if (deps.hasImage(layer.tag)) continue;
11651
- const ctx = join27(tmpdir3(), `crew-sandbox-${hash([layer.tag, process.pid, Date.now()])}`);
11652
- mkdirSync18(ctx, { recursive: true });
11884
+ const ctx = join28(tmpdir3(), `crew-sandbox-${hash([layer.tag, process.pid, Date.now()])}`);
11885
+ mkdirSync19(ctx, { recursive: true });
11653
11886
  try {
11654
- writeFileSync19(join27(ctx, "Dockerfile"), layer.dockerfile);
11887
+ writeFileSync20(join28(ctx, "Dockerfile"), layer.dockerfile);
11655
11888
  for (const [name, content] of Object.entries(layer.files)) {
11656
- mkdirSync18(dirname13(join27(ctx, name)), { recursive: true });
11657
- writeFileSync19(join27(ctx, name), content);
11889
+ mkdirSync19(dirname14(join28(ctx, name)), { recursive: true });
11890
+ writeFileSync20(join28(ctx, name), content);
11658
11891
  }
11659
- if (layer.caBundleFile) writeFileSync19(join27(ctx, layer.caBundleFile), (deps.caBundle ?? readHostCaBundle)());
11660
- const code = await deps.run(["build", "--tag", layer.tag, "--file", join27(ctx, "Dockerfile"), ctx], logPath);
11892
+ if (layer.caBundleFile) writeFileSync20(join28(ctx, layer.caBundleFile), (deps.caBundle ?? readHostCaBundle)());
11893
+ const code = await deps.run(["build", "--tag", layer.tag, "--file", join28(ctx, "Dockerfile"), ctx], logPath);
11661
11894
  if (code === BUILD_INTERRUPTED) return { kind: "interrupted", tag: plan.tag };
11662
11895
  if (code !== 0) {
11663
11896
  state[plan.repo] = { ...entry, failure: { tag: plan.tag, at: now().toISOString(), logPath } };
@@ -11666,7 +11899,7 @@ async function buildSandboxImage(plan, deps) {
11666
11899
  }
11667
11900
  builtLayers.push(layer.name);
11668
11901
  } finally {
11669
- rmSync14(ctx, { recursive: true, force: true });
11902
+ rmSync15(ctx, { recursive: true, force: true });
11670
11903
  }
11671
11904
  }
11672
11905
  const tags = [{ tag: plan.tag, builtAt: now().toISOString(), claude: plan.claude }, ...entry.tags.filter((t) => t.tag !== plan.tag)];
@@ -11769,8 +12002,8 @@ function expandSkillMarkers(text2, lookup2, opts = {}) {
11769
12002
  }
11770
12003
 
11771
12004
  // src/skills.ts
11772
- import { readFileSync as readFileSync28, readdirSync as readdirSync9, existsSync as existsSync27 } from "fs";
11773
- import { join as join29 } from "path";
12005
+ import { readFileSync as readFileSync29, readdirSync as readdirSync9, existsSync as existsSync28 } from "fs";
12006
+ import { join as join30 } from "path";
11774
12007
  import { parse as parseYaml2 } from "yaml";
11775
12008
  import { TablationClient as TablationClient3, StaleWriteError as StaleWriteError3, TablationApiError as TablationApiError2 } from "@tablation/client";
11776
12009
 
@@ -11786,7 +12019,7 @@ ${additions}`;
11786
12019
  }
11787
12020
 
11788
12021
  // src/persona-file.ts
11789
- import { readFileSync as readFileSync26 } from "fs";
12022
+ import { readFileSync as readFileSync27 } from "fs";
11790
12023
  import { parse as parseYaml } from "yaml";
11791
12024
  function parsePersonaText(text2, path) {
11792
12025
  const match = /^---\n([\s\S]*?)\n---\n([\s\S]*)$/.exec(text2);
@@ -11798,12 +12031,12 @@ function parsePersonaText(text2, path) {
11798
12031
  return { body: match[2], ...typeof meta.chat_enabled === "boolean" ? { chatEnabled: meta.chat_enabled } : {} };
11799
12032
  }
11800
12033
  function readPersonaFile(path) {
11801
- return parsePersonaText(readFileSync26(path, "utf8"), path);
12034
+ return parsePersonaText(readFileSync27(path, "utf8"), path);
11802
12035
  }
11803
12036
 
11804
12037
  // src/agents.ts
11805
- import { readFileSync as readFileSync27, existsSync as existsSync26 } from "fs";
11806
- import { join as join28 } from "path";
12038
+ import { readFileSync as readFileSync28, existsSync as existsSync27 } from "fs";
12039
+ import { join as join29 } from "path";
11807
12040
  import { TablationClient as TablationClient2, StaleWriteError as StaleWriteError2, TablationApiError } from "@tablation/client";
11808
12041
  var PERSONA_NAME = {
11809
12042
  dev: "Developer",
@@ -11817,17 +12050,17 @@ var CREW_AGENT_COLUMN = "agent_id";
11817
12050
  var AgentsSyncError = class extends Error {
11818
12051
  };
11819
12052
  function personaDefaultPrompt(promptsDir, role) {
11820
- const briefPath = join28(promptsDir, "personas", `lane-${role}.md`);
11821
- if (!existsSync26(briefPath)) throw new AgentsSyncError(`no brief at ${briefPath}`);
12053
+ const briefPath = join29(promptsDir, "personas", `lane-${role}.md`);
12054
+ if (!existsSync27(briefPath)) throw new AgentsSyncError(`no brief at ${briefPath}`);
11822
12055
  const brief = readPersonaFile(briefPath).body;
11823
12056
  if (SELF_CONTAINED_ROLES.has(role)) return brief;
11824
- const commonPath = join28(promptsDir, "personas", "common.md");
11825
- if (!existsSync26(commonPath)) return brief;
11826
- return `${readFileSync27(commonPath, "utf8")}${brief}`;
12057
+ const commonPath = join29(promptsDir, "personas", "common.md");
12058
+ if (!existsSync27(commonPath)) return brief;
12059
+ return `${readFileSync28(commonPath, "utf8")}${brief}`;
11827
12060
  }
11828
12061
  function personaChatEnabled(promptsDir, role) {
11829
- const briefPath = join28(promptsDir, "personas", `lane-${role}.md`);
11830
- return existsSync26(briefPath) ? readPersonaFile(briefPath).chatEnabled : void 0;
12062
+ const briefPath = join29(promptsDir, "personas", `lane-${role}.md`);
12063
+ return existsSync27(briefPath) ? readPersonaFile(briefPath).chatEnabled : void 0;
11831
12064
  }
11832
12065
  async function resolveAgentId(route2, role, opts) {
11833
12066
  const cached = route2.resolved?.agentPersonas?.[role]?.agentId;
@@ -12297,7 +12530,7 @@ function describeCrewLink(o) {
12297
12530
  var SkillSyncError = class extends Error {
12298
12531
  };
12299
12532
  function parseSkillFile(path) {
12300
- const text2 = readFileSync28(path, "utf8");
12533
+ const text2 = readFileSync29(path, "utf8");
12301
12534
  const match = /^---\n([\s\S]*?)\n---\n([\s\S]*)$/.exec(text2);
12302
12535
  if (!match) throw new SkillSyncError(`${path}: missing YAML frontmatter (expected a leading --- block)`);
12303
12536
  const frontmatter = match[1];
@@ -12324,9 +12557,9 @@ function parseSkillFile(path) {
12324
12557
  };
12325
12558
  }
12326
12559
  function listLocalSkills(promptsDir) {
12327
- const dir = join29(promptsDir, "skills");
12328
- if (!existsSync27(dir)) return [];
12329
- return readdirSync9(dir).filter((f) => f.endsWith(".md")).map((f) => parseSkillFile(join29(dir, f)));
12560
+ const dir = join30(promptsDir, "skills");
12561
+ if (!existsSync28(dir)) return [];
12562
+ return readdirSync9(dir).filter((f) => f.endsWith(".md")).map((f) => parseSkillFile(join30(dir, f)));
12330
12563
  }
12331
12564
  function personaColumn(model) {
12332
12565
  for (const c of ["persona_id", "persona"]) if (model.fields?.some((f) => f.columnName === c)) return c;
@@ -12560,10 +12793,10 @@ function skillMarkerWarnings(promptsDir, personaPrompts) {
12560
12793
 
12561
12794
  // src/runner.ts
12562
12795
  import { spawn as spawn5, execFile, execFileSync as execFileSync9 } from "child_process";
12563
- import { mkdtempSync, mkdirSync as mkdirSync19, writeFileSync as writeFileSync20, rmSync as rmSync15 } from "fs";
12796
+ import { mkdtempSync, mkdirSync as mkdirSync20, writeFileSync as writeFileSync21, rmSync as rmSync16 } from "fs";
12564
12797
  import { createHash as createHash5 } from "crypto";
12565
12798
  import { tmpdir as tmpdir4 } from "os";
12566
- import { basename as basename8, dirname as dirname14, join as join30 } from "path";
12799
+ import { basename as basename8, dirname as dirname15, join as join31 } from "path";
12567
12800
  import { promisify } from "util";
12568
12801
 
12569
12802
  // src/run-limit.ts
@@ -12698,6 +12931,12 @@ var SandboxRunner = class {
12698
12931
  if (/[\r\n]/.test(v)) throw new Error(`the sandbox environment variable ${k} contains a newline, which the sandbox gateway refuses`);
12699
12932
  }
12700
12933
  const createEnv = { ...process.env, ...plan.setEnv };
12934
+ for (const [k, v] of Object.entries(plan.sandboxRepoEnv ?? {})) {
12935
+ if (k in plan.setEnv) continue;
12936
+ if (/[\r\n]/.test(v)) throw new Error(`the repository environment variable ${k} contains a newline, which the sandbox gateway refuses`);
12937
+ createEnv[k] = v;
12938
+ if (!secretKeys.includes(k)) secretKeys.push(k);
12939
+ }
12701
12940
  if (cfg.forgeTokenVar && o.env[cfg.forgeTokenVar] !== void 0) createEnv[cfg.forgeTokenVar] = o.env[cfg.forgeTokenVar];
12702
12941
  let policyFile = cfg.policy;
12703
12942
  let generated;
@@ -12708,8 +12947,8 @@ var SandboxRunner = class {
12708
12947
  throw new Error(`cannot generate the sandbox policy: ${e.message}`);
12709
12948
  }
12710
12949
  policyFile = policyPathFor(plan.streamPath);
12711
- mkdirSync19(dirname14(policyFile), { recursive: true });
12712
- writeFileSync20(policyFile, generated.yaml, { mode: 384 });
12950
+ mkdirSync20(dirname15(policyFile), { recursive: true });
12951
+ writeFileSync21(policyFile, generated.yaml, { mode: 384 });
12713
12952
  }
12714
12953
  const create2 = ["sandbox", "create", "--name", name, "--detach"];
12715
12954
  if (policyFile) create2.push("--policy", policyFile);
@@ -12758,13 +12997,13 @@ var SandboxRunner = class {
12758
12997
  const harness = cfg.agentBin ?? basename8(plan.bin);
12759
12998
  const viaUpload = Buffer.byteLength(plan.prompt) > SANDBOX_STDIN_LIMIT;
12760
12999
  if (viaUpload) {
12761
- const tmp = mkdtempSync(join30(tmpdir4(), "crew-prompt-"));
13000
+ const tmp = mkdtempSync(join31(tmpdir4(), "crew-prompt-"));
12762
13001
  try {
12763
- const file = join30(tmp, "prompt.txt");
12764
- writeFileSync20(file, plan.prompt, { mode: 384 });
13002
+ const file = join31(tmp, "prompt.txt");
13003
+ writeFileSync21(file, plan.prompt, { mode: 384 });
12765
13004
  await this.os(["sandbox", "upload", name, file, SANDBOX_PROMPT_PATH]);
12766
13005
  } finally {
12767
- rmSync15(tmp, { recursive: true, force: true });
13006
+ rmSync16(tmp, { recursive: true, force: true });
12768
13007
  }
12769
13008
  }
12770
13009
  const withStubs = `${sandboxEnvExports()}PATH=${shQuote2(SANDBOX_STUB_DIR)}:"$PATH"; export PATH; `;
@@ -12959,7 +13198,7 @@ var ALLOWANCE_REFUSAL_MARKER = "AI_ALLOWANCE_EXCEEDED";
12959
13198
  function streamShowsAllowanceRefusal(streamPath) {
12960
13199
  let raw;
12961
13200
  try {
12962
- raw = readFileSync29(streamPath, "utf8");
13201
+ raw = readFileSync30(streamPath, "utf8");
12963
13202
  } catch {
12964
13203
  return false;
12965
13204
  }
@@ -12982,7 +13221,7 @@ function streamShowsAllowanceRefusal(streamPath) {
12982
13221
  }
12983
13222
  return false;
12984
13223
  }
12985
- var digestPathFor = (stateDir, routeLabel, role, runId) => join31(stateDir, `digest-${routeLabel}-${role}${runId ? `-${runId}` : ""}.md`);
13224
+ var digestPathFor = (stateDir, routeLabel, role, runId) => join32(stateDir, `digest-${routeLabel}-${role}${runId ? `-${runId}` : ""}.md`);
12986
13225
  function codeBridgeFor(o, harness) {
12987
13226
  if (!o.ticket) return void 0;
12988
13227
  const number = /(\d+)$/.exec(o.ticket)?.[1];
@@ -13009,7 +13248,7 @@ function codeBridgeFor(o, harness) {
13009
13248
  "--clone",
13010
13249
  o.ship.sandbox?.workDir ?? DEFAULT_SANDBOX_WORKDIR,
13011
13250
  "--state-dir",
13012
- dirname15(SANDBOX_INTEL_DIR),
13251
+ dirname16(SANDBOX_INTEL_DIR),
13013
13252
  "--ticket",
13014
13253
  number,
13015
13254
  ...seed ? ["--seed-cache", seed] : []
@@ -13022,32 +13261,32 @@ function codeBridgeFor(o, harness) {
13022
13261
  bridge.settingsFile = `${SANDBOX_INTEL_DIR}/gemini-settings.json`;
13023
13262
  bridge.files = [{ path: bridge.settingsFile, content: text2 }];
13024
13263
  } else {
13025
- const file = join31(intelDir(o.stateDir, o.route.route, number), "gemini-settings.json");
13026
- mkdirSync20(dirname15(file), { recursive: true });
13027
- writeFileSync21(file, text2);
13264
+ const file = join32(intelDir(o.stateDir, o.route.route, number), "gemini-settings.json");
13265
+ mkdirSync21(dirname16(file), { recursive: true });
13266
+ writeFileSync22(file, text2);
13028
13267
  bridge.settingsFile = file;
13029
13268
  }
13030
13269
  }
13031
13270
  return bridge;
13032
13271
  }
13033
13272
  function planAgentRun(o) {
13034
- const briefPath = join31(o.route.promptsDir, "personas", `lane-${o.role}.md`);
13035
- if (!existsSync28(briefPath)) {
13273
+ const briefPath = join32(o.route.promptsDir, "personas", `lane-${o.role}.md`);
13274
+ if (!existsSync29(briefPath)) {
13036
13275
  throw new AgentError(`no brief at ${briefPath} \u2014 refusing to run an unscoped session`);
13037
13276
  }
13038
- const commonPath = join31(o.route.promptsDir, "personas", "common.md");
13039
- const usesCommon = !SELF_CONTAINED_ROLES.has(o.role) && existsSync28(commonPath);
13277
+ const commonPath = join32(o.route.promptsDir, "personas", "common.md");
13278
+ const usesCommon = !SELF_CONTAINED_ROLES.has(o.role) && existsSync29(commonPath);
13040
13279
  const now = o.now ?? (() => Date.now());
13041
13280
  const routeLabel = routeSlug(o.route.route);
13042
13281
  const ownDigest = o.runId ? digestPathFor(o.stateDir, routeLabel, o.role, o.runId) : void 0;
13043
- const digestPath2 = ownDigest && existsSync28(ownDigest) ? ownDigest : digestPathFor(o.stateDir, routeLabel, o.role);
13282
+ const digestPath2 = ownDigest && existsSync29(ownDigest) ? ownDigest : digestPathFor(o.stateDir, routeLabel, o.role);
13044
13283
  let digest;
13045
13284
  let ageSeconds;
13046
- if (existsSync28(digestPath2)) {
13285
+ if (existsSync29(digestPath2)) {
13047
13286
  ageSeconds = Math.floor((now() - statSync9(digestPath2).mtimeMs) / 1e3);
13048
- if (ageSeconds <= DIGEST_MAX_AGE_SECONDS) digest = readFileSync29(digestPath2, "utf8");
13287
+ if (ageSeconds <= DIGEST_MAX_AGE_SECONDS) digest = readFileSync30(digestPath2, "utf8");
13049
13288
  }
13050
- const common = usesCommon ? readFileSync29(commonPath, "utf8") : "";
13289
+ const common = usesCommon ? readFileSync30(commonPath, "utf8") : "";
13051
13290
  const brief = readPersonaFile(briefPath).body;
13052
13291
  const effectiveCommon = o.divergedPrompt ? "" : common;
13053
13292
  const effectiveBrief = appendAdditions(o.divergedPrompt ?? brief, o.personaAdditions);
@@ -13071,7 +13310,7 @@ function planAgentRun(o) {
13071
13310
  digest
13072
13311
  });
13073
13312
  const promptSha = createHash6("sha256").update(expanded.text).digest("hex");
13074
- const streamsDir = join31(o.stateDir, "streams");
13313
+ const streamsDir = join32(o.stateDir, "streams");
13075
13314
  const base = `${routeLabel}-${o.role}-${o.cycle}${o.runId ? `-${o.runId}` : ""}`;
13076
13315
  const seat = resolveSeat(o.ship, o.route, o.role, o.agentPersona ?? (o.agentModel ? { model: o.agentModel } : {}), o.repo);
13077
13316
  const { model } = seat;
@@ -13091,11 +13330,14 @@ function planAgentRun(o) {
13091
13330
  const code = codeBridgeFor(o, adapter.harness);
13092
13331
  const sandboxLsp = o.ship.runner === "sandbox" && adapter.harness === "claude" ? sandboxLspPluginFor(o.route, o.repo) : void 0;
13093
13332
  const sandboxOrigin = o.ship.runner === "sandbox" ? sandboxOriginFor(o.route, o.repo) : void 0;
13333
+ const repoEnv = o.ship.runner === "sandbox" && o.repo ? envForRepository(readRepositoryEnv(o.stateDir), { repoRowId: repoIdForName(o.route, o.repo), remote: sandboxOrigin }) : {};
13094
13334
  const sandboxChoice = o.ship.runner === "sandbox" ? sandboxImageOf(o.route, o.repo, o.stateDir, o.repoContract) : void 0;
13095
13335
  const sandboxImage = sandboxChoice?.image;
13096
13336
  const sandboxFiles = [...code?.files ?? [], ...sandboxLsp?.files ?? []];
13337
+ const streamInput = adapter.userMessageLine !== void 0 && o.ship.runner !== "sandbox";
13097
13338
  const invocation = adapter.invocation(toolchain, {
13098
13339
  code,
13340
+ streamInput,
13099
13341
  role: o.role,
13100
13342
  model,
13101
13343
  pluginDirs: adapter.harness !== "claude" ? void 0 : sandboxLsp ? [sandboxLsp.dir] : lspPluginDirsFor(o.route, o.repo, o.stateDir),
@@ -13110,6 +13352,7 @@ function planAgentRun(o) {
13110
13352
  apiKey: o.apiKey,
13111
13353
  userAgent: o.ship.userAgent,
13112
13354
  agentId: o.resolvedAgentId,
13355
+ ...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] } } : {},
13113
13356
  ...o.route.resolved.models?.issues ? { tickets: {
13114
13357
  issuesModelId: o.route.resolved.models.issues,
13115
13358
  keyColumn: columns.key,
@@ -13147,6 +13390,7 @@ function planAgentRun(o) {
13147
13390
  runner: "sandbox",
13148
13391
  ...o.ship.sandbox ? { sandboxConfig: o.ship.sandbox } : {},
13149
13392
  ...sandboxOrigin ? { sandboxOrigin } : {},
13393
+ ...Object.keys(repoEnv).length ? { sandboxRepoEnv: repoEnv } : {},
13150
13394
  ...sandboxImage ? { sandboxImage } : {},
13151
13395
  ...sandboxChoice ? { sandboxImageReason: sandboxChoice.reason } : {},
13152
13396
  sandboxPolicy: sandboxPolicyInputFor(o.route, toolchain, { harnessBin: invocation.bin, repo: o.repo, sandbox: o.ship.sandbox, contract: o.repoContract }),
@@ -13154,6 +13398,7 @@ function planAgentRun(o) {
13154
13398
  } : {},
13155
13399
  resolution: { toolchain: seat.toolchainWhy, model: seat.modelWhy },
13156
13400
  warnings: [...seat.warnings ?? [], ...expanded.warnings],
13401
+ ...streamInput ? { acceptsInput: true } : {},
13157
13402
  prompt,
13158
13403
  promptBytes: Buffer.byteLength(prompt, "utf8"),
13159
13404
  unsetEnv: adapter.unsetEnv,
@@ -13176,8 +13421,8 @@ function planAgentRun(o) {
13176
13421
  digestAttached: digest !== void 0,
13177
13422
  digestAgeSeconds: ageSeconds,
13178
13423
  model,
13179
- streamPath: join31(streamsDir, `${base}.jsonl`),
13180
- eventsPath: join31(streamsDir, `${base}.events.jsonl`),
13424
+ streamPath: join32(streamsDir, `${base}.jsonl`),
13425
+ eventsPath: join32(streamsDir, `${base}.events.jsonl`),
13181
13426
  ticket: o.ticket,
13182
13427
  ticketRecordId: o.ticketRecordId ?? null,
13183
13428
  repo: o.repo ?? null,
@@ -13206,10 +13451,18 @@ function describePlan(p) {
13206
13451
  `stream: ${p.streamPath}`
13207
13452
  ].join("\n");
13208
13453
  }
13454
+ function updateSidecar(streamPath, patch2) {
13455
+ const sc = readRunSidecar(streamPath);
13456
+ if (!sc) return;
13457
+ try {
13458
+ writeFileSync22(pidPathFor(streamPath), JSON.stringify({ ...sc, ...patch2 }));
13459
+ } catch {
13460
+ }
13461
+ }
13209
13462
  var pidPathFor = (streamPath) => `${streamPath}.pid`;
13210
13463
  function readRunSidecar(streamPath) {
13211
13464
  try {
13212
- const sc = JSON.parse(readFileSync29(pidPathFor(streamPath), "utf8"));
13465
+ const sc = JSON.parse(readFileSync30(pidPathFor(streamPath), "utf8"));
13213
13466
  return typeof sc.pid === "number" && typeof sc.spawnedAt === "string" && typeof sc.role === "string" ? sc : null;
13214
13467
  } catch {
13215
13468
  return null;
@@ -13257,7 +13510,7 @@ async function killForDeadline(kill, pid, emit, role, ticket, spawnedAt, limitMi
13257
13510
  var withoutKey = ({ apiKey: _apiKey, ...rest }) => rest;
13258
13511
  function openSink(path) {
13259
13512
  try {
13260
- mkdirSync20(dirname15(path), { recursive: true });
13513
+ mkdirSync21(dirname16(path), { recursive: true });
13261
13514
  return createWriteStream(path, { flags: "a" });
13262
13515
  } catch {
13263
13516
  return void 0;
@@ -13300,6 +13553,8 @@ var FileTail = class {
13300
13553
  var TAIL_POLL_MS = 200;
13301
13554
  var RunObserver = class {
13302
13555
  cycles = [];
13556
+ /** CREW-3116: sends the cycles to the run's Agent Log row as they are mapped. */
13557
+ reporter;
13303
13558
  attribution = new TicketAttributionTracker();
13304
13559
  /** Hand-off writes and their outcomes, to tell a run whose hand-off never landed (CREW-2363). */
13305
13560
  handoff = new HandoffTranscriptTracker();
@@ -13316,6 +13571,8 @@ var RunObserver = class {
13316
13571
  * ticket the run actually claims (CREW-1776); `id.ticket` stays the hint.
13317
13572
  */
13318
13573
  liveTicket;
13574
+ /** CREW-3118: called when the stream first carries the harness's final result, e.g. to close a streaming stdin. */
13575
+ onResult;
13319
13576
  /** Called after `liveTicket` changes, so the sidecar can be rewritten. */
13320
13577
  onClaim;
13321
13578
  buf = "";
@@ -13333,6 +13590,11 @@ var RunObserver = class {
13333
13590
  this.liveTicket = id.ticket ?? void 0;
13334
13591
  this.mapper = adapter.createStreamMapper?.() ?? { map: (p) => adapter.mapStreamLine(p), flush: () => [] };
13335
13592
  }
13593
+ /** Hands the live reporter every cycle mapped so far, then each new one as it arrives. */
13594
+ attachReporter(r) {
13595
+ this.reporter = r;
13596
+ for (const c of this.cycles) r.add(c);
13597
+ }
13336
13598
  feed(text2) {
13337
13599
  this.buf += text2;
13338
13600
  const lines2 = this.buf.split("\n");
@@ -13359,7 +13621,11 @@ var RunObserver = class {
13359
13621
  const got = this.adapter.extractResult(parsed);
13360
13622
  if (got) {
13361
13623
  this.result = { ...this.result, ...Object.fromEntries(Object.entries(got).filter(([, v]) => v !== void 0)) };
13362
- if (got.numTurns !== void 0 || got.costUsd !== void 0) this.sawResult = true;
13624
+ if (got.numTurns !== void 0 || got.costUsd !== void 0) {
13625
+ const first = !this.sawResult;
13626
+ this.sawResult = true;
13627
+ if (first && !this.muted) this.onResult?.();
13628
+ }
13363
13629
  }
13364
13630
  this.handoff.feed(parsed);
13365
13631
  this.consume(parsed, this.mapper.map(parsed));
@@ -13414,7 +13680,7 @@ var RunObserver = class {
13414
13680
  turnText += `${ev.text}
13415
13681
  `;
13416
13682
  const cycleIndex = this.cycles.length;
13417
- this.cycles.push({
13683
+ const cycle = {
13418
13684
  cycleIndex,
13419
13685
  occurredAt: e.at,
13420
13686
  thinking: ev.text,
@@ -13425,7 +13691,9 @@ var RunObserver = class {
13425
13691
  // for the same column. A `thought` cycle stays untagged, same
13426
13692
  // as before this change.
13427
13693
  ...ev.kind === "text" ? { role: "assistant" } : {}
13428
- });
13694
+ };
13695
+ this.cycles.push(cycle);
13696
+ this.reporter?.add(cycle);
13429
13697
  if (!this.muted) {
13430
13698
  this.eventsSink?.write(`${JSON.stringify({
13431
13699
  ...e,
@@ -13443,7 +13711,7 @@ var RunObserver = class {
13443
13711
  };
13444
13712
  function writeRunMeta(id, startedAt, liveTicket, extra) {
13445
13713
  try {
13446
- writeFileSync21(`${id.streamPath}.meta.json`, JSON.stringify({
13714
+ writeFileSync22(`${id.streamPath}.meta.json`, JSON.stringify({
13447
13715
  route: id.route,
13448
13716
  role: id.role,
13449
13717
  hint: id.ticket,
@@ -13550,6 +13818,7 @@ async function finishRun(id, obs, emit, startedAt, end, agentLogKey, hintMoved)
13550
13818
  // CREW-2980: under `auth: workspace` the endpoint's rows are the accounting; the run row
13551
13819
  // keeps turns only, and `reportAgentRun` sums those rows into the ticket counters.
13552
13820
  ...id.agentLogRowId ? { rowId: id.agentLogRowId } : {},
13821
+ ...obs.reporter ? { cyclesPosted: obs.reporter.posted } : {},
13553
13822
  ...id.workspaceRunId ? { runId: id.workspaceRunId } : {
13554
13823
  tokensIn: result?.inputTokens,
13555
13824
  tokensOut: result?.outputTokens,
@@ -13625,7 +13894,36 @@ async function finishRun(id, obs, emit, startedAt, end, agentLogKey, hintMoved)
13625
13894
  }
13626
13895
  return { ms: ms3, ticket: attributedTicket, handoffPending: !!pending };
13627
13896
  }
13897
+ async function deliverNotes(target, rowId, msgs, write) {
13898
+ const names = await memberNames(target);
13899
+ for (const m of msgs) {
13900
+ const landed = await write(frameNote(m, m.authorId && names.get(m.authorId) || void 0));
13901
+ await markMessage(target, rowId, m.id, landed ? "delivered" : "carried_forward");
13902
+ }
13903
+ }
13904
+ async function withOperatorNotes(plan) {
13905
+ const log = plan.agentLog;
13906
+ const issues = log?.tickets?.issuesModelId;
13907
+ if (!log || !issues || !plan.ticketRecordId) return plan;
13908
+ const notes = await fetchPendingMessages(log, { table: issues, recordId: plan.ticketRecordId });
13909
+ if (notes.length === 0) return plan;
13910
+ const section = operatorNotesSection(notes, await memberNames(log));
13911
+ const prompt = `${plan.prompt}
13912
+
13913
+ ${section}
13914
+ `;
13915
+ await Promise.all(notes.map((m) => m.agentLogId ? markMessage(log, m.agentLogId, m.id, "delivered") : Promise.resolve(false)));
13916
+ return { ...plan, prompt, promptBytes: Buffer.byteLength(prompt, "utf8") };
13917
+ }
13918
+ function streamsInput(plan) {
13919
+ const i = plan.args.indexOf("--input-format");
13920
+ return !!plan.acceptsInput && i >= 0 && plan.args[i + 1] === "stream-json";
13921
+ }
13628
13922
  function spawnAgent(plan, emit, hintMoved) {
13923
+ if (!plan.agentLog?.tickets || !plan.ticketRecordId) return spawnPlanned(plan, emit, hintMoved);
13924
+ return withOperatorNotes(plan).catch(() => plan).then((p) => spawnPlanned(p, emit, hintMoved));
13925
+ }
13926
+ function spawnPlanned(plan, emit, hintMoved) {
13629
13927
  const adapter = adapterFor(plan.harness ?? LEGACY_TOOLCHAIN_HARNESS);
13630
13928
  const runner = runnerFor(plan.runner, plan.sandboxConfig);
13631
13929
  const started = Date.now();
@@ -13635,7 +13933,7 @@ function spawnAgent(plan, emit, hintMoved) {
13635
13933
  const id = identityOf(plan, adapter.harness);
13636
13934
  let streamFd;
13637
13935
  try {
13638
- mkdirSync20(dirname15(plan.streamPath), { recursive: true });
13936
+ mkdirSync21(dirname16(plan.streamPath), { recursive: true });
13639
13937
  streamFd = openSync4(plan.streamPath, "a");
13640
13938
  } catch (e) {
13641
13939
  void endSink(eventsSink);
@@ -13694,11 +13992,31 @@ function spawnAgent(plan, emit, hintMoved) {
13694
13992
  ...plan.workspaceRunId ? { workspaceRunId: plan.workspaceRunId } : {}
13695
13993
  };
13696
13994
  try {
13697
- writeFileSync21(pidPathFor(plan.streamPath), JSON.stringify(sidecar));
13995
+ writeFileSync22(pidPathFor(plan.streamPath), JSON.stringify(sidecar));
13698
13996
  } catch {
13699
13997
  }
13700
13998
  }
13701
- const startedRow = plan.workspaceRunId && plan.agentLog ? startAgentRunRow(plan.agentLog, {
13999
+ const obs = new RunObserver(id, adapter, eventsSink, emit.cycle);
14000
+ let inputOpen = streamsInput(plan) && !promptDelivered && !!adapter.userMessageLine;
14001
+ const closeInput = () => {
14002
+ if (!inputOpen) return;
14003
+ inputOpen = false;
14004
+ child.stdin?.end();
14005
+ };
14006
+ if (inputOpen) obs.onResult = closeInput;
14007
+ const writeNote = (text2) => new Promise((done) => {
14008
+ const stdin = child.stdin;
14009
+ if (!inputOpen || !stdin || !stdin.writable) {
14010
+ done(false);
14011
+ return;
14012
+ }
14013
+ try {
14014
+ stdin.write(adapter.userMessageLine(text2), (err3) => done(!err3));
14015
+ } catch {
14016
+ done(false);
14017
+ }
14018
+ });
14019
+ const startedRow = plan.agentLog ? startAgentRunRow(plan.agentLog, {
13702
14020
  runId: plan.workspaceRunId,
13703
14021
  ticketReference: plan.ticket ?? void 0,
13704
14022
  startedAt,
@@ -13706,19 +14024,21 @@ function spawnAgent(plan, emit, hintMoved) {
13706
14024
  harness: id.harness,
13707
14025
  provider: id.provider,
13708
14026
  promptVersion: plan.promptVersion,
13709
- promptSha: plan.promptSha
13710
- }).then((rowId) => {
13711
- if (!rowId) return;
13712
- id.agentLogRowId = rowId;
13713
- const sc = readRunSidecar(plan.streamPath);
13714
- if (sc) {
13715
- try {
13716
- writeFileSync21(pidPathFor(plan.streamPath), JSON.stringify({ ...sc, agentLogRowId: rowId }));
13717
- } catch {
13718
- }
14027
+ promptSha: plan.promptSha,
14028
+ actorLabel: plan.role
14029
+ }).then((row) => {
14030
+ if (!row) return;
14031
+ id.agentLogRowId = row.id;
14032
+ updateSidecar(plan.streamPath, { agentLogRowId: row.id });
14033
+ if (row.live && plan.agentLog) {
14034
+ const reporter = new LiveRunReporter(plan.agentLog, row.id, {
14035
+ onPosted: (n) => updateSidecar(plan.streamPath, { cyclesPosted: n }),
14036
+ onMessages: (msgs) => deliverNotes(plan.agentLog, row.id, msgs, writeNote)
14037
+ });
14038
+ obs.attachReporter(reporter);
14039
+ reporter.start();
13719
14040
  }
13720
14041
  }) : Promise.resolve();
13721
- const obs = new RunObserver(id, adapter, eventsSink, emit.cycle);
13722
14042
  const meta = { pid: child.pid ?? null, ...deadline ? { deadline } : {} };
13723
14043
  obs.onClaim = () => writeRunMeta(id, startedAt, obs.liveTicket, meta);
13724
14044
  if (child.pid !== void 0) writeRunMeta(id, startedAt, obs.liveTicket, meta);
@@ -13739,6 +14059,7 @@ function spawnAgent(plan, emit, hintMoved) {
13739
14059
  reject(new AgentSpawnError(`cannot run ${plan.bin}: ${err3.message}`));
13740
14060
  });
13741
14061
  child.on("close", async (code) => {
14062
+ inputOpen = false;
13742
14063
  clearInterval(timer);
13743
14064
  clearTimeout(limitTimer);
13744
14065
  obs.feed(tail3.poll());
@@ -13750,6 +14071,7 @@ function spawnAgent(plan, emit, hintMoved) {
13750
14071
  killed = { limitMinutes: plan.maxRunMinutes ?? 0, elapsedMs: Date.now() - Date.parse(spawnedAt) };
13751
14072
  }
13752
14073
  await startedRow;
14074
+ await obs.reporter?.stop();
13753
14075
  const { ms: ms3, handoffPending } = await finishRun(
13754
14076
  id,
13755
14077
  obs,
@@ -13765,7 +14087,9 @@ function spawnAgent(plan, emit, hintMoved) {
13765
14087
  emit.warn(`agent closed stdin before the prompt was delivered: ${err3.message}`, { step: "agent" });
13766
14088
  });
13767
14089
  if (promptDelivered) child.stdin?.end();
13768
- else child.stdin?.end(plan.prompt);
14090
+ else if (inputOpen) {
14091
+ child.stdin?.write(adapter.userMessageLine(plan.prompt));
14092
+ } else child.stdin?.end(plan.prompt);
13769
14093
  });
13770
14094
  }
13771
14095
  }
@@ -13779,6 +14103,16 @@ async function reattachRun(streamPath, sc, emit, o = {}) {
13779
14103
  obs.muted = true;
13780
14104
  obs.feed(tail3.poll());
13781
14105
  obs.muted = false;
14106
+ if (sc.agentLogRowId && sc.agentLog && o.agentLogKey) {
14107
+ const logTarget = { ...sc.agentLog, apiKey: o.agentLogKey };
14108
+ const reporter = new LiveRunReporter(logTarget, sc.agentLogRowId, {
14109
+ onPosted: (n) => updateSidecar(streamPath, { cyclesPosted: n }),
14110
+ // CREW-3118: the adopted run's stdin belongs to the process that died, so a note can only be carried forward.
14111
+ onMessages: (msgs) => deliverNotes(logTarget, sc.agentLogRowId, msgs, async () => false)
14112
+ }, sc.cyclesPosted ?? 0);
14113
+ obs.attachReporter(reporter);
14114
+ reporter.start();
14115
+ }
13782
14116
  const runner = runnerOfSidecar(sc);
13783
14117
  const adopted = isAlive(sc);
13784
14118
  let killed;
@@ -13796,6 +14130,7 @@ async function reattachRun(streamPath, sc, emit, o = {}) {
13796
14130
  }
13797
14131
  obs.feed(tail3.poll());
13798
14132
  obs.end();
14133
+ await obs.reporter?.stop();
13799
14134
  await endSink(eventsSink);
13800
14135
  await runner.release(runner.reattach(sc), emit);
13801
14136
  const interrupted = killed ? WALL_CLOCK_REASON : obs.sawResult ? void 0 : adopted ? "no-result" : "daemon-exit";
@@ -13829,21 +14164,21 @@ var pidAlive = (pid) => {
13829
14164
  };
13830
14165
  function runFinished(streamPath) {
13831
14166
  const path = `${streamPath}.meta.json`;
13832
- if (!existsSync29(path)) return false;
14167
+ if (!existsSync30(path)) return false;
13833
14168
  try {
13834
- return JSON.parse(readFileSync30(path, "utf8")).running !== true;
14169
+ return JSON.parse(readFileSync31(path, "utf8")).running !== true;
13835
14170
  } catch {
13836
14171
  return true;
13837
14172
  }
13838
14173
  }
13839
14174
  function orphanedStreams(o) {
13840
- const dir = join32(o.stateDir, "streams");
13841
- if (!existsSync29(dir)) return [];
14175
+ const dir = join33(o.stateDir, "streams");
14176
+ if (!existsSync30(dir)) return [];
13842
14177
  const ownerAlive = o.isOwnerAlive ?? pidAlive;
13843
14178
  const out = [];
13844
14179
  for (const name of readdirSync10(dir)) {
13845
14180
  if (!name.endsWith(".jsonl") || name.endsWith(".events.jsonl")) continue;
13846
- const streamPath = join32(dir, name);
14181
+ const streamPath = join33(dir, name);
13847
14182
  if (runFinished(streamPath)) continue;
13848
14183
  const sidecar = readRunSidecar(streamPath);
13849
14184
  if (!sidecar || sidecar.route !== o.routeLabel) continue;
@@ -13896,15 +14231,15 @@ async function reconcileRuns(o) {
13896
14231
  }
13897
14232
 
13898
14233
  // src/live-runs.ts
13899
- import { existsSync as existsSync30, readdirSync as readdirSync11, statSync as statSync10 } from "fs";
13900
- import { join as join33 } from "path";
14234
+ import { existsSync as existsSync31, readdirSync as readdirSync11, statSync as statSync10 } from "fs";
14235
+ import { join as join34 } from "path";
13901
14236
  function liveRuns(stateDir, isAlive = runIsAlive) {
13902
- const dir = join33(stateDir, "streams");
13903
- if (!existsSync30(dir)) return [];
14237
+ const dir = join34(stateDir, "streams");
14238
+ if (!existsSync31(dir)) return [];
13904
14239
  const out = [];
13905
14240
  for (const name of readdirSync11(dir)) {
13906
14241
  if (!name.endsWith(".jsonl") || name.endsWith(".events.jsonl")) continue;
13907
- const streamPath = join33(dir, name);
14242
+ const streamPath = join34(dir, name);
13908
14243
  if (runFinished(streamPath)) continue;
13909
14244
  const sidecar = readRunSidecar(streamPath);
13910
14245
  if (!sidecar || !isAlive(sidecar)) continue;
@@ -13914,12 +14249,12 @@ function liveRuns(stateDir, isAlive = runIsAlive) {
13914
14249
  }
13915
14250
  function runActivity(stateDir, isAlive = runIsAlive) {
13916
14251
  const activeRuns = liveRuns(stateDir, isAlive).length;
13917
- const dir = join33(stateDir, "streams");
14252
+ const dir = join34(stateDir, "streams");
13918
14253
  let newest = 0;
13919
- if (existsSync30(dir)) {
14254
+ if (existsSync31(dir)) {
13920
14255
  for (const name of readdirSync11(dir)) {
13921
14256
  if (!name.endsWith(".jsonl") || name.endsWith(".events.jsonl")) continue;
13922
- const streamPath = join33(dir, name);
14257
+ const streamPath = join34(dir, name);
13923
14258
  if (!runFinished(streamPath)) continue;
13924
14259
  try {
13925
14260
  newest = Math.max(newest, statSync10(`${streamPath}.meta.json`).mtimeMs);
@@ -14014,7 +14349,7 @@ function realDeprovisionDeps(cfg, emit, crewHome, getStore) {
14014
14349
  if (host === "windows") return [];
14015
14350
  const ctx = installContext();
14016
14351
  const systemd = detectSystemd();
14017
- return ["run", "release", "passengers"].flatMap((job) => planInstall(cfg.ship, crewHome, host, systemd, job, ctx).unitPaths).filter((p) => existsSync31(p));
14352
+ return ["run", "release", "passengers"].flatMap((job) => planInstall(cfg.ship, crewHome, host, systemd, job, ctx).unitPaths).filter((p) => existsSync32(p));
14018
14353
  };
14019
14354
  return {
14020
14355
  liveRuns: () => liveRuns(stateDir).map((r) => ({ role: r.role, route: r.route, pid: r.pid, ticketRecordId: r.ticketRecordId ?? void 0, streamPath: r.streamPath })),
@@ -14070,6 +14405,9 @@ function realDeprovisionDeps(cfg, emit, crewHome, getStore) {
14070
14405
  },
14071
14406
  forgeHosts,
14072
14407
  eraseForgeToken: (host) => eraseForgeToken(cfg.ship.forges, host, stateDir),
14408
+ eraseRepositoryEnv: () => {
14409
+ eraseRepositoryEnv(stateDir);
14410
+ },
14073
14411
  labeled: labeledDocker,
14074
14412
  removeVolume: (name) => {
14075
14413
  docker(["volume", "rm", "-f", name]);
@@ -14079,8 +14417,9 @@ function realDeprovisionDeps(cfg, emit, crewHome, getStore) {
14079
14417
  },
14080
14418
  remaining() {
14081
14419
  const left = [];
14082
- if (existsSync31(cfg.configFile)) left.push(`config ${cfg.configFile}`);
14420
+ if (existsSync32(cfg.configFile)) left.push(`config ${cfg.configFile}`);
14083
14421
  for (const h of forgeHosts()) if (hasForgeToken(cfg.ship.forges, h, stateDir)) left.push(`forge token for ${h}`);
14422
+ if (hasRepositoryEnv(stateDir)) left.push("repository environment");
14084
14423
  try {
14085
14424
  for (const k of readdirSync12(keysDir(stateDir))) left.push(`seat key ${k}`);
14086
14425
  } catch {
@@ -14903,9 +15242,9 @@ function managedGitIdentityWarnings(kind, identity) {
14903
15242
 
14904
15243
  // src/selftest.ts
14905
15244
  import { spawn as spawn7 } from "child_process";
14906
- import { existsSync as existsSync32, mkdirSync as mkdirSync21, mkdtempSync as mkdtempSync2, readFileSync as readFileSync31, rmSync as rmSync16, writeFileSync as writeFileSync22 } from "fs";
15245
+ import { existsSync as existsSync33, mkdirSync as mkdirSync22, mkdtempSync as mkdtempSync2, readFileSync as readFileSync32, rmSync as rmSync17, writeFileSync as writeFileSync23 } from "fs";
14907
15246
  import { tmpdir as tmpdir5 } from "os";
14908
- import { join as join34 } from "path";
15247
+ import { join as join35 } from "path";
14909
15248
  var SELFTEST_TIMEOUT_MS = 12e4;
14910
15249
  var KEY_VAR = "CREW_API_KEY";
14911
15250
  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: ";
@@ -15071,7 +15410,7 @@ async function runSelftest(i, deps = realDeps) {
15071
15410
  ...adapter.runEnv(spec),
15072
15411
  [KEY_VAR]: i.apiKey
15073
15412
  };
15074
- const cwd = mkdtempSync2(join34(tmpdir5(), "crew-selftest-"));
15413
+ const cwd = mkdtempSync2(join35(tmpdir5(), "crew-selftest-"));
15075
15414
  try {
15076
15415
  const run4 = await deps.run({
15077
15416
  bin: invocation.bin,
@@ -15093,7 +15432,7 @@ async function runSelftest(i, deps = realDeps) {
15093
15432
  return finish({ ok: false, failure, detail, ...usage2 });
15094
15433
  } finally {
15095
15434
  try {
15096
- rmSync16(cwd, { recursive: true, force: true });
15435
+ rmSync17(cwd, { recursive: true, force: true });
15097
15436
  } catch {
15098
15437
  }
15099
15438
  }
@@ -15104,11 +15443,11 @@ function formatResult(r) {
15104
15443
  const secs = `${(r.ms / 1e3).toFixed(1)}s`;
15105
15444
  return r.ok ? `${r.toolchain}: PASS ${r.detail} (${secs}${tok})` : `${r.toolchain}: FAIL ${r.failure} \u2014 ${r.detail} (${secs})`;
15106
15445
  }
15107
- var fileFor2 = (stateDir) => join34(stateDir, "selftest.json");
15446
+ var fileFor2 = (stateDir) => join35(stateDir, "selftest.json");
15108
15447
  function readSelftest(stateDir) {
15109
15448
  try {
15110
15449
  const p = fileFor2(stateDir);
15111
- return existsSync32(p) ? JSON.parse(readFileSync31(p, "utf8")) : {};
15450
+ return existsSync33(p) ? JSON.parse(readFileSync32(p, "utf8")) : {};
15112
15451
  } catch {
15113
15452
  return {};
15114
15453
  }
@@ -15116,8 +15455,8 @@ function readSelftest(stateDir) {
15116
15455
  function recordSelftest(stateDir, results) {
15117
15456
  const all = readSelftest(stateDir);
15118
15457
  for (const r of results) all[r.toolchain] = r;
15119
- mkdirSync21(stateDir, { recursive: true });
15120
- writeFileSync22(fileFor2(stateDir), `${JSON.stringify(all, null, 2)}
15458
+ mkdirSync22(stateDir, { recursive: true });
15459
+ writeFileSync23(fileFor2(stateDir), `${JSON.stringify(all, null, 2)}
15121
15460
  `);
15122
15461
  }
15123
15462
  function doctorSelftestLines(stored, toolchains) {
@@ -15129,7 +15468,7 @@ function doctorSelftestLines(stored, toolchains) {
15129
15468
  }
15130
15469
 
15131
15470
  // src/cli.ts
15132
- import { resolve as resolve7, dirname as dirname36, join as join59, basename as basename16 } from "path";
15471
+ import { resolve as resolve7, dirname as dirname37, join as join61, basename as basename16 } from "path";
15133
15472
  import { fileURLToPath as fileURLToPath2 } from "url";
15134
15473
  import { hostname as hostname5, homedir as homedir11, userInfo as userInfo2 } from "os";
15135
15474
  import { spawnSync as spawnSync13 } from "child_process";
@@ -15328,14 +15667,14 @@ function rosterMarkdown(roster, meId) {
15328
15667
  }
15329
15668
 
15330
15669
  // src/connect-resume.ts
15331
- import { mkdirSync as mkdirSync22, readFileSync as readFileSync32, rmSync as rmSync17, writeFileSync as writeFileSync23 } from "fs";
15332
- import { dirname as dirname16, join as join35 } from "path";
15670
+ import { mkdirSync as mkdirSync23, readFileSync as readFileSync33, rmSync as rmSync18, writeFileSync as writeFileSync24 } from "fs";
15671
+ import { dirname as dirname17, join as join36 } from "path";
15333
15672
  function lastSessionFile(stateDir) {
15334
- return join35(stateDir, "connect-session.json");
15673
+ return join36(stateDir, "connect-session.json");
15335
15674
  }
15336
15675
  function readPointers(stateDir) {
15337
15676
  try {
15338
- const parsed = JSON.parse(readFileSync32(lastSessionFile(stateDir), "utf8"));
15677
+ const parsed = JSON.parse(readFileSync33(lastSessionFile(stateDir), "utf8"));
15339
15678
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
15340
15679
  const out = {};
15341
15680
  for (const [host, v] of Object.entries(parsed)) {
@@ -15349,8 +15688,8 @@ function readPointers(stateDir) {
15349
15688
  }
15350
15689
  function writePointers(stateDir, pointers) {
15351
15690
  const file = lastSessionFile(stateDir);
15352
- mkdirSync22(dirname16(file), { recursive: true });
15353
- writeFileSync23(file, `${JSON.stringify(pointers, null, 2)}
15691
+ mkdirSync23(dirname17(file), { recursive: true });
15692
+ writeFileSync24(file, `${JSON.stringify(pointers, null, 2)}
15354
15693
  `, { mode: 384 });
15355
15694
  }
15356
15695
  function rememberSession(stateDir, host, workspaceSlug) {
@@ -15367,7 +15706,7 @@ function forgetWorkspace(stateDir, host, workspaceSlug) {
15367
15706
  const { [host]: _old, ...rest } = all;
15368
15707
  const next = left.length ? { ...rest, [host]: left } : rest;
15369
15708
  if (Object.keys(next).length) writePointers(stateDir, next);
15370
- else rmSync17(lastSessionFile(stateDir), { force: true });
15709
+ else rmSync18(lastSessionFile(stateDir), { force: true });
15371
15710
  } catch {
15372
15711
  }
15373
15712
  }
@@ -15407,7 +15746,7 @@ function forgetSession(stateDir, host) {
15407
15746
  try {
15408
15747
  const { [host]: _gone, ...rest } = readPointers(stateDir);
15409
15748
  if (Object.keys(rest).length) writePointers(stateDir, rest);
15410
- else rmSync17(lastSessionFile(stateDir), { force: true });
15749
+ else rmSync18(lastSessionFile(stateDir), { force: true });
15411
15750
  } catch {
15412
15751
  }
15413
15752
  }
@@ -15435,15 +15774,15 @@ async function signOutSessions(o) {
15435
15774
  }
15436
15775
 
15437
15776
  // src/reset.ts
15438
- import { existsSync as existsSync33, mkdirSync as mkdirSync23, readFileSync as readFileSync33, readdirSync as readdirSync13, rmSync as rmSync18, statSync as statSync11, writeFileSync as writeFileSync24 } from "fs";
15439
- import { dirname as dirname17, join as join36 } from "path";
15777
+ import { existsSync as existsSync34, mkdirSync as mkdirSync24, readFileSync as readFileSync34, readdirSync as readdirSync13, rmSync as rmSync19, statSync as statSync11, writeFileSync as writeFileSync25 } from "fs";
15778
+ import { dirname as dirname18, join as join37 } from "path";
15440
15779
  import { hostFromUrl as hostFromUrl3 } from "@tablation/client";
15441
15780
  function clonedCheckoutsFile(stateDir) {
15442
- return join36(stateDir, "cloned-checkouts.json");
15781
+ return join37(stateDir, "cloned-checkouts.json");
15443
15782
  }
15444
15783
  function readClonedCheckouts(stateDir) {
15445
15784
  try {
15446
- const parsed = JSON.parse(readFileSync33(clonedCheckoutsFile(stateDir), "utf8"));
15785
+ const parsed = JSON.parse(readFileSync34(clonedCheckoutsFile(stateDir), "utf8"));
15447
15786
  return Array.isArray(parsed) ? parsed.filter((d) => typeof d === "string") : [];
15448
15787
  } catch {
15449
15788
  return [];
@@ -15453,8 +15792,8 @@ function recordClonedCheckout(stateDir, dir) {
15453
15792
  const known = readClonedCheckouts(stateDir);
15454
15793
  if (known.includes(dir)) return;
15455
15794
  const file = clonedCheckoutsFile(stateDir);
15456
- mkdirSync23(dirname17(file), { recursive: true });
15457
- writeFileSync24(file, `${JSON.stringify([...known, dir], null, 2)}
15795
+ mkdirSync24(dirname18(file), { recursive: true });
15796
+ writeFileSync25(file, `${JSON.stringify([...known, dir], null, 2)}
15458
15797
  `);
15459
15798
  }
15460
15799
  var mark = (dryRun) => dryRun ? "would-remove" : "removed";
@@ -15508,8 +15847,8 @@ async function runReset(o, fx) {
15508
15847
  }
15509
15848
  if (o.beforeState) steps.push(...await o.beforeState());
15510
15849
  steps.push(...o.wipeState ? wipeStateDir(o.stateDir, o.dryRun) : removeState(o.stateDir, o.dryRun));
15511
- if (existsSync33(o.configFile)) {
15512
- if (!o.dryRun) rmSync18(o.configFile, { force: true });
15850
+ if (existsSync34(o.configFile)) {
15851
+ if (!o.dryRun) rmSync19(o.configFile, { force: true });
15513
15852
  steps.push({ step: "config", target: o.configFile, action: mark(o.dryRun) });
15514
15853
  } else {
15515
15854
  steps.push({ step: "config", target: o.configFile, action: "absent" });
@@ -15517,7 +15856,7 @@ async function runReset(o, fx) {
15517
15856
  return steps;
15518
15857
  }
15519
15858
  function removeCheckout(dir, dryRun, fx) {
15520
- if (!existsSync33(dir)) return { step: "checkout", target: dir, action: "absent", detail: "already gone" };
15859
+ if (!existsSync34(dir)) return { step: "checkout", target: dir, action: "absent", detail: "already gone" };
15521
15860
  const { dirty, linkedWorktrees } = fx.inspectCheckout(dir);
15522
15861
  if (dirty.length) {
15523
15862
  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" : ""})` };
@@ -15525,21 +15864,21 @@ function removeCheckout(dir, dryRun, fx) {
15525
15864
  if (linkedWorktrees.length) {
15526
15865
  return { step: "checkout", target: dir, action: "kept", detail: `has linked worktrees (${linkedWorktrees.join(", ")}); remove them first` };
15527
15866
  }
15528
- if (!dryRun) rmSync18(dir, { recursive: true, force: true });
15867
+ if (!dryRun) rmSync19(dir, { recursive: true, force: true });
15529
15868
  return { step: "checkout", target: dir, action: mark(dryRun) };
15530
15869
  }
15531
15870
  function removeState(stateDir, dryRun) {
15532
15871
  const out = [];
15533
- const targets = [join36(stateDir, "resolved"), join36(stateDir, "keys"), clonedCheckoutsFile(stateDir), join36(stateDir, "connect-session.json"), join36(stateDir, "reload-requested"), join36(stateDir, "daemon.started")];
15872
+ const targets = [join37(stateDir, "resolved"), join37(stateDir, "keys"), clonedCheckoutsFile(stateDir), join37(stateDir, "connect-session.json"), join37(stateDir, "reload-requested"), join37(stateDir, "daemon.started")];
15534
15873
  try {
15535
15874
  for (const name of readdirSync13(stateDir)) {
15536
- if (name.startsWith(".") && statSync11(join36(stateDir, name)).isFile()) targets.push(join36(stateDir, name));
15875
+ if (name.startsWith(".") && statSync11(join37(stateDir, name)).isFile()) targets.push(join37(stateDir, name));
15537
15876
  }
15538
15877
  } catch {
15539
15878
  }
15540
15879
  for (const t of targets) {
15541
- if (!existsSync33(t)) continue;
15542
- if (!dryRun) rmSync18(t, { recursive: true, force: true });
15880
+ if (!existsSync34(t)) continue;
15881
+ if (!dryRun) rmSync19(t, { recursive: true, force: true });
15543
15882
  out.push({ step: "state", target: t, action: mark(dryRun) });
15544
15883
  }
15545
15884
  if (!out.length) out.push({ step: "state", target: stateDir, action: "absent", detail: "nothing to remove" });
@@ -15553,7 +15892,7 @@ function wipeStateDir(stateDir, dryRun) {
15553
15892
  return [{ step: "state", target: stateDir, action: "absent", detail: "no state directory" }];
15554
15893
  }
15555
15894
  if (!names.length) return [{ step: "state", target: stateDir, action: "absent", detail: "already empty" }];
15556
- if (!dryRun) for (const n of names) rmSync18(join36(stateDir, n), { recursive: true, force: true });
15895
+ if (!dryRun) for (const n of names) rmSync19(join37(stateDir, n), { recursive: true, force: true });
15557
15896
  return [{ step: "state", target: stateDir, action: mark(dryRun), detail: `${names.length} entr${names.length === 1 ? "y" : "ies"}` }];
15558
15897
  }
15559
15898
  function describeResetStep(s) {
@@ -15619,6 +15958,7 @@ async function runDeprovision(o, fx, deps) {
15619
15958
  steps2.push({ step: "forge", target: host, action: "failed", detail: e.message });
15620
15959
  }
15621
15960
  }
15961
+ if (!o.dryRun) deps.eraseRepositoryEnv?.();
15622
15962
  const { volumes, images } = deps.labeled();
15623
15963
  for (const v of volumes) steps2.push(attempt("cache", `volume ${v}`, () => {
15624
15964
  deps.removeVolume(v);
@@ -15634,9 +15974,9 @@ async function runDeprovision(o, fx, deps) {
15634
15974
  }
15635
15975
 
15636
15976
  // src/pool-member.ts
15637
- import { mkdirSync as mkdirSync24, readFileSync as readFileSync34, renameSync as renameSync4, writeFileSync as writeFileSync25 } from "fs";
15977
+ import { mkdirSync as mkdirSync25, readFileSync as readFileSync35, renameSync as renameSync5, writeFileSync as writeFileSync26 } from "fs";
15638
15978
  import { homedir as homedir8 } from "os";
15639
- import { dirname as dirname18, join as join37 } from "path";
15979
+ import { dirname as dirname19, join as join38 } from "path";
15640
15980
  var POOL_EXIT = { ok: 0, failed: 1, credential: 2 };
15641
15981
  function backoffMs(attempt) {
15642
15982
  return Math.min(6e4, 5e3 * 2 ** Math.max(0, attempt));
@@ -15842,6 +16182,13 @@ async function runPoolMember(deps) {
15842
16182
  deps.log(`tokens: ${applied.reason ?? "could not apply the delivered forge tokens"}`);
15843
16183
  continue;
15844
16184
  }
16185
+ if (Array.isArray(body.repositoryEnv) && deps.applyRepositoryEnv) {
16186
+ const env = await deps.applyRepositoryEnv(body.repositoryEnv);
16187
+ if (!env.ok) {
16188
+ deps.log(`tokens: ${env.reason ?? "could not apply the delivered repository environment"}`);
16189
+ continue;
16190
+ }
16191
+ }
15845
16192
  deps.log(`tokens: replaced the forge tokens (${(body.forges ?? []).length} host${(body.forges ?? []).length === 1 ? "" : "s"})`);
15846
16193
  const r2 = await report("running", { leaseId: current });
15847
16194
  if (r2 === "credential") return POOL_EXIT.credential;
@@ -15859,6 +16206,10 @@ async function runPoolMember(deps) {
15859
16206
  if (r === "stopped") return POOL_EXIT.ok;
15860
16207
  const done = await deps.provision(lease, platform2.instanceClassKey, platform2.shipKind ?? "pooled_instance");
15861
16208
  if (!done.ok) return fail2(lease.id, done.reason ?? "provisioning failed");
16209
+ if (deps.applyRepositoryEnv) {
16210
+ const env = await deps.applyRepositoryEnv(lease.repositoryEnv ?? []);
16211
+ if (!env.ok) return fail2(lease.id, env.reason ?? "could not store the repository environment");
16212
+ }
15862
16213
  r = await report("running", { leaseId: lease.id });
15863
16214
  if (r === "credential") return POOL_EXIT.credential;
15864
16215
  current = lease.id;
@@ -15867,24 +16218,24 @@ async function runPoolMember(deps) {
15867
16218
  }
15868
16219
  }
15869
16220
  function defaultMemberDir(env = process.env) {
15870
- return env.CREW_POOL_DIR ?? join37(env.XDG_STATE_HOME ?? join37(homedir8(), ".local", "state"), "crew-pool-member");
16221
+ return env.CREW_POOL_DIR ?? join38(env.XDG_STATE_HOME ?? join38(homedir8(), ".local", "state"), "crew-pool-member");
15871
16222
  }
15872
16223
  function fileMemberStore(dir) {
15873
- const file = join37(dir, "member.json");
16224
+ const file = join38(dir, "member.json");
15874
16225
  return {
15875
16226
  read() {
15876
16227
  try {
15877
- return JSON.parse(readFileSync34(file, "utf8"));
16228
+ return JSON.parse(readFileSync35(file, "utf8"));
15878
16229
  } catch {
15879
16230
  return {};
15880
16231
  }
15881
16232
  },
15882
16233
  write(f) {
15883
- mkdirSync24(dirname18(file), { recursive: true, mode: 448 });
16234
+ mkdirSync25(dirname19(file), { recursive: true, mode: 448 });
15884
16235
  const tmp = `${file}.tmp`;
15885
- writeFileSync25(tmp, `${JSON.stringify(f)}
16236
+ writeFileSync26(tmp, `${JSON.stringify(f)}
15886
16237
  `, { mode: 384 });
15887
- renameSync4(tmp, file);
16238
+ renameSync5(tmp, file);
15888
16239
  }
15889
16240
  };
15890
16241
  }
@@ -15934,16 +16285,16 @@ function hostArchitecture(arch = process.arch) {
15934
16285
 
15935
16286
  // src/pool-member-host.ts
15936
16287
  import "child_process";
15937
- import { existsSync as existsSync36 } from "fs";
16288
+ import { existsSync as existsSync37 } from "fs";
15938
16289
  import { hostname as hostname3 } from "os";
15939
16290
 
15940
16291
  // src/machine-id.ts
15941
16292
  import { execFileSync as execFileSync12 } from "child_process";
15942
16293
  import { createHash as createHash8 } from "crypto";
15943
- import { existsSync as existsSync34, mkdirSync as mkdirSync25, readFileSync as readFileSync35, writeFileSync as writeFileSync26 } from "fs";
15944
- import { dirname as dirname19, join as join38 } from "path";
16294
+ import { existsSync as existsSync35, mkdirSync as mkdirSync26, readFileSync as readFileSync36, writeFileSync as writeFileSync27 } from "fs";
16295
+ import { dirname as dirname20, join as join39 } from "path";
15945
16296
  function machineIdPathFor(stateDir) {
15946
- return join38(stateDir, "machine-id");
16297
+ return join39(stateDir, "machine-id");
15947
16298
  }
15948
16299
  var sha256 = (s) => createHash8("sha256").update(s).digest("hex");
15949
16300
  function readRawMachineId(platform2 = process.platform) {
@@ -15956,8 +16307,8 @@ function readRawMachineId(platform2 = process.platform) {
15956
16307
  return /"IOPlatformUUID"\s*=\s*"([^"]+)"/.exec(out)?.[1];
15957
16308
  }
15958
16309
  for (const p of ["/etc/machine-id", "/var/lib/dbus/machine-id"]) {
15959
- if (existsSync34(p)) {
15960
- const id = readFileSync35(p, "utf8").trim();
16310
+ if (existsSync35(p)) {
16311
+ const id = readFileSync36(p, "utf8").trim();
15961
16312
  if (id) return id;
15962
16313
  }
15963
16314
  }
@@ -15968,15 +16319,15 @@ function readRawMachineId(platform2 = process.platform) {
15968
16319
  function ensureMachineId(stateDir, opts = {}) {
15969
16320
  if (opts.override?.trim()) return sha256(opts.override.trim());
15970
16321
  const path = machineIdPathFor(stateDir);
15971
- if (existsSync34(path)) {
15972
- const cached = readFileSync35(path, "utf8").trim();
16322
+ if (existsSync35(path)) {
16323
+ const cached = readFileSync36(path, "utf8").trim();
15973
16324
  if (/^[0-9a-f]{64}$/.test(cached)) return cached;
15974
16325
  }
15975
16326
  const raw = (opts.read ?? readRawMachineId)();
15976
16327
  if (!raw) return void 0;
15977
16328
  const hashed = sha256(raw);
15978
- mkdirSync25(dirname19(path), { recursive: true });
15979
- writeFileSync26(path, `${hashed}
16329
+ mkdirSync26(dirname20(path), { recursive: true });
16330
+ writeFileSync27(path, `${hashed}
15980
16331
  `, { mode: 384 });
15981
16332
  return hashed;
15982
16333
  }
@@ -15989,7 +16340,7 @@ function matchShipRows(ships, shipName2, machineId) {
15989
16340
 
15990
16341
  // src/provision.ts
15991
16342
  import { spawnSync as spawnSync9 } from "child_process";
15992
- import { existsSync as existsSync35, readFileSync as readFileSync36, writeFileSync as writeFileSync27 } from "fs";
16343
+ import { existsSync as existsSync36, readFileSync as readFileSync37, writeFileSync as writeFileSync28 } from "fs";
15993
16344
  import { hostname as hostname2 } from "os";
15994
16345
  import { parseDocument as parseDocument3, isMap as isMap2, isScalar } from "yaml";
15995
16346
 
@@ -15998,11 +16349,11 @@ import { parseDocument as parseDocument2 } from "yaml";
15998
16349
 
15999
16350
  // src/repos-cmd.ts
16000
16351
  import { homedir as homedir9 } from "os";
16001
- import { basename as basename10, join as join39, resolve as resolve4 } from "path";
16352
+ import { basename as basename10, join as join40, resolve as resolve4 } from "path";
16002
16353
  import { isMap, isSeq, parseDocument, stringify as stringify2 } from "yaml";
16003
16354
  var ReposError = class extends Error {
16004
16355
  };
16005
- function normalizeRemote(url) {
16356
+ function normalizeRemote2(url) {
16006
16357
  if (!url) return void 0;
16007
16358
  let s = url.trim();
16008
16359
  if (!s) return void 0;
@@ -16015,10 +16366,10 @@ function normalizeRemote(url) {
16015
16366
  return parts.slice(-2).join("/").toLowerCase();
16016
16367
  }
16017
16368
  function matchRepoName(origin, resolved) {
16018
- const want = normalizeRemote(origin);
16369
+ const want = normalizeRemote2(origin);
16019
16370
  if (!want || !resolved?.repoRemotes) return void 0;
16020
16371
  for (const [id, remote] of Object.entries(resolved.repoRemotes)) {
16021
- if (normalizeRemote(remote) === want) return resolved.repoNames?.[id];
16372
+ if (normalizeRemote2(remote) === want) return resolved.repoNames?.[id];
16022
16373
  }
16023
16374
  return void 0;
16024
16375
  }
@@ -16098,15 +16449,15 @@ function listRepoRows(i) {
16098
16449
  const originFor = (c, remote) => {
16099
16450
  const o = i.originOf(c.dir) ?? null;
16100
16451
  if (!o) return null;
16101
- return remote !== null && normalizeRemote(o) === normalizeRemote(remote) ? null : o;
16452
+ return remote !== null && normalizeRemote2(o) === normalizeRemote2(remote) ? null : o;
16102
16453
  };
16103
16454
  const rows = [];
16104
16455
  const names = i.resolved?.repoNames ?? {};
16105
16456
  const remotes = i.resolved?.repoRemotes ?? {};
16106
16457
  for (const [id, name] of Object.entries(names)) {
16107
16458
  const remote = remotes[id] ?? null;
16108
- const want = normalizeRemote(remote);
16109
- let idx = checkouts.findIndex((c2, n) => !claimed.has(n) && want !== void 0 && normalizeRemote(i.originOf(c2.dir)) === want);
16459
+ const want = normalizeRemote2(remote);
16460
+ let idx = checkouts.findIndex((c2, n) => !claimed.has(n) && want !== void 0 && normalizeRemote2(i.originOf(c2.dir)) === want);
16110
16461
  if (idx < 0) idx = checkouts.findIndex((c2, n) => !claimed.has(n) && c2.name === name);
16111
16462
  const c = idx >= 0 ? checkouts[idx] : void 0;
16112
16463
  if (idx >= 0) claimed.add(idx);
@@ -16159,11 +16510,11 @@ function planRepoAdd(i) {
16159
16510
  throw new ReposError(`${target} is already configured on route ${i.route}`);
16160
16511
  }
16161
16512
  const matched = matchRepoName(i.origin, i.resolved);
16162
- const name = matched ?? i.name ?? normalizeRemote(i.origin)?.split("/").pop() ?? basename10(target);
16513
+ const name = matched ?? i.name ?? normalizeRemote2(i.origin)?.split("/").pop() ?? basename10(target);
16163
16514
  let warning;
16164
16515
  if (!matched) {
16165
16516
  const known = Object.values(i.resolved?.repoNames ?? {});
16166
- 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";
16517
+ 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";
16167
16518
  }
16168
16519
  const repos = m.get("repos", true);
16169
16520
  let mode;
@@ -16216,7 +16567,7 @@ function renderBlock(m) {
16216
16567
  }
16217
16568
  var LOCAL_RELEASE_MODES = /* @__PURE__ */ new Set(["integrate", "external"]);
16218
16569
  function planRepoRow(i) {
16219
- const remote = normalizeRemote(i.origin);
16570
+ const remote = normalizeRemote2(i.origin);
16220
16571
  if (!remote) throw new ReposError(`cannot derive an owner/repo from origin "${i.origin}"`);
16221
16572
  const mode = i.spec?.releaseMode;
16222
16573
  return {
@@ -16262,7 +16613,7 @@ function planRepoClone(i) {
16262
16613
  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"}`);
16263
16614
  }
16264
16615
  const name = names[id];
16265
- const remote = normalizeRemote(i.resolved?.repoRemotes?.[id]);
16616
+ const remote = normalizeRemote2(i.resolved?.repoRemotes?.[id]);
16266
16617
  if (!remote) {
16267
16618
  throw new ReposError(
16268
16619
  `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\``
@@ -16276,7 +16627,7 @@ function planRepoClone(i) {
16276
16627
  }
16277
16628
  const ship = doc.get("ship", true);
16278
16629
  const basePath = String(m.get("reposBasePath") ?? (isMap(ship) ? ship.get("reposBasePath") : void 0) ?? "~/Crew");
16279
- const target = i.dir ? expandDir(i.dir, i.base) : join39(expandDir(basePath, i.base), i.route.split("/")[0], name);
16630
+ const target = i.dir ? expandDir(i.dir, i.base) : join40(expandDir(basePath, i.base), i.route.split("/")[0], name);
16280
16631
  const add = planRepoAdd({ text: i.text, base: i.base, route: i.route, path: target, origin: remote, resolved: i.resolved, name, isCheckout: i.isCheckout });
16281
16632
  const forgeHost = i.resolved?.repoForgeHosts?.[id];
16282
16633
  return { ...add, remote, target, ...forgeHost ? { forgeHost } : {} };
@@ -16607,7 +16958,7 @@ function realProvisionDeps(crewHome) {
16607
16958
  };
16608
16959
  const configFile = () => {
16609
16960
  const f = findConfigFile(crewHome);
16610
- return existsSync35(f) ? f : null;
16961
+ return existsSync36(f) ? f : null;
16611
16962
  };
16612
16963
  return {
16613
16964
  crew: spawnCrew,
@@ -16615,13 +16966,13 @@ function realProvisionDeps(crewHome) {
16615
16966
  enableRoute(route2) {
16616
16967
  const file = configFile();
16617
16968
  if (!file) return false;
16618
- const text2 = readFileSync36(file, "utf8");
16969
+ const text2 = readFileSync37(file, "utf8");
16619
16970
  const doc = parseDocument3(text2);
16620
16971
  const routes = doc.get("routes");
16621
16972
  const entry = routes?.items?.find((r) => r.get("route") === route2);
16622
16973
  if (!entry) throw new Error(`route ${route2} is not in ${file}`);
16623
16974
  if (entry.get("enabled") === true) return false;
16624
- writeFileSync27(file, planEnable(text2, route2));
16975
+ writeFileSync28(file, planEnable(text2, route2));
16625
16976
  return true;
16626
16977
  },
16627
16978
  installState() {
@@ -16641,14 +16992,14 @@ function realProvisionDeps(crewHome) {
16641
16992
  continue;
16642
16993
  }
16643
16994
  for (const p of plan.unitPaths) {
16644
- if (!existsSync35(p) || readFileSync36(p, "utf8") !== plan.unitContent[p]) unitsStale = true;
16995
+ if (!existsSync36(p) || readFileSync37(p, "utf8") !== plan.unitContent[p]) unitsStale = true;
16645
16996
  }
16646
16997
  }
16647
16998
  const label = labelFor(crewHome, "run");
16648
16999
  let running = false;
16649
17000
  let lingering = true;
16650
17001
  if (mechanism === "systemd") {
16651
- const system = ctx.root || existsSync35(systemUnitPathFor(label));
17002
+ const system = ctx.root || existsSync36(systemUnitPathFor(label));
16652
17003
  const ctl = system ? ["systemctl"] : ["systemctl", "--user"];
16653
17004
  running = spawnSync9(ctl[0], [...ctl.slice(1), "is-active", "--quiet", `${label}.service`], { env: withUserBusEnv() }).status === 0;
16654
17005
  if (!system) {
@@ -16665,18 +17016,18 @@ function realProvisionDeps(crewHome) {
16665
17016
  setShipSetting(key, value2) {
16666
17017
  const file = configFile();
16667
17018
  if (!file) return false;
16668
- const doc = parseDocument3(readFileSync36(file, "utf8"));
17019
+ const doc = parseDocument3(readFileSync37(file, "utf8"));
16669
17020
  if (doc.getIn(["ship", key]) === value2) return false;
16670
17021
  doc.setIn(["ship", key], value2);
16671
- writeFileSync27(file, doc.toString());
17022
+ writeFileSync28(file, doc.toString());
16672
17023
  return true;
16673
17024
  },
16674
17025
  applyManagedDefaults() {
16675
17026
  const file = configFile();
16676
17027
  if (!file) return [];
16677
- const doc = parseDocument3(readFileSync36(file, "utf8"));
17028
+ const doc = parseDocument3(readFileSync37(file, "utf8"));
16678
17029
  const wrote = applyManagedDefaultsToDoc(doc);
16679
- if (wrote.length) writeFileSync27(file, doc.toString());
17030
+ if (wrote.length) writeFileSync28(file, doc.toString());
16680
17031
  return wrote;
16681
17032
  },
16682
17033
  ensureGitIdentity(name, email) {
@@ -16726,7 +17077,7 @@ function realPoolMemberDeps(o) {
16726
17077
  crewVersion: crewVersion(o.crewHome),
16727
17078
  hostname: hostname3()
16728
17079
  },
16729
- hasShipConfig: () => existsSync36(findConfigFile(o.crewHome)),
17080
+ hasShipConfig: () => existsSync37(findConfigFile(o.crewHome)),
16730
17081
  async provision(lease, instanceClass, shipKind) {
16731
17082
  const hosts = lease.forges.map((f) => f.host.toLowerCase());
16732
17083
  const lines2 = [];
@@ -16775,6 +17126,16 @@ function realPoolMemberDeps(o) {
16775
17126
  }
16776
17127
  return { ok: true };
16777
17128
  },
17129
+ async applyRepositoryEnv(entries) {
17130
+ const cfg = loadShip(o.crewHome);
17131
+ if (!cfg) return { ok: false, reason: "no ship config to store the repository environment under" };
17132
+ try {
17133
+ writeRepositoryEnv(cfg.ship.stateDir, entries);
17134
+ } catch (e) {
17135
+ return { ok: false, reason: `repository environment: ${e.message}` };
17136
+ }
17137
+ return { ok: true };
17138
+ },
16778
17139
  async reconcile() {
16779
17140
  const before = provisionDeps.installState();
16780
17141
  if (before.unitsStale || !before.running || !before.lingering) {
@@ -17604,7 +17965,7 @@ ${waiting.map((t) => `| ${displayKey2(t)} | ${t.status} | ${blockers(t, i)} |`).
17604
17965
 
17605
17966
  // src/sandbox-hygiene.ts
17606
17967
  import { execFile as execFile3 } from "child_process";
17607
- import { existsSync as existsSync37, statfsSync as statfsSync2 } from "fs";
17968
+ import { existsSync as existsSync38, statfsSync as statfsSync2 } from "fs";
17608
17969
  import { promisify as promisify3 } from "util";
17609
17970
  var execFileP3 = promisify3(execFile3);
17610
17971
  var REAP_MIN_AGE_MS = 5 * 6e4;
@@ -17747,7 +18108,7 @@ async function realDiskReadings(ship) {
17747
18108
  const paths = ["/"];
17748
18109
  try {
17749
18110
  const root = (await run3(ship.sandbox?.engine ?? DEFAULT_CACHE_SETTINGS.engine, ["info", "--format", "{{.DockerRootDir}}"])).trim();
17750
- if (root && existsSync37(root)) paths.push(root);
18111
+ if (root && existsSync38(root)) paths.push(root);
17751
18112
  } catch {
17752
18113
  }
17753
18114
  return paths.flatMap((path) => {
@@ -17788,8 +18149,8 @@ function diskFullStop(state) {
17788
18149
  }
17789
18150
 
17790
18151
  // src/poll.ts
17791
- import { writeFileSync as writeFileSync28 } from "fs";
17792
- import { join as join40 } from "path";
18152
+ import { writeFileSync as writeFileSync29 } from "fs";
18153
+ import { join as join41 } from "path";
17793
18154
 
17794
18155
  // src/stalled.ts
17795
18156
  var STALLED_AFTER_CYCLES = 30;
@@ -18103,7 +18464,7 @@ async function decideCycle(o) {
18103
18464
  }
18104
18465
  return decision;
18105
18466
  }
18106
- var digestPath = (stateDir, route2, role, runId) => join40(stateDir, `digest-${route2}-${role}${runId ? `-${runId}` : ""}.md`);
18467
+ var digestPath = (stateDir, route2, role, runId) => join41(stateDir, `digest-${route2}-${role}${runId ? `-${runId}` : ""}.md`);
18107
18468
  function otherRunsRemoved(tickets, own) {
18108
18469
  if (!own) return tickets;
18109
18470
  return tickets.filter((t) => t.id === own.ticket.id || !own.inFlight(t.id));
@@ -18187,7 +18548,7 @@ function writeDigest(o, d, role, stateDir, runId, own) {
18187
18548
 
18188
18549
  ${body}` : body;
18189
18550
  const path = digestPath(stateDir, routeSlug(o.route.route), role, runId);
18190
- writeFileSync28(path, text2);
18551
+ writeFileSync29(path, text2);
18191
18552
  o.emit.emit(`queue digest written for ${role} (${Buffer.byteLength(text2)} bytes)`, {
18192
18553
  data: { role, bytes: Buffer.byteLength(text2) }
18193
18554
  });
@@ -18310,8 +18671,8 @@ async function claimStillHeld(tracker, t, buildingStatus, affinity) {
18310
18671
  }
18311
18672
 
18312
18673
  // src/repo-refresh.ts
18313
- import { existsSync as existsSync38, mkdirSync as mkdirSync26, readFileSync as readFileSync37, writeFileSync as writeFileSync29 } from "fs";
18314
- import { dirname as dirname21 } from "path";
18674
+ import { existsSync as existsSync39, mkdirSync as mkdirSync27, readFileSync as readFileSync38, writeFileSync as writeFileSync30 } from "fs";
18675
+ import { dirname as dirname22 } from "path";
18315
18676
  var REFRESH_COOLDOWN_MS = 2 * 6e4;
18316
18677
  var UNSERVABLE_PASSES_BEFORE_ATTENTION = 3;
18317
18678
  var lastAsked = /* @__PURE__ */ new Map();
@@ -18340,11 +18701,11 @@ function applyRepoRows(resolved, rows) {
18340
18701
  }
18341
18702
  function persistRepoRows(stateDir, routeName, rows) {
18342
18703
  const path = resolvedPathFor(stateDir, routeName);
18343
- if (!existsSync38(path)) return;
18344
- const raw = JSON.parse(readFileSync37(path, "utf8"));
18704
+ if (!existsSync39(path)) return;
18705
+ const raw = JSON.parse(readFileSync38(path, "utf8"));
18345
18706
  applyRepoRows(raw, rows);
18346
- mkdirSync26(dirname21(path), { recursive: true });
18347
- writeFileSync29(path, `${JSON.stringify(raw, null, 2)}
18707
+ mkdirSync27(dirname22(path), { recursive: true });
18708
+ writeFileSync30(path, `${JSON.stringify(raw, null, 2)}
18348
18709
  `);
18349
18710
  }
18350
18711
  async function refreshUnknownRepos(o) {
@@ -18794,7 +19155,7 @@ Ship ${shipName2} found: ${problem}. The release refuses to squash a ref nobody
18794
19155
  var localRefSkipReported = (ticket, problem, events) => events.some((e) => e.record_id === ticket.id && e.event_type === "local_ref_skip" && (e.message ?? "").includes(problem));
18795
19156
 
18796
19157
  // src/platform-gate.ts
18797
- import { join as join41 } from "path";
19158
+ import { join as join42 } from "path";
18798
19159
  function platformAdmitters(dir, baseRef, ship, tickets, locate) {
18799
19160
  const out = [];
18800
19161
  for (const t of tickets) {
@@ -18806,7 +19167,7 @@ function platformAdmitters(dir, baseRef, ship, tickets, locate) {
18806
19167
  const text2 = gitOk(dir, ["show", `${branch}:${file}`]);
18807
19168
  if (text2 === null) continue;
18808
19169
  try {
18809
- const { platform: platform2 } = parseRepoConfig(text2, join41(dir, file));
19170
+ const { platform: platform2 } = parseRepoConfig(text2, join42(dir, file));
18810
19171
  if (satisfies(ship, platform2)) out.push({ issueId: t.issue_id, branch, platform: platform2 });
18811
19172
  } catch (e) {
18812
19173
  if (e instanceof RepoConfigError) continue;
@@ -18822,13 +19183,13 @@ function platformStuckNote(repo, required, ship, issueIds) {
18822
19183
  }
18823
19184
 
18824
19185
  // src/connect-wizard.ts
18825
- import { delimiter, dirname as dirname22, join as join42 } from "path";
18826
- import { accessSync as accessSync3, constants as constants3, existsSync as existsSync39, mkdirSync as mkdirSync27, writeFileSync as writeFileSync30 } from "fs";
19186
+ import { delimiter, dirname as dirname23, join as join43 } from "path";
19187
+ import { accessSync as accessSync3, constants as constants3, existsSync as existsSync40, mkdirSync as mkdirSync28, writeFileSync as writeFileSync31 } from "fs";
18827
19188
  import { stringify as stringify3 } from "yaml";
18828
19189
  var HOST_PASSENGERS_DOCS_URL = "https://crew.tablation.dev/host-passengers";
18829
19190
  function shouldRunWizard(opts) {
18830
19191
  if (!opts.isTTY) return false;
18831
- const exists = opts.configExists ?? existsSync39;
19192
+ const exists = opts.configExists ?? existsSync40;
18832
19193
  return !configSearchPath(opts.crewHome).some((p) => exists(p));
18833
19194
  }
18834
19195
  function firstRunConfigPath() {
@@ -18845,7 +19206,7 @@ function defaultIsExecutable(p) {
18845
19206
  function findOnPath2(name, pathEnv, isExecutable = defaultIsExecutable) {
18846
19207
  for (const dir of pathEnv.split(delimiter)) {
18847
19208
  if (!dir) continue;
18848
- const candidate = join42(dir, name);
19209
+ const candidate = join43(dir, name);
18849
19210
  if (isExecutable(candidate)) return candidate;
18850
19211
  }
18851
19212
  return void 0;
@@ -18871,9 +19232,9 @@ async function runWizard(p, env) {
18871
19232
  if (entered && isExec(entered)) agentBin = entered;
18872
19233
  else p.say(entered ? `${entered} is not an executable file.` : "A path is required.");
18873
19234
  }
18874
- const nodeDir = dirname22(env.nodePath);
19235
+ const nodeDir = dirname23(env.nodePath);
18875
19236
  const pnpmPath = findOnPath2("pnpm", env.pathEnv, isExec);
18876
- const baseDirs = [nodeDir, pnpmPath ? dirname22(pnpmPath) : void 0];
19237
+ const baseDirs = [nodeDir, pnpmPath ? dirname23(pnpmPath) : void 0];
18877
19238
  p.say(
18878
19239
  `
18879
19240
  Host Passengers lets this machine run the agent sessions that other people's
@@ -18884,7 +19245,7 @@ Tablation workspaces ask for, in a container. More: ${HOST_PASSENGERS_DOCS_URL}`
18884
19245
  p.say("Docker is not available here, so nothing will be hosted until it is. Your answer is recorded anyway.");
18885
19246
  }
18886
19247
  const dockerPath = hostPassengers ? findOnPath2("docker", env.pathEnv, isExec) : void 0;
18887
- const extraPath = deriveExtraPath([...baseDirs, dockerPath ? dirname22(dockerPath) : void 0]);
19248
+ const extraPath = deriveExtraPath([...baseDirs, dockerPath ? dirname23(dockerPath) : void 0]);
18888
19249
  if (extraPath) {
18889
19250
  p.say(`Hooks will get ${extraPath} on their PATH (where node, pnpm${dockerPath ? " and docker" : ""} live).`);
18890
19251
  }
@@ -18906,9 +19267,9 @@ routes:
18906
19267
  ${routeBlock}`;
18907
19268
  }
18908
19269
  function writeNewConfig(path, text2) {
18909
- mkdirSync27(dirname22(path), { recursive: true });
19270
+ mkdirSync28(dirname23(path), { recursive: true });
18910
19271
  try {
18911
- writeFileSync30(path, text2, { mode: 384, flag: "wx" });
19272
+ writeFileSync31(path, text2, { mode: 384, flag: "wx" });
18912
19273
  return true;
18913
19274
  } catch (e) {
18914
19275
  if (e.code === "EEXIST") return false;
@@ -18942,7 +19303,7 @@ Wrote ${o.configPath}.
18942
19303
  // src/connect-json.ts
18943
19304
  import { accessSync as accessSync4, constants as constants4 } from "fs";
18944
19305
  import { homedir as homedir10 } from "os";
18945
- import { dirname as dirname23, join as join43 } from "path";
19306
+ import { dirname as dirname24, join as join44 } from "path";
18946
19307
  import { delimiter as delimiter2 } from "path";
18947
19308
  var CHOICE_EXIT_CODE = 3;
18948
19309
  function createEmitter(json2, write) {
@@ -18981,12 +19342,12 @@ function agentBinSearchDirs(home, pathEnv, extraPath) {
18981
19342
  const dirs = [
18982
19343
  ...pathEnv.split(delimiter2),
18983
19344
  ...(extraPath ?? "").split(delimiter2),
18984
- join43(home, ".local/bin"),
18985
- join43(home, ".claude/local"),
19345
+ join44(home, ".local/bin"),
19346
+ join44(home, ".claude/local"),
18986
19347
  "/opt/homebrew/bin",
18987
19348
  "/usr/local/bin",
18988
- join43(home, ".npm-global/bin"),
18989
- join43(home, ".volta/bin")
19349
+ join44(home, ".npm-global/bin"),
19350
+ join44(home, ".volta/bin")
18990
19351
  ];
18991
19352
  return [...new Set(dirs.filter(Boolean))];
18992
19353
  }
@@ -19008,7 +19369,7 @@ function flagWizardAnswers(f, env) {
19008
19369
  const agentBin = f.agentBin ?? found?.bin;
19009
19370
  const pnpmPath = findOnPath2("pnpm", env.pathEnv, isExec);
19010
19371
  const dockerPath = f.hostPassengers ? findOnPath2("docker", env.pathEnv, isExec) : void 0;
19011
- const extraPath = f.extraPath ?? deriveExtraPath([dirname23(env.nodePath), pnpmPath ? dirname23(pnpmPath) : void 0, dockerPath ? dirname23(dockerPath) : void 0]);
19372
+ const extraPath = f.extraPath ?? deriveExtraPath([dirname24(env.nodePath), pnpmPath ? dirname24(pnpmPath) : void 0, dockerPath ? dirname24(dockerPath) : void 0]);
19012
19373
  return {
19013
19374
  answers: {
19014
19375
  name: f.shipName?.trim() || env.hostname,
@@ -19107,8 +19468,8 @@ async function collectDiagnostics(d) {
19107
19468
  }
19108
19469
 
19109
19470
  // src/release-run.ts
19110
- import { readFileSync as readFileSync38, writeFileSync as writeFileSync31, existsSync as existsSync40, copyFileSync, mkdirSync as mkdirSync28, mkdtempSync as mkdtempSync3, rmSync as rmSync19 } from "fs";
19111
- import { dirname as dirname24, join as join44 } from "path";
19471
+ import { readFileSync as readFileSync39, writeFileSync as writeFileSync32, existsSync as existsSync41, copyFileSync, mkdirSync as mkdirSync29, mkdtempSync as mkdtempSync3, rmSync as rmSync20 } from "fs";
19472
+ import { dirname as dirname25, join as join45 } from "path";
19112
19473
  import { tmpdir as tmpdir6, hostname as hostname4 } from "os";
19113
19474
 
19114
19475
  // src/release.ts
@@ -19890,13 +20251,13 @@ async function bump(o, size) {
19890
20251
  }
19891
20252
  return printed;
19892
20253
  }
19893
- const files = o.repo.release.versionFiles.map((f) => join44(o.cwd, f));
20254
+ const files = o.repo.release.versionFiles.map((f) => join45(o.cwd, f));
19894
20255
  const first = files[0];
19895
- if (!existsAt(first, existsSync40)) {
20256
+ if (!existsAt(first, existsSync41)) {
19896
20257
  o.emit.error(`no ${o.repo.release.versionFiles[0]} to read a version from`);
19897
20258
  return null;
19898
20259
  }
19899
- const firstText = readTextAt(first, (p) => readFileSync38(p, "utf8"));
20260
+ const firstText = readTextAt(first, (p) => readFileSync39(p, "utf8"));
19900
20261
  const problem = versionFileProblem(o.repo.release.versionFiles[0], firstText);
19901
20262
  if (problem) {
19902
20263
  o.emit.error(problem);
@@ -19915,27 +20276,27 @@ async function bump(o, size) {
19915
20276
  return version;
19916
20277
  }
19917
20278
  for (const f of files) {
19918
- const src = readTextAt(f, (p) => readFileSync38(p, "utf8"));
20279
+ const src = readTextAt(f, (p) => readFileSync39(p, "utf8"));
19919
20280
  const out = src.replace(/("version"\s*:\s*")[^"]*(")/, `$1${version}$2`);
19920
20281
  if (out === src) {
19921
20282
  o.emit.error(`no version field in ${f}`);
19922
20283
  return null;
19923
20284
  }
19924
- writeTextAt(f, out, writeFileSync31);
20285
+ writeTextAt(f, out, writeFileSync32);
19925
20286
  }
19926
20287
  return version;
19927
20288
  }
19928
20289
  function writeChangelog(o, version, entries) {
19929
20290
  const file = o.repo.release.changelog;
19930
20291
  if (!file || entries.length === 0) return;
19931
- const path = join44(o.cwd, file);
20292
+ const path = join45(o.cwd, file);
19932
20293
  const section = renderChangelogSection(version, (/* @__PURE__ */ new Date()).toISOString().slice(0, 10), entries);
19933
20294
  if (o.dryRun) {
19934
20295
  o.emit.emit(`would prepend ${entries.length} entr(ies) to ${file}`);
19935
20296
  return;
19936
20297
  }
19937
- const existing = existsAt(path, existsSync40) ? readTextAt(path, (p) => readFileSync38(p, "utf8")) : "# Changelog\n";
19938
- writeTextAt(path, insertChangelogSection(existing, section), writeFileSync31);
20298
+ const existing = existsAt(path, existsSync41) ? readTextAt(path, (p) => readFileSync39(p, "utf8")) : "# Changelog\n";
20299
+ writeTextAt(path, insertChangelogSection(existing, section), writeFileSync32);
19939
20300
  }
19940
20301
  async function confirm(o, expected) {
19941
20302
  if (!o.repo.hooks.released) return void 0;
@@ -20018,7 +20379,7 @@ function closeReleaseCheckout(cwd, root, dir, branch, run4 = gitOk) {
20018
20379
  run4(cwd, ["worktree", "remove", "--force", dir]);
20019
20380
  } finally {
20020
20381
  try {
20021
- rmSync19(root, { recursive: true, force: true });
20382
+ rmSync20(root, { recursive: true, force: true });
20022
20383
  } finally {
20023
20384
  run4(cwd, ["worktree", "prune"]);
20024
20385
  run4(cwd, ["branch", "-D", branch]);
@@ -20028,8 +20389,8 @@ function closeReleaseCheckout(cwd, root, dir, branch, run4 = gitOk) {
20028
20389
  function openReleaseCheckout(o) {
20029
20390
  const { remote, base } = o.repo.branch;
20030
20391
  const branch = `crew/release-${Date.now()}`;
20031
- const root = mkdtempSync3(join44(tmpdir6(), "crew-release-"));
20032
- const dir = join44(root, "checkout");
20392
+ const root = mkdtempSync3(join45(tmpdir6(), "crew-release-"));
20393
+ const dir = join45(root, "checkout");
20033
20394
  o.emit.emit(`release checkout: ${dir}`, { step: "release" });
20034
20395
  const close = () => closeReleaseCheckout(o.cwd, root, dir, branch);
20035
20396
  try {
@@ -20039,10 +20400,10 @@ function openReleaseCheckout(o) {
20039
20400
  throw e;
20040
20401
  }
20041
20402
  for (const f of o.repo.worktrees.copy) {
20042
- const src = join44(o.cwd, f);
20043
- if (!existsSync40(src)) continue;
20044
- mkdirSync28(dirname24(join44(dir, f)), { recursive: true });
20045
- copyFileSync(src, join44(dir, f));
20403
+ const src = join45(o.cwd, f);
20404
+ if (!existsSync41(src)) continue;
20405
+ mkdirSync29(dirname25(join45(dir, f)), { recursive: true });
20406
+ copyFileSync(src, join45(dir, f));
20046
20407
  }
20047
20408
  return { dir, branch, close };
20048
20409
  }
@@ -20768,11 +21129,11 @@ Passed: ${passed}.${willClose ? " Closing this alert." : ""}`,
20768
21129
  }
20769
21130
 
20770
21131
  // src/daemon-liveness.ts
20771
- import { existsSync as existsSync47, readFileSync as readFileSync44 } from "fs";
21132
+ import { existsSync as existsSync48, readFileSync as readFileSync45 } from "fs";
20772
21133
 
20773
21134
  // src/daemon.ts
20774
- import { existsSync as existsSync46, mkdirSync as mkdirSync34, readFileSync as readFileSync43, readdirSync as readdirSync14, rmSync as rmSync21, statSync as statSync13, writeFileSync as writeFileSync35 } from "fs";
20775
- import { join as join49 } from "path";
21135
+ import { existsSync as existsSync47, mkdirSync as mkdirSync35, readFileSync as readFileSync44, readdirSync as readdirSync14, rmSync as rmSync22, statSync as statSync13, writeFileSync as writeFileSync36 } from "fs";
21136
+ import { join as join50 } from "path";
20776
21137
  import { randomBytes } from "crypto";
20777
21138
 
20778
21139
  // src/fleet.ts
@@ -20862,27 +21223,27 @@ function nextRoles(decision, ran) {
20862
21223
  }
20863
21224
 
20864
21225
  // src/noop-runs.ts
20865
- import { existsSync as existsSync41, mkdirSync as mkdirSync29, readFileSync as readFileSync39, renameSync as renameSync5, writeFileSync as writeFileSync32 } from "fs";
20866
- import { join as join45 } from "path";
21226
+ import { existsSync as existsSync42, mkdirSync as mkdirSync30, readFileSync as readFileSync40, renameSync as renameSync6, writeFileSync as writeFileSync33 } from "fs";
21227
+ import { join as join46 } from "path";
20867
21228
  var NOOP_DELAYS_MS = [5, 15, 60].map((m) => m * 6e4);
20868
21229
  var DEFAULT_NOOP_REPEATS = 3;
20869
21230
  var NOOP_BOUNCED_MARKER = calloutHeader("WARNING", "Runs Changed Nothing");
20870
- var noopRunsPath = (stateDir) => join45(stateDir, "noop-runs.json");
21231
+ var noopRunsPath = (stateDir) => join46(stateDir, "noop-runs.json");
20871
21232
  var noopRunsKey = (issueId) => `noop_runs:${issueId}`;
20872
21233
  function readNoopRuns(stateDir) {
20873
21234
  try {
20874
- const v = JSON.parse(readFileSync39(noopRunsPath(stateDir), "utf8"));
21235
+ const v = JSON.parse(readFileSync40(noopRunsPath(stateDir), "utf8"));
20875
21236
  return v && typeof v === "object" && !Array.isArray(v) ? v : {};
20876
21237
  } catch {
20877
21238
  return {};
20878
21239
  }
20879
21240
  }
20880
21241
  function writeNoopRuns(stateDir, state) {
20881
- mkdirSync29(stateDir, { recursive: true });
21242
+ mkdirSync30(stateDir, { recursive: true });
20882
21243
  const file = noopRunsPath(stateDir);
20883
- writeFileSync32(`${file}.tmp`, `${JSON.stringify(state, null, 2)}
21244
+ writeFileSync33(`${file}.tmp`, `${JSON.stringify(state, null, 2)}
20884
21245
  `);
20885
- renameSync5(`${file}.tmp`, file);
21246
+ renameSync6(`${file}.tmp`, file);
20886
21247
  }
20887
21248
  function noopBackedOff(stateDir, recordId, now = Date.now()) {
20888
21249
  const e = readNoopRuns(stateDir)[recordId];
@@ -20897,7 +21258,7 @@ function recordNoopRun(stateDir, recordId, repeats, now = Date.now()) {
20897
21258
  return { count, nextAt, bounce: count >= repeats };
20898
21259
  }
20899
21260
  function clearNoopRuns(stateDir, recordId) {
20900
- if (!existsSync41(noopRunsPath(stateDir))) return;
21261
+ if (!existsSync42(noopRunsPath(stateDir))) return;
20901
21262
  const state = readNoopRuns(stateDir);
20902
21263
  if (!(recordId in state)) return;
20903
21264
  delete state[recordId];
@@ -20957,8 +21318,8 @@ async function settleNoopRun(o) {
20957
21318
  }
20958
21319
 
20959
21320
  // src/ship-name.ts
20960
- import { existsSync as existsSync42, mkdirSync as mkdirSync30, readFileSync as readFileSync40, renameSync as renameSync6, writeFileSync as writeFileSync33 } from "fs";
20961
- import { dirname as dirname25 } from "path";
21321
+ import { existsSync as existsSync43, mkdirSync as mkdirSync31, readFileSync as readFileSync41, renameSync as renameSync7, writeFileSync as writeFileSync34 } from "fs";
21322
+ import { dirname as dirname26 } from "path";
20962
21323
  import { parseDocument as parseDocument4 } from "yaml";
20963
21324
  var ShipNameError = class extends Error {
20964
21325
  };
@@ -21019,34 +21380,34 @@ async function syncRouteName(i) {
21019
21380
  return { status: "ok", ...base, action, name: i.local };
21020
21381
  }
21021
21382
  function readSyncedName(resolvedFile) {
21022
- if (!existsSync42(resolvedFile)) return void 0;
21383
+ if (!existsSync43(resolvedFile)) return void 0;
21023
21384
  try {
21024
- const v = JSON.parse(readFileSync40(resolvedFile, "utf8")).shipName;
21385
+ const v = JSON.parse(readFileSync41(resolvedFile, "utf8")).shipName;
21025
21386
  return typeof v === "string" ? v : void 0;
21026
21387
  } catch {
21027
21388
  return void 0;
21028
21389
  }
21029
21390
  }
21030
21391
  function writeSyncedName(resolvedFile, name) {
21031
- if (!existsSync42(resolvedFile)) return;
21392
+ if (!existsSync43(resolvedFile)) return;
21032
21393
  let raw;
21033
21394
  try {
21034
- raw = JSON.parse(readFileSync40(resolvedFile, "utf8"));
21395
+ raw = JSON.parse(readFileSync41(resolvedFile, "utf8"));
21035
21396
  } catch {
21036
21397
  return;
21037
21398
  }
21038
21399
  if (raw.shipName === name) return;
21039
21400
  raw.shipName = name;
21040
- mkdirSync30(dirname25(resolvedFile), { recursive: true });
21401
+ mkdirSync31(dirname26(resolvedFile), { recursive: true });
21041
21402
  const tmp = `${resolvedFile}.tmp${process.pid}`;
21042
- writeFileSync33(tmp, `${JSON.stringify(raw, null, 2)}
21403
+ writeFileSync34(tmp, `${JSON.stringify(raw, null, 2)}
21043
21404
  `);
21044
- renameSync6(tmp, resolvedFile);
21405
+ renameSync7(tmp, resolvedFile);
21045
21406
  }
21046
21407
  async function reconcileShipName(i) {
21047
21408
  let local = i.ship.name;
21048
21409
  try {
21049
- local = shipNameOfYaml(readFileSync40(i.configFile, "utf8")) ?? local;
21410
+ local = shipNameOfYaml(readFileSync41(i.configFile, "utf8")) ?? local;
21050
21411
  } catch {
21051
21412
  }
21052
21413
  const resolvedFile = resolvedPathFor(i.stateDir, i.route);
@@ -21070,8 +21431,8 @@ async function reconcileShipName(i) {
21070
21431
  }
21071
21432
  if (result.status !== "ok") return result;
21072
21433
  if (result.action === "adopt" || result.action === "row-wins") {
21073
- const text2 = readFileSync40(i.configFile, "utf8");
21074
- writeFileSync33(i.configFile, setShipNameInYaml(text2, result.name));
21434
+ const text2 = readFileSync41(i.configFile, "utf8");
21435
+ writeFileSync34(i.configFile, setShipNameInYaml(text2, result.name));
21075
21436
  i.ship.name = result.name;
21076
21437
  if (result.action === "row-wins") {
21077
21438
  i.emit?.warn(
@@ -21116,11 +21477,11 @@ async function reconcileRouteShipName(o) {
21116
21477
  }
21117
21478
 
21118
21479
  // src/mirror-contract.ts
21119
- import { existsSync as existsSync43 } from "fs";
21480
+ import { existsSync as existsSync44 } from "fs";
21120
21481
 
21121
21482
  // src/passenger-mirror.ts
21122
- import { mkdirSync as mkdirSync31 } from "fs";
21123
- import { dirname as dirname26 } from "path";
21483
+ import { mkdirSync as mkdirSync32 } from "fs";
21484
+ import { dirname as dirname27 } from "path";
21124
21485
  function mirrorRepoOf(spec) {
21125
21486
  const fromOrigin = spec.originUrl ? parseRemote(spec.originUrl) : null;
21126
21487
  if (fromOrigin) return fromOrigin;
@@ -21138,9 +21499,9 @@ async function materializeMirrorCheckouts(specs, cacheFor = (s) => new SandboxCa
21138
21499
  continue;
21139
21500
  }
21140
21501
  try {
21141
- const parent = dirname26(spec.dir);
21142
- mkdirSync31(parent, { recursive: true });
21143
- mkdirSync31(spec.dir, { recursive: true });
21502
+ const parent = dirname27(spec.dir);
21503
+ mkdirSync32(parent, { recursive: true });
21504
+ mkdirSync32(spec.dir, { recursive: true });
21144
21505
  const r = await cacheFor(spec).materialize(repo, spec.base, parent, spec.name);
21145
21506
  out.push({ ...base, action: r.changed ? "updated" : "unchanged", detail: r.tip });
21146
21507
  } catch (e) {
@@ -21157,7 +21518,7 @@ function mirrorOutcome(m) {
21157
21518
 
21158
21519
  // src/mirror-contract.ts
21159
21520
  function lacksCheckout(ship, dir) {
21160
- return ship.runner === "sandbox" && !existsSync43(dir) && !remoteOf(dir);
21521
+ return ship.runner === "sandbox" && !existsSync44(dir) && !remoteOf(dir);
21161
21522
  }
21162
21523
  function skipsHostCheckout(ship) {
21163
21524
  return ship.runner === "sandbox";
@@ -21238,18 +21599,18 @@ function explainRefusal(readable, unreadable) {
21238
21599
 
21239
21600
  // src/ssh-keys.ts
21240
21601
  import { execFileSync as execFileSync13 } from "child_process";
21241
- import { existsSync as existsSync44, mkdirSync as mkdirSync32, readFileSync as readFileSync41, chmodSync as chmodSync3 } from "fs";
21242
- import { dirname as dirname27, join as join46 } from "path";
21602
+ import { existsSync as existsSync45, mkdirSync as mkdirSync33, readFileSync as readFileSync42, chmodSync as chmodSync3 } from "fs";
21603
+ import { dirname as dirname28, join as join47 } from "path";
21243
21604
  var SshKeyError = class extends Error {
21244
21605
  };
21245
21606
  function shipSshKeyPathFor(stateDir) {
21246
- return join46(stateDir, "ssh", "id_ed25519");
21607
+ return join47(stateDir, "ssh", "id_ed25519");
21247
21608
  }
21248
21609
  function ensureShipSshKeypair(stateDir) {
21249
21610
  const privateKeyPath = shipSshKeyPathFor(stateDir);
21250
21611
  const publicKeyPath = `${privateKeyPath}.pub`;
21251
- if (!existsSync44(privateKeyPath)) {
21252
- mkdirSync32(dirname27(privateKeyPath), { recursive: true });
21612
+ if (!existsSync45(privateKeyPath)) {
21613
+ mkdirSync33(dirname28(privateKeyPath), { recursive: true });
21253
21614
  try {
21254
21615
  execFileSync13("ssh-keygen", [
21255
21616
  "-t",
@@ -21269,10 +21630,10 @@ function ensureShipSshKeypair(stateDir) {
21269
21630
  }
21270
21631
  chmodSync3(privateKeyPath, 384);
21271
21632
  }
21272
- if (!existsSync44(publicKeyPath)) {
21633
+ if (!existsSync45(publicKeyPath)) {
21273
21634
  throw new SshKeyError(`${privateKeyPath} exists but ${publicKeyPath} does not \u2014 regenerate or restore it`);
21274
21635
  }
21275
- const publicKey = readFileSync41(publicKeyPath, "utf8").trim();
21636
+ const publicKey = readFileSync42(publicKeyPath, "utf8").trim();
21276
21637
  return { privateKeyPath, publicKeyPath, publicKey };
21277
21638
  }
21278
21639
  function sshKeygenAvailable() {
@@ -21287,7 +21648,7 @@ function sshKeygenAvailable() {
21287
21648
  // src/periscope-idle.ts
21288
21649
  import { execFileSync as execFileSync14 } from "child_process";
21289
21650
  import { statSync as statSync12 } from "fs";
21290
- import { join as join47 } from "path";
21651
+ import { join as join48 } from "path";
21291
21652
  var MAX_SCANNED_FILES = 2e4;
21292
21653
  function newestWorktreeMtime(root) {
21293
21654
  const a = newestTrackedMtime(root);
@@ -21312,7 +21673,7 @@ function newestTrackedMtime(root) {
21312
21673
  if (!rel) continue;
21313
21674
  if (++scanned > MAX_SCANNED_FILES) break;
21314
21675
  try {
21315
- const m = statSync12(join47(root, rel)).mtimeMs;
21676
+ const m = statSync12(join48(root, rel)).mtimeMs;
21316
21677
  if (newest === null || m > newest) newest = m;
21317
21678
  } catch {
21318
21679
  }
@@ -21386,8 +21747,8 @@ async function runPeriscopeIdlePass(d) {
21386
21747
  }
21387
21748
 
21388
21749
  // src/periscope-cmd.ts
21389
- import { existsSync as existsSync45, mkdirSync as mkdirSync33, readFileSync as readFileSync42, rmSync as rmSync20, writeFileSync as writeFileSync34 } from "fs";
21390
- import { join as join48 } from "path";
21750
+ import { existsSync as existsSync46, mkdirSync as mkdirSync34, readFileSync as readFileSync43, rmSync as rmSync21, writeFileSync as writeFileSync35 } from "fs";
21751
+ import { join as join49 } from "path";
21391
21752
  var PeriscopeError = class extends Error {
21392
21753
  };
21393
21754
  var LivePeriscopeError = class extends PeriscopeError {
@@ -21397,22 +21758,22 @@ var LivePeriscopeError = class extends PeriscopeError {
21397
21758
  this.data = { refused: "live_periscope_exists", ...live };
21398
21759
  }
21399
21760
  };
21400
- var priorDir = (stateDir) => join48(stateDir, "periscope-priors");
21401
- var priorPath = (stateDir, ticketRecordId) => join48(priorDir(stateDir), `${ticketRecordId}.json`);
21761
+ var priorDir = (stateDir) => join49(stateDir, "periscope-priors");
21762
+ var priorPath = (stateDir, ticketRecordId) => join49(priorDir(stateDir), `${ticketRecordId}.json`);
21402
21763
  function removePeriscopePrior(stateDir, ticketRecordId) {
21403
- rmSync20(priorPath(stateDir, ticketRecordId), { force: true });
21764
+ rmSync21(priorPath(stateDir, ticketRecordId), { force: true });
21404
21765
  }
21405
21766
  function writePeriscopePrior(stateDir, ticketRecordId, prior) {
21406
21767
  try {
21407
- mkdirSync33(priorDir(stateDir), { recursive: true });
21408
- writeFileSync34(priorPath(stateDir, ticketRecordId), JSON.stringify(prior));
21768
+ mkdirSync34(priorDir(stateDir), { recursive: true });
21769
+ writeFileSync35(priorPath(stateDir, ticketRecordId), JSON.stringify(prior));
21409
21770
  } catch {
21410
21771
  }
21411
21772
  }
21412
21773
  function readPeriscopePrior(stateDir, ticketRecordId) {
21413
21774
  try {
21414
21775
  const p = priorPath(stateDir, ticketRecordId);
21415
- return existsSync45(p) ? JSON.parse(readFileSync42(p, "utf8")) : void 0;
21776
+ return existsSync46(p) ? JSON.parse(readFileSync43(p, "utf8")) : void 0;
21416
21777
  } catch {
21417
21778
  return void 0;
21418
21779
  }
@@ -21981,7 +22342,7 @@ function latestMtime(path) {
21981
22342
  if (!stat2.isDirectory()) return 0;
21982
22343
  let latest = stat2.mtimeMs;
21983
22344
  for (const entry of readdirSync14(path, { withFileTypes: true })) {
21984
- latest = Math.max(latest, latestMtime(join49(path, entry.name)));
22345
+ latest = Math.max(latest, latestMtime(join50(path, entry.name)));
21985
22346
  }
21986
22347
  return latest;
21987
22348
  }
@@ -21990,10 +22351,10 @@ function computeTreeSignature(paths) {
21990
22351
  }
21991
22352
  function makeStaleChecker(paths, opts = {}) {
21992
22353
  const initial = computeTreeSignature(paths);
21993
- return () => computeTreeSignature(paths) !== initial || opts.reloadSentinel !== void 0 && existsSync46(opts.reloadSentinel);
22354
+ return () => computeTreeSignature(paths) !== initial || opts.reloadSentinel !== void 0 && existsSync47(opts.reloadSentinel);
21994
22355
  }
21995
22356
  function reloadSentinelFor(stateDir) {
21996
- return join49(stateDir, "reload-requested");
22357
+ return join50(stateDir, "reload-requested");
21997
22358
  }
21998
22359
  function readReloadRequestedAt(stateDir) {
21999
22360
  try {
@@ -22003,17 +22364,17 @@ function readReloadRequestedAt(stateDir) {
22003
22364
  }
22004
22365
  }
22005
22366
  function daemonStampFor(stateDir) {
22006
- return join49(stateDir, "daemon.started");
22367
+ return join50(stateDir, "daemon.started");
22007
22368
  }
22008
22369
  function noteDaemonStarted(stateDir, now = Date.now()) {
22009
- mkdirSync34(stateDir, { recursive: true });
22010
- rmSync21(reloadSentinelFor(stateDir), { force: true });
22011
- writeFileSync35(daemonStampFor(stateDir), `${JSON.stringify({ pid: process.pid, startedAt: now })}
22370
+ mkdirSync35(stateDir, { recursive: true });
22371
+ rmSync22(reloadSentinelFor(stateDir), { force: true });
22372
+ writeFileSync36(daemonStampFor(stateDir), `${JSON.stringify({ pid: process.pid, startedAt: now })}
22012
22373
  `);
22013
22374
  }
22014
22375
  function readDaemonStarted(stateDir) {
22015
22376
  try {
22016
- const v = JSON.parse(readFileSync43(daemonStampFor(stateDir), "utf8")).startedAt;
22377
+ const v = JSON.parse(readFileSync44(daemonStampFor(stateDir), "utf8")).startedAt;
22017
22378
  return typeof v === "number" ? v : null;
22018
22379
  } catch {
22019
22380
  return null;
@@ -22869,7 +23230,7 @@ function parseSystemctlShow(text2) {
22869
23230
  }
22870
23231
  function lastLogLine(path, read = (p) => {
22871
23232
  try {
22872
- return readFileSync44(p, "utf8");
23233
+ return readFileSync45(p, "utf8");
22873
23234
  } catch {
22874
23235
  return null;
22875
23236
  }
@@ -22896,7 +23257,7 @@ function probeDaemonUnit(o) {
22896
23257
  const r = spawnSync11(cmd[0], cmd.slice(1), { encoding: "utf8" });
22897
23258
  return r.error ? null : { status: r.status, stdout: r.stdout ?? "" };
22898
23259
  });
22899
- const installed = o.plan.unitPaths.some((p) => existsSync47(p));
23260
+ const installed = o.plan.unitPaths.some((p) => existsSync48(p));
22900
23261
  let reading = null;
22901
23262
  if (installed && o.plan.mechanism === "launchd") {
22902
23263
  const r = run4(["launchctl", "print", `gui/${o.uid}/${o.label}`]);
@@ -22946,7 +23307,7 @@ function daemonProblem(d, route2) {
22946
23307
  }
22947
23308
  function readDaemonStamp(stateDir) {
22948
23309
  try {
22949
- const v = JSON.parse(readFileSync44(daemonStampFor(stateDir), "utf8"));
23310
+ const v = JSON.parse(readFileSync45(daemonStampFor(stateDir), "utf8"));
22950
23311
  if (typeof v.startedAt !== "number") return null;
22951
23312
  return typeof v.pid === "number" ? { pid: v.pid, startedAt: v.startedAt } : { startedAt: v.startedAt };
22952
23313
  } catch {
@@ -22955,15 +23316,15 @@ function readDaemonStamp(stateDir) {
22955
23316
  }
22956
23317
 
22957
23318
  // src/daemon-start-failure.ts
22958
- import { existsSync as existsSync48, mkdirSync as mkdirSync35, readFileSync as readFileSync45, unlinkSync as unlinkSync4, writeFileSync as writeFileSync36 } from "fs";
22959
- import { dirname as dirname28, join as join50 } from "path";
23319
+ import { existsSync as existsSync49, mkdirSync as mkdirSync36, readFileSync as readFileSync46, unlinkSync as unlinkSync4, writeFileSync as writeFileSync37 } from "fs";
23320
+ import { dirname as dirname29, join as join51 } from "path";
22960
23321
  var DAEMON_START_FAILED_KEY = "daemon_start_failed";
22961
23322
  var START_FAILURE_BACKOFF_MS = 6e4;
22962
23323
  var BACKOFF_AFTER_FAILURES = 2;
22963
- var fileFor3 = (stateDir) => join50(stateDir, ".daemon-start-failure.json");
23324
+ var fileFor3 = (stateDir) => join51(stateDir, ".daemon-start-failure.json");
22964
23325
  function readStartFailure(stateDir) {
22965
23326
  try {
22966
- const parsed = JSON.parse(readFileSync45(fileFor3(stateDir), "utf8"));
23327
+ const parsed = JSON.parse(readFileSync46(fileFor3(stateDir), "utf8"));
22967
23328
  return typeof parsed.reason === "string" && typeof parsed.count === "number" ? { reason: parsed.reason, count: parsed.count, firstAt: String(parsed.firstAt), lastAt: String(parsed.lastAt) } : null;
22968
23329
  } catch {
22969
23330
  return null;
@@ -22979,8 +23340,8 @@ function noteStartFailure(stateDir, reason, nowMs = Date.now()) {
22979
23340
  firstAt: same ? previous.firstAt : nowIso,
22980
23341
  lastAt: nowIso
22981
23342
  };
22982
- mkdirSync35(stateDir, { recursive: true });
22983
- writeFileSync36(fileFor3(stateDir), JSON.stringify(record));
23343
+ mkdirSync36(stateDir, { recursive: true });
23344
+ writeFileSync37(fileFor3(stateDir), JSON.stringify(record));
22984
23345
  return record;
22985
23346
  }
22986
23347
  function startFailureDelayMs(count) {
@@ -22994,7 +23355,7 @@ function startFailureItem(record, o = {}) {
22994
23355
  return { kind: "daemon_start_failed", key: DAEMON_START_FAILED_KEY, message: parts.join(". ").replace(/\.\./g, "."), since: record.firstAt };
22995
23356
  }
22996
23357
  function clearStartFailure(state, stateDir) {
22997
- if (existsSync48(fileFor3(stateDir))) {
23358
+ if (existsSync49(fileFor3(stateDir))) {
22998
23359
  try {
22999
23360
  unlinkSync4(fileFor3(stateDir));
23000
23361
  } catch {
@@ -23021,7 +23382,7 @@ async function reportStartFailure(o) {
23021
23382
  return delay;
23022
23383
  }
23023
23384
  function fallbackStateDir(configFile) {
23024
- return join50(dirname28(configFile), "state");
23385
+ return join51(dirname29(configFile), "state");
23025
23386
  }
23026
23387
 
23027
23388
  // src/projects-cmd.ts
@@ -23135,8 +23496,8 @@ function runForge(a, io) {
23135
23496
 
23136
23497
  // src/release-sandbox.ts
23137
23498
  import { execFile as execFile5 } from "child_process";
23138
- import { mkdirSync as mkdirSync36, writeFileSync as writeFileSync37 } from "fs";
23139
- import { dirname as dirname29 } from "path";
23499
+ import { mkdirSync as mkdirSync37, writeFileSync as writeFileSync38 } from "fs";
23500
+ import { dirname as dirname30 } from "path";
23140
23501
  import { promisify as promisify4 } from "util";
23141
23502
  var execFileP4 = promisify4(execFile5);
23142
23503
  var RELEASE_CLONE_DEPTH = 50;
@@ -23182,8 +23543,8 @@ async function openReleaseSandbox(o) {
23182
23543
  if (!policyFile) {
23183
23544
  generated = generateSandboxPolicy({ mirrorDir: cfg.mirrorDir, workDir: cfg.workDir, ...o.policy });
23184
23545
  policyFile = o.policyFile;
23185
- mkdirSync36(dirname29(policyFile), { recursive: true });
23186
- writeFileSync37(policyFile, generated.yaml, { mode: 384 });
23546
+ mkdirSync37(dirname30(policyFile), { recursive: true });
23547
+ writeFileSync38(policyFile, generated.yaml, { mode: 384 });
23187
23548
  }
23188
23549
  const secrets = { ...process.env };
23189
23550
  const secretKeys = [];
@@ -23349,7 +23710,7 @@ function missingReleaserWarning(repo, release, ships, now = Date.now()) {
23349
23710
  }
23350
23711
 
23351
23712
  // src/watch.ts
23352
- import { watch as watchFile, existsSync as existsSync49, statSync as statSync14, openSync as openSync5, readSync as readSync2, closeSync as closeSync5 } from "fs";
23713
+ import { watch as watchFile, existsSync as existsSync50, statSync as statSync14, openSync as openSync5, readSync as readSync2, closeSync as closeSync5 } from "fs";
23353
23714
  var E = "\x1B[";
23354
23715
  var dim = (s) => `${E}2m${s}${E}0m`;
23355
23716
  var bold = (s) => `${E}1m${s}${E}0m`;
@@ -23450,7 +23811,7 @@ function renderHeaders(states, now = Date.now()) {
23450
23811
  return states.map((s) => renderHeader(s, now)).join("");
23451
23812
  }
23452
23813
  function readFrom(file, from) {
23453
- if (!existsSync49(file)) return { events: [], offset: from };
23814
+ if (!existsSync50(file)) return { events: [], offset: from };
23454
23815
  const size = statSync14(file).size;
23455
23816
  if (size < from) return readFrom(file, 0);
23456
23817
  if (size === from) return { events: [], offset: from };
@@ -24220,9 +24581,78 @@ function describeCapability(i) {
24220
24581
  return `missing ${missLine(i)}`;
24221
24582
  }
24222
24583
 
24584
+ // src/persona-avatars.ts
24585
+ import { existsSync as existsSync51, readFileSync as readFileSync47 } from "fs";
24586
+ import { join as join52 } from "path";
24587
+ var IMAGE_TYPES = { png: "image/png", svg: "image/svg+xml" };
24588
+ function personaAvatarFile(promptsDir, role) {
24589
+ for (const ext of ["png", "svg"]) {
24590
+ const name = `lane-${role}.${ext}`;
24591
+ const path = join52(promptsDir, "personas", name);
24592
+ if (existsSync51(path)) return { path, mimeType: IMAGE_TYPES[ext], name };
24593
+ }
24594
+ return void 0;
24595
+ }
24596
+ async function syncPersonaAvatars(route2, agentPersonas, opts) {
24597
+ if (!route2.resolved) return [];
24598
+ const base = `${route2.baseUrl.replace(/\/+$/, "")}/api/workspaces/${route2.resolved.workspaceId}/agents/personas`;
24599
+ const outcomes = [];
24600
+ for (const role of ROLE_NAMES) {
24601
+ const file = personaAvatarFile(route2.promptsDir, role);
24602
+ const agentId = agentPersonas[role]?.agentId;
24603
+ if (!file || !agentId) continue;
24604
+ try {
24605
+ const form = new FormData();
24606
+ form.append("file", new Blob([readFileSync47(file.path)], { type: file.mimeType }), file.name);
24607
+ const res = await fetch(`${base}/${agentId}/avatar`, {
24608
+ method: "PUT",
24609
+ headers: { Authorization: `Bearer ${resolveApiKey(route2)}`, "User-Agent": opts.userAgent ?? "Mozilla/5.0 TablationCrewAgent/1.0" },
24610
+ body: form
24611
+ });
24612
+ if (!res.ok) {
24613
+ outcomes.push({ role, status: "failed", detail: `${res.status} ${(await res.text()).slice(0, 200)}`.trim() });
24614
+ continue;
24615
+ }
24616
+ const body = await res.json();
24617
+ if (body.status === "updated" || body.status === "unchanged" || body.status === "skipped") {
24618
+ outcomes.push({ role, status: body.status, ...body.reason ? { detail: body.reason } : {} });
24619
+ } else {
24620
+ outcomes.push({ role, status: "failed", detail: "unrecognised response" });
24621
+ }
24622
+ } catch (e) {
24623
+ outcomes.push({ role, status: "failed", detail: e instanceof Error ? e.message : String(e) });
24624
+ }
24625
+ }
24626
+ return outcomes;
24627
+ }
24628
+ function describeAvatarOutcome(o, label) {
24629
+ switch (o.status) {
24630
+ case "updated":
24631
+ return `${label}: avatar uploaded`;
24632
+ case "unchanged":
24633
+ return `${label}: avatar already current`;
24634
+ case "skipped":
24635
+ return `${label}: avatar left alone${o.detail ? ` (${o.detail})` : ""}`;
24636
+ case "failed":
24637
+ return `${label}: avatar upload failed \u2014 ${o.detail ?? "unknown error"}`;
24638
+ }
24639
+ }
24640
+ function avatarFailures(raw) {
24641
+ const map = raw?.avatarSyncFailures;
24642
+ if (!map || typeof map !== "object") return [];
24643
+ return Object.entries(map).map(([role, detail]) => ({ role, detail: String(detail) }));
24644
+ }
24645
+ function routeAvatarFailures(stateDir, route2) {
24646
+ try {
24647
+ return avatarFailures(JSON.parse(readFileSync47(resolvedPathFor(stateDir, route2), "utf8")));
24648
+ } catch {
24649
+ return [];
24650
+ }
24651
+ }
24652
+
24223
24653
  // src/agents-sync-run.ts
24224
- import { existsSync as existsSync50, mkdirSync as mkdirSync37, readFileSync as readFileSync46, writeFileSync as writeFileSync38 } from "fs";
24225
- import { dirname as dirname30 } from "path";
24654
+ import { existsSync as existsSync52, mkdirSync as mkdirSync38, readFileSync as readFileSync48, writeFileSync as writeFileSync39 } from "fs";
24655
+ import { dirname as dirname31 } from "path";
24226
24656
  async function runAgentsSync(target, o) {
24227
24657
  const dryRun = o.dryRun ?? false;
24228
24658
  const force = o.force ?? false;
@@ -24255,14 +24685,25 @@ async function runAgentsSync(target, o) {
24255
24685
  }
24256
24686
  for (const s of skillResult?.outcomes ?? []) o.say(describeSkillSyncOutcome(s));
24257
24687
  for (const w of skillResult?.warnings ?? []) o.warn(`warning: ${w}`);
24688
+ const avatarFailures2 = {};
24689
+ if (!readOnly && !dryRun) {
24690
+ for (const a of await syncPersonaAvatars(target, personaResult.agentPersonas, { userAgent: o.userAgent })) {
24691
+ const line = describeAvatarOutcome(a, PERSONA_NAME[a.role]);
24692
+ if (a.status === "failed") {
24693
+ o.warn(`warning: ${line}`);
24694
+ avatarFailures2[a.role] = a.detail ?? "unknown error";
24695
+ } else o.say(line);
24696
+ }
24697
+ }
24258
24698
  if (!dryRun) {
24259
24699
  const resolvedPath = resolvedPathFor(o.stateDir, target.route);
24260
- const raw = existsSync50(resolvedPath) ? JSON.parse(readFileSync46(resolvedPath, "utf8")) : {};
24700
+ const raw = existsSync52(resolvedPath) ? JSON.parse(readFileSync48(resolvedPath, "utf8")) : {};
24261
24701
  raw.agentPersonas = personaResult.agentPersonas;
24262
24702
  if (skillResult) raw.agentSkills = skillResult.agentSkills;
24703
+ if (!readOnly) raw.avatarSyncFailures = avatarFailures2;
24263
24704
  if (personaResult.releaseAgentId) raw.releaseAgentId = personaResult.releaseAgentId;
24264
- mkdirSync37(dirname30(resolvedPath), { recursive: true });
24265
- writeFileSync38(resolvedPath, `${JSON.stringify(raw, null, 2)}
24705
+ mkdirSync38(dirname31(resolvedPath), { recursive: true });
24706
+ writeFileSync39(resolvedPath, `${JSON.stringify(raw, null, 2)}
24266
24707
  `);
24267
24708
  if (target.resolved) {
24268
24709
  target.resolved.agentPersonas = personaResult.agentPersonas;
@@ -24399,7 +24840,7 @@ async function showLogEntry(route2, entryId, opts = {}) {
24399
24840
 
24400
24841
  // src/repos-check.ts
24401
24842
  import { spawnSync as spawnSync12 } from "child_process";
24402
- import { readFileSync as readFileSync47 } from "fs";
24843
+ import { readFileSync as readFileSync49 } from "fs";
24403
24844
  import { basename as basename11 } from "path";
24404
24845
  var POSIX_SHELL = /^(?:ba|z|da|k|a|mk)?sh$|^fish$/;
24405
24846
  function checkHookSyntax(script, shell) {
@@ -24440,7 +24881,7 @@ function checkRepoSpec(dir, opts = {}) {
24440
24881
  }
24441
24882
  let parsed;
24442
24883
  try {
24443
- parsed = parseRepoConfig(readFileSync47(file, "utf8"), file);
24884
+ parsed = parseRepoConfig(readFileSync49(file, "utf8"), file);
24444
24885
  } catch (e) {
24445
24886
  if (!(e instanceof RepoConfigError)) throw e;
24446
24887
  return { ...empty, file, error: e.message, exitCode: 1 };
@@ -24904,7 +25345,7 @@ ${run4.err}` });
24904
25345
  }
24905
25346
 
24906
25347
  // src/sample-ticket.ts
24907
- import { basename as basename12, dirname as dirname31, join as join51 } from "path";
25348
+ import { basename as basename12, dirname as dirname32, join as join53 } from "path";
24908
25349
  var SAMPLE_REPO = "crew-sample";
24909
25350
  var SAMPLE_REMOTE = `local/${SAMPLE_REPO}`;
24910
25351
  var SAMPLE_MARKER = "sample: true";
@@ -24927,8 +25368,8 @@ has something safe to work on: its test and build hooks always pass, it has no
24927
25368
  remote, and \`crew sample-ticket --remove\` deletes it.
24928
25369
  `;
24929
25370
  function sampleDir(existing, reposBase, workspace) {
24930
- if (existing.length > 0) return join51(dirname31(existing[0]), SAMPLE_REPO);
24931
- return join51(reposBase, workspace, SAMPLE_REPO);
25371
+ if (existing.length > 0) return join53(dirname32(existing[0]), SAMPLE_REPO);
25372
+ return join53(reposBase, workspace, SAMPLE_REPO);
24932
25373
  }
24933
25374
  var SAMPLE_TITLE = "Sample: add a documented `greet` function with a test";
24934
25375
  function sampleDescription() {
@@ -24972,8 +25413,8 @@ function planSampleTicket(i) {
24972
25413
  }
24973
25414
 
24974
25415
  // src/worktree-sweep.ts
24975
- import { existsSync as existsSync51, readFileSync as readFileSync48, readdirSync as readdirSync15 } from "fs";
24976
- import { basename as basename13, dirname as dirname32, join as join52, resolve as resolve5 } from "path";
25416
+ import { existsSync as existsSync53, readFileSync as readFileSync50, readdirSync as readdirSync15 } from "fs";
25417
+ import { basename as basename13, dirname as dirname33, join as join54, resolve as resolve5 } from "path";
24977
25418
  function planWorktreeSweep(target, tickets, contract) {
24978
25419
  const terminal = new Set(contract.statuses.resolved.filter((s) => s !== contract.statuses.verified));
24979
25420
  const verified = contract.statuses.verified;
@@ -25037,7 +25478,7 @@ function worktreeTicketNumbers(target) {
25037
25478
  return [...nums];
25038
25479
  }
25039
25480
  function siblingWorktreeDirs(target) {
25040
- const parent = dirname32(target.dir.replace(/[/\\]+$/, ""));
25481
+ const parent = dirname33(target.dir.replace(/[/\\]+$/, ""));
25041
25482
  const stem = `${basename13(target.dir.replace(/[/\\]+$/, ""))}-`;
25042
25483
  const registered = new Set(worktrees(target.dir).map((w) => resolve5(w.path)));
25043
25484
  let names;
@@ -25050,7 +25491,7 @@ function siblingWorktreeDirs(target) {
25050
25491
  for (const name of names) {
25051
25492
  if (!name.startsWith(stem)) continue;
25052
25493
  const m = DIR_NUMBER_SUFFIXED.exec(name);
25053
- const path = join52(parent, name);
25494
+ const path = join54(parent, name);
25054
25495
  if (m && !registered.has(resolve5(path))) out.push({ path, number: m[1] });
25055
25496
  }
25056
25497
  return out;
@@ -25085,7 +25526,7 @@ async function applyWorktreeSweep(cwd, actions, dryRun, log, remote = "origin",
25085
25526
  let removed = 0;
25086
25527
  let keptBranches = 0;
25087
25528
  for (const a of actions) {
25088
- if (!dryRun && base && !a.keepBranch && existsSync51(a.path) && isHandBackMerge(a.path, base)) {
25529
+ if (!dryRun && base && !a.keepBranch && existsSync53(a.path) && isHandBackMerge(a.path, base)) {
25089
25530
  if (gitOk(a.path, ["merge", "--abort"]) !== null) {
25090
25531
  log.emit(
25091
25532
  `abandoned the hand-back merge of ${base} in ${a.path}: ${a.ticket.issue_id} deployed without it`,
@@ -25093,7 +25534,7 @@ async function applyWorktreeSweep(cwd, actions, dryRun, log, remote = "origin",
25093
25534
  );
25094
25535
  }
25095
25536
  }
25096
- if (!dryRun && existsSync51(a.path)) {
25537
+ if (!dryRun && existsSync53(a.path)) {
25097
25538
  let dirty = false;
25098
25539
  try {
25099
25540
  dirty = status(a.path).length > 0;
@@ -25104,7 +25545,7 @@ async function applyWorktreeSweep(cwd, actions, dryRun, log, remote = "origin",
25104
25545
  continue;
25105
25546
  }
25106
25547
  }
25107
- if (!dryRun && a.requirePushed && a.branch && existsSync51(a.path) && remoteConfigured(cwd, remote) && worktreeHoldsUnpushed(a.path, remote)) {
25548
+ if (!dryRun && a.requirePushed && a.branch && existsSync53(a.path) && remoteConfigured(cwd, remote) && worktreeHoldsUnpushed(a.path, remote)) {
25108
25549
  refuse2(a, "unpushed commits", `${a.branch} has commits that are not on ${remote}`);
25109
25550
  continue;
25110
25551
  }
@@ -25153,7 +25594,7 @@ function isHandBackMerge(path, base) {
25153
25594
  if (!msgPath) return false;
25154
25595
  let first;
25155
25596
  try {
25156
- first = readFileSync48(resolve5(path, msgPath), "utf8").split("\n")[0] ?? "";
25597
+ first = readFileSync50(resolve5(path, msgPath), "utf8").split("\n")[0] ?? "";
25157
25598
  } catch {
25158
25599
  return false;
25159
25600
  }
@@ -25258,14 +25699,14 @@ function applyRemoteBranchCleanup(cwd, remote, branches2, dryRun, log) {
25258
25699
  }
25259
25700
 
25260
25701
  // src/stream-sweep.ts
25261
- import { existsSync as existsSync52, readdirSync as readdirSync16, rmSync as rmSync22, statSync as statSync15 } from "fs";
25262
- import { join as join53 } from "path";
25702
+ import { existsSync as existsSync54, readdirSync as readdirSync16, rmSync as rmSync23, statSync as statSync15 } from "fs";
25703
+ import { join as join55 } from "path";
25263
25704
  var DAY_MS2 = 24 * 60 * 60 * 1e3;
25264
25705
  function planStreamSweep(stateDir, retentionDays, now = Date.now()) {
25265
- const dir = join53(stateDir, "streams");
25266
- if (!existsSync52(dir)) return [];
25706
+ const dir = join55(stateDir, "streams");
25707
+ if (!existsSync54(dir)) return [];
25267
25708
  const cutoff = now - retentionDays * DAY_MS2;
25268
- return readdirSync16(dir).map((name) => join53(dir, name)).filter((path) => {
25709
+ return readdirSync16(dir).map((name) => join55(dir, name)).filter((path) => {
25269
25710
  try {
25270
25711
  return statSync15(path).mtimeMs < cutoff;
25271
25712
  } catch {
@@ -25281,7 +25722,7 @@ function applyStreamSweep(paths, dryRun, log) {
25281
25722
  continue;
25282
25723
  }
25283
25724
  try {
25284
- rmSync22(path, { force: true });
25725
+ rmSync23(path, { force: true });
25285
25726
  removed++;
25286
25727
  log.emit(`removed stream artifact ${path}`, { step: "worktree" });
25287
25728
  } catch (e) {
@@ -25291,9 +25732,9 @@ function applyStreamSweep(paths, dryRun, log) {
25291
25732
  return removed;
25292
25733
  }
25293
25734
  function planEventsSweep(stateDir, retentionDays, now = Date.now()) {
25294
- if (!existsSync52(stateDir)) return [];
25735
+ if (!existsSync54(stateDir)) return [];
25295
25736
  const cutoff = now - retentionDays * DAY_MS2;
25296
- return readdirSync16(stateDir).filter((name) => ROTATED_EVENTS_RE.test(name)).map((name) => join53(stateDir, name)).filter((path) => {
25737
+ return readdirSync16(stateDir).filter((name) => ROTATED_EVENTS_RE.test(name)).map((name) => join55(stateDir, name)).filter((path) => {
25297
25738
  try {
25298
25739
  return statSync15(path).mtimeMs < cutoff;
25299
25740
  } catch {
@@ -25303,7 +25744,7 @@ function planEventsSweep(stateDir, retentionDays, now = Date.now()) {
25303
25744
  }
25304
25745
 
25305
25746
  // src/cli.ts
25306
- 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";
25747
+ import { realpathSync as realpathSync3, readFileSync as readFileSync53, existsSync as existsSync58, 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";
25307
25748
  import { createInterface } from "readline/promises";
25308
25749
 
25309
25750
  // src/periscope-resume.ts
@@ -25530,8 +25971,8 @@ async function unregisterEndpoint(workspaceId, info, d) {
25530
25971
  import { createServer as createHttpServer } from "http";
25531
25972
  import { spawn as spawn9 } from "child_process";
25532
25973
  import { randomBytes as randomBytes2 } from "crypto";
25533
- import { existsSync as existsSync53, mkdirSync as mkdirSync38, readFileSync as readFileSync49, writeFileSync as writeFileSync39, unlinkSync as unlinkSync5, readdirSync as readdirSync17 } from "fs";
25534
- import { join as join54 } from "path";
25974
+ import { existsSync as existsSync55, mkdirSync as mkdirSync39, readFileSync as readFileSync51, writeFileSync as writeFileSync40, unlinkSync as unlinkSync5, readdirSync as readdirSync17 } from "fs";
25975
+ import { join as join56 } from "path";
25535
25976
 
25536
25977
  // src/secret-compare.ts
25537
25978
  import { timingSafeEqual } from "crypto";
@@ -25624,21 +26065,21 @@ var defaultSpawn2 = (cmd, args, env) => {
25624
26065
  return child;
25625
26066
  };
25626
26067
  function syncDaemonStatePath(stateDir, workspaceId) {
25627
- return join54(stateDir, "passengers", `${workspaceId}-sync.json`);
26068
+ return join56(stateDir, "passengers", `${workspaceId}-sync.json`);
25628
26069
  }
25629
26070
  function readPersistedSyncDaemon(stateDir, workspaceId) {
25630
26071
  const path = syncDaemonStatePath(stateDir, workspaceId);
25631
- if (!existsSync53(path)) return void 0;
26072
+ if (!existsSync55(path)) return void 0;
25632
26073
  try {
25633
- return JSON.parse(readFileSync49(path, "utf8"));
26074
+ return JSON.parse(readFileSync51(path, "utf8"));
25634
26075
  } catch {
25635
26076
  return void 0;
25636
26077
  }
25637
26078
  }
25638
26079
  function writePersistedSyncDaemon(stateDir, state) {
25639
26080
  const path = syncDaemonStatePath(stateDir, state.workspaceId);
25640
- mkdirSync38(join54(stateDir, "passengers"), { recursive: true });
25641
- writeFileSync39(path, `${JSON.stringify(state, null, 2)}
26081
+ mkdirSync39(join56(stateDir, "passengers"), { recursive: true });
26082
+ writeFileSync40(path, `${JSON.stringify(state, null, 2)}
25642
26083
  `);
25643
26084
  }
25644
26085
  function removePersistedSyncDaemon(stateDir, workspaceId) {
@@ -25658,8 +26099,8 @@ function waitForExit(pid, alive, timeoutMs = 5e3) {
25658
26099
  }
25659
26100
  }
25660
26101
  function readAllPersistedSyncWorkspaceIds(stateDir) {
25661
- const dir = join54(stateDir, "passengers");
25662
- if (!existsSync53(dir)) return [];
26102
+ const dir = join56(stateDir, "passengers");
26103
+ if (!existsSync55(dir)) return [];
25663
26104
  const suffix = "-sync.json";
25664
26105
  return readdirSync17(dir).filter((f) => f.endsWith(suffix)).map((f) => f.slice(0, -suffix.length));
25665
26106
  }
@@ -25717,12 +26158,12 @@ function syncPassengerSyncDaemons(plans, cfg, stateDir, deps = {}) {
25717
26158
 
25718
26159
  // src/periscope-proxy.ts
25719
26160
  import { spawn as spawn10 } from "child_process";
25720
- import { appendFileSync as appendFileSync3, mkdirSync as mkdirSync39 } from "fs";
26161
+ import { appendFileSync as appendFileSync3, mkdirSync as mkdirSync40 } from "fs";
25721
26162
  import { createServer, request as httpRequest } from "http";
25722
26163
  import { request as httpsRequest } from "https";
25723
26164
  import { connect as netConnect } from "net";
25724
26165
  import { connect as tlsConnect } from "tls";
25725
- import { dirname as dirname33, isAbsolute as isAbsolute4 } from "path";
26166
+ import { dirname as dirname34, isAbsolute as isAbsolute4 } from "path";
25726
26167
  import { brotliDecompressSync, gunzipSync, inflateSync } from "zlib";
25727
26168
 
25728
26169
  // src/periscope-inspector.ts
@@ -25836,7 +26277,7 @@ function parsePointedBody(raw) {
25836
26277
  return entry;
25837
26278
  }
25838
26279
  function appendPointed(file, entry, now = /* @__PURE__ */ new Date()) {
25839
- mkdirSync39(dirname33(file), { recursive: true });
26280
+ mkdirSync40(dirname34(file), { recursive: true });
25840
26281
  appendFileSync3(file, `${JSON.stringify({ ...entry, at: now.toISOString() })}
25841
26282
  `);
25842
26283
  }
@@ -26125,7 +26566,7 @@ async function startWorktreeIntel(d) {
26125
26566
  }
26126
26567
 
26127
26568
  // src/contract-refusal.ts
26128
- import { join as join55 } from "path";
26569
+ import { join as join57 } from "path";
26129
26570
  function contractFixers(dir, baseRef, tickets, locate) {
26130
26571
  const out = [];
26131
26572
  for (const t of tickets) {
@@ -26137,7 +26578,7 @@ function contractFixers(dir, baseRef, tickets, locate) {
26137
26578
  const text2 = gitOk(dir, ["show", `${branch}:${file}`]);
26138
26579
  if (text2 === null) continue;
26139
26580
  try {
26140
- parseRepoConfig(text2, join55(dir, file));
26581
+ parseRepoConfig(text2, join57(dir, file));
26141
26582
  } catch (e) {
26142
26583
  if (e instanceof RepoConfigError) continue;
26143
26584
  throw e;
@@ -26152,18 +26593,18 @@ import { createHash as createHash11 } from "crypto";
26152
26593
  import {
26153
26594
  chmodSync as chmodSync4,
26154
26595
  closeSync as closeSync6,
26155
- existsSync as existsSync54,
26596
+ existsSync as existsSync56,
26156
26597
  fstatSync,
26157
26598
  openSync as openSync6,
26158
26599
  readSync as readSync3,
26159
26600
  readdirSync as readdirSync18,
26160
- rmSync as rmSync23,
26601
+ rmSync as rmSync24,
26161
26602
  statSync as statSync16,
26162
26603
  watch
26163
26604
  } from "fs";
26164
26605
  import { createConnection } from "net";
26165
26606
  import { createServer as createServer2 } from "http";
26166
- import { basename as basename14, dirname as dirname34, join as join56 } from "path";
26607
+ import { basename as basename14, dirname as dirname35, join as join58 } from "path";
26167
26608
  import { execFile as execFile6, spawn as spawn12 } from "child_process";
26168
26609
 
26169
26610
  // src/periscope-control.ts
@@ -26400,7 +26841,7 @@ function runCrew(args, onLine, timeoutMs = 20 * 6e4) {
26400
26841
  // src/control-api.ts
26401
26842
  var PAUSABLE = ["dev", "design", "qa"];
26402
26843
  var CONTROL_SOCKET_NAME = "control.sock";
26403
- var controlSocketFor = (stateDir) => join56(stateDir, CONTROL_SOCKET_NAME);
26844
+ var controlSocketFor = (stateDir) => join58(stateDir, CONTROL_SOCKET_NAME);
26404
26845
  var MAX_SOCKET_PATH = 100;
26405
26846
  var MAX_TAIL_BYTES = 1024 * 1024;
26406
26847
  var MAX_WAIT_SECONDS = 30;
@@ -26487,7 +26928,7 @@ function candidates(live, rotated) {
26487
26928
  const out = [live];
26488
26929
  if (!rotated) return out;
26489
26930
  try {
26490
- for (const n of readdirSync18(dirname34(live))) if (ROTATED_EVENTS_RE.test(n)) out.push(join56(dirname34(live), n));
26931
+ for (const n of readdirSync18(dirname35(live))) if (ROTATED_EVENTS_RE.test(n)) out.push(join58(dirname35(live), n));
26491
26932
  } catch {
26492
26933
  }
26493
26934
  return out;
@@ -26531,7 +26972,7 @@ function lastLines2(path, n) {
26531
26972
  }
26532
26973
  function readTail(live, opts) {
26533
26974
  const max = opts.maxBytes ?? MAX_TAIL_BYTES;
26534
- if (!existsSync54(live)) {
26975
+ if (!existsSync56(live)) {
26535
26976
  return { lines: [], cursor: opts.after ?? encodeCursor({ dev: 0, ino: 0, off: 0 }), reset: false };
26536
26977
  }
26537
26978
  const cur = opts.after ? decodeCursor(opts.after) : null;
@@ -26647,7 +27088,7 @@ async function tailReply(path, q2, rotated, abort) {
26647
27088
  const deadline = Date.now() + Math.min(wait, MAX_WAIT_SECONDS) * 1e3;
26648
27089
  let r = readTail(path, { after, tail: tail3, rotated });
26649
27090
  while (after && !r.lines.length && !r.reset && Date.now() < deadline && !abort.aborted) {
26650
- await waitForChange(dirname34(path), deadline - Date.now(), abort);
27091
+ await waitForChange(dirname35(path), deadline - Date.now(), abort);
26651
27092
  r = readTail(path, { after: r.cursor, rotated });
26652
27093
  }
26653
27094
  return reply2(200, r);
@@ -26687,8 +27128,8 @@ async function route(deps, method, url, req, abort) {
26687
27128
  if (p.startsWith("/streams/") && get2) {
26688
27129
  const run4 = decodeURIComponent(p.slice("/streams/".length));
26689
27130
  if (!RUN_NAME_RE.test(run4) || run4.includes("..") || /\.(pid|meta\.json|events\.jsonl)$/.test(run4)) return err2(400, "not a run name");
26690
- const file = join56(deps.stateDir, "streams", run4.endsWith(".jsonl") ? run4 : `${run4}.jsonl`);
26691
- if (!existsSync54(file)) return err2(404, "no such run");
27131
+ const file = join58(deps.stateDir, "streams", run4.endsWith(".jsonl") ? run4 : `${run4}.jsonl`);
27132
+ if (!existsSync56(file)) return err2(404, "no such run");
26692
27133
  return tailReply(file, url.searchParams, false, abort);
26693
27134
  }
26694
27135
  if ((p === "/pause" || p === "/resume") && post3) {
@@ -26718,7 +27159,7 @@ async function route(deps, method, url, req, abort) {
26718
27159
  if (known.includes(p) || p.startsWith("/streams/") || sched) return err2(405, "method not allowed");
26719
27160
  return err2(404, "not found");
26720
27161
  }
26721
- function send(res, r) {
27162
+ function send2(res, r) {
26722
27163
  if (r.stream) {
26723
27164
  res.writeHead(200, { "Content-Type": "application/x-ndjson", "Cache-Control": "no-store" });
26724
27165
  return r.stream((ev) => {
@@ -26733,7 +27174,7 @@ function send(res, r) {
26733
27174
  res.end(body);
26734
27175
  }
26735
27176
  async function socketIsStale(path) {
26736
- if (!existsSync54(path)) return false;
27177
+ if (!existsSync56(path)) return false;
26737
27178
  return new Promise((resolve8) => {
26738
27179
  const c = createConnection(path);
26739
27180
  c.once("connect", () => {
@@ -26751,8 +27192,8 @@ async function startControlServer(deps) {
26751
27192
  log(`control API not started: socket path is too long for a unix socket (${path})`);
26752
27193
  return null;
26753
27194
  }
26754
- if (await socketIsStale(path)) rmSync23(path, { force: true });
26755
- else if (existsSync54(path)) {
27195
+ if (await socketIsStale(path)) rmSync24(path, { force: true });
27196
+ else if (existsSync56(path)) {
26756
27197
  log(`control API not started: ${path} is in use by another process`);
26757
27198
  return null;
26758
27199
  }
@@ -26763,21 +27204,21 @@ async function startControlServer(deps) {
26763
27204
  try {
26764
27205
  const mcp = /^\/periscopes\/([^/]+)\/mcp\/?$/.exec(new URL(req.url ?? "/", "http://ship").pathname);
26765
27206
  if (mcp) {
26766
- if (!deps.periscopeMcp) return send(res, err2(404, "not found"));
27207
+ if (!deps.periscopeMcp) return send2(res, err2(404, "not found"));
26767
27208
  return await deps.periscopeMcp(req, res, decodeURIComponent(mcp[1]));
26768
27209
  }
26769
27210
  if (isPeriscopePath(new URL(req.url ?? "/", "http://ship").pathname.replace(/\/+$/, "") || "/")) {
26770
- return await send(res, await route(deps, req.method ?? "GET", new URL(req.url ?? "/", "http://ship"), req, abort.signal));
27211
+ return await send2(res, await route(deps, req.method ?? "GET", new URL(req.url ?? "/", "http://ship"), req, abort.signal));
26771
27212
  }
26772
27213
  const m = /^Bearer (.+)$/.exec(req.headers.authorization ?? "");
26773
27214
  const verdict = await deps.auth.verify(m?.[1]?.trim() ?? "");
26774
- if (verdict === "unauthorized") return send(res, err2(401, "invalid or revoked key"));
26775
- if (verdict === "forbidden") return send(res, err2(403, "this key does not belong to a workspace this ship serves"));
26776
- if (verdict === "unavailable") return send(res, err2(503, "could not verify the key right now"));
26777
- await send(res, await route(deps, req.method ?? "GET", new URL(req.url ?? "/", "http://ship"), req, abort.signal));
27215
+ if (verdict === "unauthorized") return send2(res, err2(401, "invalid or revoked key"));
27216
+ if (verdict === "forbidden") return send2(res, err2(403, "this key does not belong to a workspace this ship serves"));
27217
+ if (verdict === "unavailable") return send2(res, err2(503, "could not verify the key right now"));
27218
+ await send2(res, await route(deps, req.method ?? "GET", new URL(req.url ?? "/", "http://ship"), req, abort.signal));
26778
27219
  } catch (e) {
26779
27220
  log(`control API request failed: ${e.message}`);
26780
- if (!res.headersSent) send(res, err2(500, "internal error"));
27221
+ if (!res.headersSent) send2(res, err2(500, "internal error"));
26781
27222
  else res.end();
26782
27223
  }
26783
27224
  })();
@@ -26798,7 +27239,7 @@ async function startControlServer(deps) {
26798
27239
  path,
26799
27240
  close: () => new Promise((done) => {
26800
27241
  server.close(() => {
26801
- rmSync23(path, { force: true });
27242
+ rmSync24(path, { force: true });
26802
27243
  done();
26803
27244
  });
26804
27245
  })
@@ -26838,57 +27279,57 @@ function crewJson(args, timeoutMs = 6e4) {
26838
27279
 
26839
27280
  // src/periscope-mcp.ts
26840
27281
  import { lstat, mkdir, readdir, readFile, readlink, realpath, rm, stat, writeFile } from "fs/promises";
26841
- import { basename as basename15, dirname as dirname35, isAbsolute as isAbsolute5, join as join58, relative as relative2, resolve as resolve6, sep } from "path";
27282
+ import { basename as basename15, dirname as dirname36, isAbsolute as isAbsolute5, join as join60, relative as relative2, resolve as resolve6, sep } from "path";
26842
27283
  import { z } from "zod";
26843
27284
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
26844
27285
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
26845
27286
 
26846
27287
  // src/periscope-endpoints.ts
26847
27288
  import { randomBytes as randomBytes3 } from "crypto";
26848
- import { chmodSync as chmodSync5, existsSync as existsSync55, mkdirSync as mkdirSync40, readdirSync as readdirSync19, readFileSync as readFileSync50, rmSync as rmSync24, writeFileSync as writeFileSync40 } from "fs";
26849
- import { join as join57 } from "path";
26850
- var secretDir = (stateDir) => join57(stateDir, "periscope-mcp");
26851
- var secretFile = (stateDir, id) => join57(secretDir(stateDir), `${id}.json`);
26852
- var endpointDir = (stateDir) => join57(stateDir, "periscope-endpoints");
26853
- var endpointFile = (stateDir, id) => join57(endpointDir(stateDir), `${id}.json`);
27289
+ import { chmodSync as chmodSync5, existsSync as existsSync57, mkdirSync as mkdirSync41, readdirSync as readdirSync19, readFileSync as readFileSync52, rmSync as rmSync25, writeFileSync as writeFileSync41 } from "fs";
27290
+ import { join as join59 } from "path";
27291
+ var secretDir = (stateDir) => join59(stateDir, "periscope-mcp");
27292
+ var secretFile = (stateDir, id) => join59(secretDir(stateDir), `${id}.json`);
27293
+ var endpointDir = (stateDir) => join59(stateDir, "periscope-endpoints");
27294
+ var endpointFile = (stateDir, id) => join59(endpointDir(stateDir), `${id}.json`);
26854
27295
  function mintPeriscopeSecret(stateDir, ticketRecordId) {
26855
- mkdirSync40(secretDir(stateDir), { recursive: true, mode: 448 });
27296
+ mkdirSync41(secretDir(stateDir), { recursive: true, mode: 448 });
26856
27297
  const secret = randomBytes3(32).toString("base64url");
26857
27298
  const file = secretFile(stateDir, ticketRecordId);
26858
- writeFileSync40(file, `${JSON.stringify({ secret })}
27299
+ writeFileSync41(file, `${JSON.stringify({ secret })}
26859
27300
  `, { mode: 384 });
26860
27301
  chmodSync5(file, 384);
26861
27302
  return secret;
26862
27303
  }
26863
27304
  function readPeriscopeSecret(stateDir, ticketRecordId) {
26864
27305
  try {
26865
- const v = JSON.parse(readFileSync50(secretFile(stateDir, ticketRecordId), "utf8"));
27306
+ const v = JSON.parse(readFileSync52(secretFile(stateDir, ticketRecordId), "utf8"));
26866
27307
  return typeof v.secret === "string" && v.secret ? v.secret : void 0;
26867
27308
  } catch {
26868
27309
  return void 0;
26869
27310
  }
26870
27311
  }
26871
27312
  function removePeriscopeSecret(stateDir, ticketRecordId) {
26872
- rmSync24(secretFile(stateDir, ticketRecordId), { force: true });
27313
+ rmSync25(secretFile(stateDir, ticketRecordId), { force: true });
26873
27314
  }
26874
27315
  function readPeriscopeEndpoint(stateDir, ticketRecordId) {
26875
27316
  try {
26876
- return JSON.parse(readFileSync50(endpointFile(stateDir, ticketRecordId), "utf8"));
27317
+ return JSON.parse(readFileSync52(endpointFile(stateDir, ticketRecordId), "utf8"));
26877
27318
  } catch {
26878
27319
  return void 0;
26879
27320
  }
26880
27321
  }
26881
27322
  function writePeriscopeEndpoint(stateDir, rec) {
26882
- mkdirSync40(endpointDir(stateDir), { recursive: true });
26883
- writeFileSync40(endpointFile(stateDir, rec.ticketRecordId), `${JSON.stringify(rec, null, 2)}
27323
+ mkdirSync41(endpointDir(stateDir), { recursive: true });
27324
+ writeFileSync41(endpointFile(stateDir, rec.ticketRecordId), `${JSON.stringify(rec, null, 2)}
26884
27325
  `);
26885
27326
  }
26886
27327
  function removePeriscopeEndpointRecord(stateDir, ticketRecordId) {
26887
- rmSync24(endpointFile(stateDir, ticketRecordId), { force: true });
27328
+ rmSync25(endpointFile(stateDir, ticketRecordId), { force: true });
26888
27329
  }
26889
27330
  function listPeriscopeEndpoints(stateDir) {
26890
27331
  const dir = endpointDir(stateDir);
26891
- if (!existsSync55(dir)) return [];
27332
+ if (!existsSync57(dir)) return [];
26892
27333
  const out = [];
26893
27334
  for (const name of readdirSync19(dir)) {
26894
27335
  if (!name.endsWith(".json")) continue;
@@ -26976,10 +27417,10 @@ async function realAncestor(p) {
26976
27417
  }
26977
27418
  if (isLink) {
26978
27419
  if (++hops > 40) throw new PathRefusal(`too many symbolic links resolving ${p}`);
26979
- cur = resolve6(dirname35(cur), await readlink(cur));
27420
+ cur = resolve6(dirname36(cur), await readlink(cur));
26980
27421
  continue;
26981
27422
  }
26982
- const parent = dirname35(cur);
27423
+ const parent = dirname36(cur);
26983
27424
  if (parent === cur) throw new PathRefusal(`cannot resolve ${p}`);
26984
27425
  tail3.push(basename15(cur));
26985
27426
  cur = parent;
@@ -26991,13 +27432,13 @@ async function resolveInWorktree(root, requested) {
26991
27432
  let abs;
26992
27433
  if (isAbsolute5(requested)) {
26993
27434
  abs = resolve6(requested);
26994
- if (isInside(root, abs)) abs = join58(realRoot, relative2(root, abs));
27435
+ if (isInside(root, abs)) abs = join60(realRoot, relative2(root, abs));
26995
27436
  } else {
26996
27437
  abs = resolve6(realRoot, requested);
26997
27438
  }
26998
27439
  if (!isInside(realRoot, abs)) throw new PathRefusal(`${requested} is outside this periscope's worktree`);
26999
27440
  const { real, rest } = await realAncestor(abs);
27000
- const final = rest ? join58(real, rest) : real;
27441
+ const final = rest ? join60(real, rest) : real;
27001
27442
  if (!isInside(realRoot, final)) throw new PathRefusal(`${requested} is outside this periscope's worktree`);
27002
27443
  if (relative2(realRoot, final).split(sep).includes(".git")) throw new PathRefusal(".git is not reachable from a periscope");
27003
27444
  return final;
@@ -27065,7 +27506,7 @@ function createPeriscopeMcpServer(d, sc) {
27065
27506
  const entries = (await readdir(abs, { withFileTypes: true })).filter((e) => e.name !== ".git");
27066
27507
  const lines2 = await Promise.all(entries.map(async (e) => {
27067
27508
  if (e.isDirectory()) return `[DIR] ${e.name}`;
27068
- const size = (await lstat(join58(abs, e.name))).size;
27509
+ const size = (await lstat(join60(abs, e.name))).size;
27069
27510
  return `[FILE] ${e.name} (${size} bytes)`;
27070
27511
  }));
27071
27512
  return text(lines2.join("\n") || "(empty)");
@@ -27090,7 +27531,7 @@ function createPeriscopeMcpServer(d, sc) {
27090
27531
  if (Buffer.byteLength(content) > MAX_WRITE_BYTES) return text(`content exceeds ${MAX_WRITE_BYTES} bytes`, true);
27091
27532
  const abs = await inTree(path);
27092
27533
  if (abs === await realpath(root)) return text("path must name a file", true);
27093
- await mkdir(dirname35(abs), { recursive: true });
27534
+ await mkdir(dirname36(abs), { recursive: true });
27094
27535
  await inTree(path);
27095
27536
  await writeFile(abs, content);
27096
27537
  return text(`Wrote ${Buffer.byteLength(content)} bytes to ${await rel(abs)}`);
@@ -27130,8 +27571,8 @@ function createPeriscopeMcpServer(d, sc) {
27130
27571
  inputSchema: { path: z.string() },
27131
27572
  annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: false }
27132
27573
  }, async ({ path }) => {
27133
- const parent = await inTree(dirname35(path) === "" ? "." : dirname35(path));
27134
- const abs = join58(parent, basename15(path));
27574
+ const parent = await inTree(dirname36(path) === "" ? "." : dirname36(path));
27575
+ const abs = join60(parent, basename15(path));
27135
27576
  if (basename15(path) === ".git" || abs === parent) return text("path must name a file", true);
27136
27577
  const st = await lstat(abs).catch(() => void 0);
27137
27578
  if (!st) return text(`${path} does not exist`, true);
@@ -27252,7 +27693,7 @@ function findPeriscope(sidecars, segment) {
27252
27693
  }
27253
27694
 
27254
27695
  // src/cli.ts
27255
- var CREW_HOME = isCompiledBinary(import.meta.url) ? dirname36(process.execPath) : resolve7(dirname36(fileURLToPath2(import.meta.url)), "..");
27696
+ var CREW_HOME = isCompiledBinary(import.meta.url) ? dirname37(process.execPath) : resolve7(dirname37(fileURLToPath2(import.meta.url)), "..");
27256
27697
  var RELEASE_LOCK_TTL_MS = 20 * 60 * 1e3;
27257
27698
  var CYCLE_SECONDS2 = 120;
27258
27699
  var STALE_CYCLES = 3;
@@ -27622,7 +28063,7 @@ if (command === "provision") {
27622
28063
  process.exit(outcome.code);
27623
28064
  }
27624
28065
  if (command === "pool-member") {
27625
- const pool = poolConfigFrom(argv, process.env, () => readFileSync51(0, "utf8"));
28066
+ const pool = poolConfigFrom(argv, process.env, () => readFileSync53(0, "utf8"));
27626
28067
  if (typeof pool === "string") {
27627
28068
  process.stderr.write(`crew pool-member: ${pool}
27628
28069
  `);
@@ -27943,7 +28384,7 @@ if (command === "passenger-sync-daemon") {
27943
28384
  } else {
27944
28385
  const toleratesNoRoutes = command === "credential" || command === "forge" || command === "repos" || command === "ship" || command === "disconnect" && flag("reset") || command === "deprovision" || command === "connect" && flag("sign-out");
27945
28386
  const configless = command === "connect" && flag("sign-out") || command === "disconnect" && flag("reset") || command === "deprovision";
27946
- if (configless && !existsSync56(findConfigFile(CREW_HOME))) {
28387
+ if (configless && !existsSync58(findConfigFile(CREW_HOME))) {
27947
28388
  cfg = loadConfig(CREW_HOME, firstRunConfigPath(), { text: "ship: {}\n", allowNoRoutes: true });
27948
28389
  } else {
27949
28390
  cfg = loadConfig(CREW_HOME, void 0, toleratesNoRoutes ? { allowNoRoutes: true } : {});
@@ -27966,7 +28407,7 @@ if (command === "passenger-sync-daemon") {
27966
28407
  throw e;
27967
28408
  }
27968
28409
  if (command === "credential") {
27969
- const r = runCredential(positional[1], readFileSync51(0, "utf8"), cfg.ship.forges, cfg.ship.stateDir, process.env, !flag("no-miss"));
28410
+ const r = runCredential(positional[1], readFileSync53(0, "utf8"), cfg.ship.forges, cfg.ship.stateDir, process.env, !flag("no-miss"));
27970
28411
  process.stdout.write(r.out);
27971
28412
  process.stderr.write(r.err);
27972
28413
  process.exit(r.code);
@@ -27978,9 +28419,9 @@ if (command === "passenger-sync-daemon") {
27978
28419
  forges: cfg.ship.forges,
27979
28420
  stateDir: cfg.ship.stateDir,
27980
28421
  configFile: cfg.configFile,
27981
- readFile: (p) => readFileSync51(p, "utf8"),
27982
- writeFile: (p, t) => writeFileSync41(p, t),
27983
- stdin: () => readFileSync51(0, "utf8"),
28422
+ readFile: (p) => readFileSync53(p, "utf8"),
28423
+ writeFile: (p, t) => writeFileSync42(p, t),
28424
+ stdin: () => readFileSync53(0, "utf8"),
27984
28425
  env: process.env
27985
28426
  }
27986
28427
  );
@@ -28314,8 +28755,8 @@ if (command === "passenger-sync-daemon") {
28314
28755
  }
28315
28756
  if (host === "linux" && hasSystemd) {
28316
28757
  const label = labelFor(CREW_HOME, "run");
28317
- const staleTimer = join59(homedir11(), ".config", "systemd", "user", `${label}.timer`);
28318
- if (existsSync56(staleTimer)) {
28758
+ const staleTimer = join61(homedir11(), ".config", "systemd", "user", `${label}.timer`);
28759
+ if (existsSync58(staleTimer)) {
28319
28760
  process.stdout.write(
28320
28761
  `removing stale run timer from before the persistent-service cutover: ${staleTimer}${dryRun ? " (dry run)" : ""}
28321
28762
  `
@@ -28344,7 +28785,7 @@ if (command === "passenger-sync-daemon") {
28344
28785
  const { settled: doctorRepos, errors: refusedRepos } = await settleRepos(reposOf(c), (t) => t.name, (t) => resolveOneRepo(c, t));
28345
28786
  for (const e of refusedRepos) problems.push(`repo ${e.repo}: ${e.detail}`);
28346
28787
  for (const r of doctorRepos) {
28347
- if (!existsSync56(r.dir)) problems.push(`repo ${r.name}: ${r.dir} is missing on disk`);
28788
+ if (!existsSync58(r.dir)) problems.push(`repo ${r.name}: ${r.dir} is missing on disk`);
28348
28789
  if (!satisfies(host, r.config.platform)) problems.push(`repo ${r.name}: requires ${r.config.platform}, this host is ${host}`);
28349
28790
  readiness.push(...validateEffective(r.config).map((p) => `repo ${r.name}: ${p}`));
28350
28791
  }
@@ -28379,7 +28820,7 @@ if (command === "passenger-sync-daemon") {
28379
28820
  }
28380
28821
  async function doctorFix(o) {
28381
28822
  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))));
28382
- const unitExists = (p) => existsSync56(p);
28823
+ const unitExists = (p) => existsSync58(p);
28383
28824
  const crontab = o.host === "linux" ? spawnSync13("crontab", ["-l"], { encoding: "utf8" }).stdout ?? "" : "";
28384
28825
  const schedulerAbsent = o.host !== "windows" ? !schedulerInstalled(planInstall(cfg.ship, CREW_HOME, o.host, detectSystemd(), "run", installContext()), unitExists, crontab) : true;
28385
28826
  const plan = planFix({ routes, schedulerAbsent, host: o.host });
@@ -28396,7 +28837,7 @@ if (command === "passenger-sync-daemon") {
28396
28837
  for (const a of plan.actions) {
28397
28838
  if (a.kind === "enable") {
28398
28839
  if (prompter && !await prompter.confirm(`Route ${a.route} passes every check \u2014 set enabled: true in ${cfg.configFile}?`, false)) continue;
28399
- writeFileSync41(cfg.configFile, planEnable(readFileSync51(cfg.configFile, "utf8"), a.route));
28840
+ writeFileSync42(cfg.configFile, planEnable(readFileSync53(cfg.configFile, "utf8"), a.route));
28400
28841
  enabledSound.add(a.route);
28401
28842
  changed2.push(`enabled route ${a.route} in ${cfg.configFile}`);
28402
28843
  } else {
@@ -28625,7 +29066,7 @@ ${changed2.map((c) => ` - ${c}
28625
29066
  harnessBin: "claude",
28626
29067
  ...contract.sandboxNetwork ? { extraHosts: contract.sandboxNetwork.hosts, toolchains: contract.sandboxNetwork.toolchains } : {}
28627
29068
  },
28628
- policyFile: join59(cfg.ship.stateDir, "release", `${target.name}.policy.yaml`),
29069
+ policyFile: join61(cfg.ship.stateDir, "release", `${target.name}.policy.yaml`),
28629
29070
  repo: mirror,
28630
29071
  origin: forgeDescriptorFor(forgeHost).httpsUrl(mirror.host, mirror.path),
28631
29072
  base: effective.branch.base,
@@ -29827,7 +30268,7 @@ ${cu.tail.trimEnd()}
29827
30268
  logFile: cfg.ship.logFile
29828
30269
  });
29829
30270
  }
29830
- const watchPaths = isCompiledBinary(import.meta.url) ? [process.execPath] : [join59(CREW_HOME, "src"), join59(CREW_HOME, "dist"), join59(CREW_HOME, "bin")];
30271
+ const watchPaths = isCompiledBinary(import.meta.url) ? [process.execPath] : [join61(CREW_HOME, "src"), join61(CREW_HOME, "dist"), join61(CREW_HOME, "bin")];
29831
30272
  const configPaths = daemonConfigPaths(cfg);
29832
30273
  watchPaths.push(...configPaths);
29833
30274
  noteDaemonStarted(cfg.ship.stateDir);
@@ -30145,10 +30586,10 @@ ${cu.tail.trimEnd()}
30145
30586
  `);
30146
30587
  if (!dryRun) {
30147
30588
  const resolvedPath = resolvedPathFor(cfg.ship.stateDir, target.route);
30148
- const raw = existsSync56(resolvedPath) ? JSON.parse(readFileSync51(resolvedPath, "utf8")) : {};
30589
+ const raw = existsSync58(resolvedPath) ? JSON.parse(readFileSync53(resolvedPath, "utf8")) : {};
30149
30590
  raw.agentSkills = result.agentSkills;
30150
- mkdirSync41(dirOf2(resolvedPath), { recursive: true });
30151
- writeFileSync41(resolvedPath, `${JSON.stringify(raw, null, 2)}
30591
+ mkdirSync42(dirOf2(resolvedPath), { recursive: true });
30592
+ writeFileSync42(resolvedPath, `${JSON.stringify(raw, null, 2)}
30152
30593
  `);
30153
30594
  }
30154
30595
  if (result.outcomes.some((o) => o.action === "diverged")) process.exitCode = 1;
@@ -30171,7 +30612,7 @@ ${cu.tail.trimEnd()}
30171
30612
  throw e;
30172
30613
  }
30173
30614
  const oldName = cfg.ship.name;
30174
- writeFileSync41(cfg.configFile, setShipNameInYaml(readFileSync51(cfg.configFile, "utf8"), newName));
30615
+ writeFileSync42(cfg.configFile, setShipNameInYaml(readFileSync53(cfg.configFile, "utf8"), newName));
30175
30616
  cfg.ship.name = newName;
30176
30617
  let renameMachineId;
30177
30618
  try {
@@ -30218,14 +30659,14 @@ ${cu.tail.trimEnd()}
30218
30659
  process.exit(2);
30219
30660
  };
30220
30661
  if (sub !== "add" && sub !== "list" && sub !== "clone" && sub !== "hooks" && sub !== "check") usage2();
30221
- const configText = readFileSync51(cfg.configFile, "utf8");
30662
+ const configText = readFileSync53(cfg.configFile, "utf8");
30222
30663
  if (sub === "check") {
30223
30664
  try {
30224
30665
  const routeArg = value("route") ?? positional[2];
30225
30666
  const found = cfg.routes.find((r) => r.route === routeArg);
30226
30667
  if (!found) throw new ReposError(`no route "${routeArg}" in the config (have: ${cfg.routes.map((r) => r.route).join(", ") || "none"})`);
30227
30668
  const named2 = value("route") ? void 0 : positional[3];
30228
- const dir = named2 ? repoDirOf(configText, dirname36(cfg.configFile), found.route, named2) : resolvePath(positional[value("route") ? 2 : 3] ?? ".");
30669
+ const dir = named2 ? repoDirOf(configText, dirname37(cfg.configFile), found.route, named2) : resolvePath(positional[value("route") ? 2 : 3] ?? ".");
30229
30670
  const target = reposOf(found).find((t) => resolvePath(t.dir) === dir || t.name === named2);
30230
30671
  const o = target ? found.repoOverrides[target.name] : void 0;
30231
30672
  runReposCheck(dir, {
@@ -30249,9 +30690,9 @@ ${cu.tail.trimEnd()}
30249
30690
  if (sub === "hooks") {
30250
30691
  try {
30251
30692
  const a = parseHooksArgs(positional.slice(2), routeNamesOf(configText));
30252
- const dir = repoDirOf(configText, dirname36(cfg.configFile), a.route, a.name);
30253
- if (!existsSync56(dir)) throw new ReposError(`${dir} does not exist on disk`);
30254
- const files = { exists: (r) => existsSync56(resolvePath(dir, r)), list: (r) => {
30693
+ const dir = repoDirOf(configText, dirname37(cfg.configFile), a.route, a.name);
30694
+ if (!existsSync58(dir)) throw new ReposError(`${dir} does not exist on disk`);
30695
+ const files = { exists: (r) => existsSync58(resolvePath(dir, r)), list: (r) => {
30255
30696
  try {
30256
30697
  return readdirSync20(resolvePath(dir, r));
30257
30698
  } catch {
@@ -30259,7 +30700,7 @@ ${cu.tail.trimEnd()}
30259
30700
  }
30260
30701
  }, read: (r) => {
30261
30702
  try {
30262
- return readFileSync51(resolvePath(dir, r), "utf8");
30703
+ return readFileSync53(resolvePath(dir, r), "utf8");
30263
30704
  } catch {
30264
30705
  return void 0;
30265
30706
  }
@@ -30301,19 +30742,19 @@ ${cu.tail.trimEnd()}
30301
30742
  let cleared;
30302
30743
  if (clear2) {
30303
30744
  const plan = clearRouteHooks(configText, a.route, a.name);
30304
- if (plan.removed.length > 0) writeFileSync41(cfg.configFile, plan.text);
30745
+ if (plan.removed.length > 0) writeFileSync42(cfg.configFile, plan.text);
30305
30746
  cleared = { file: cfg.configFile, removed: plan.removed };
30306
30747
  }
30307
30748
  if (write && suggestion.source === null && recipeIds.length === 0 && hookSpecs.length === 0) throw new ReposError(`nothing to write: ${suggestion.notes[0]}`);
30308
30749
  if (write === "route") {
30309
30750
  const plan = planRouteHooks(configText, a.route, a.name, picked.hooks, { replace: flag("replace") });
30310
- writeFileSync41(cfg.configFile, plan.text);
30751
+ writeFileSync42(cfg.configFile, plan.text);
30311
30752
  written = { target: "route", file: cfg.configFile, hooks: plan.written, kept: plan.kept, replaced: plan.replaced };
30312
30753
  } else if (write === "repo") {
30313
30754
  const have = existingRepoConfig(files);
30314
30755
  if (have) throw new ReposError(`${resolvePath(dir, have)} already exists; not overwriting it`);
30315
30756
  const file = resolvePath(dir, ".crew.yaml");
30316
- writeFileSync41(file, starterRepoConfig(picked.hooks, picked.release), { flag: "wx" });
30757
+ writeFileSync42(file, starterRepoConfig(picked.hooks, picked.release), { flag: "wx" });
30317
30758
  written = { target: "repo", file, hooks: Object.keys(picked.hooks), kept: [], replaced: [] };
30318
30759
  }
30319
30760
  if (flag("json")) {
@@ -30369,7 +30810,7 @@ ${cu.tail.trimEnd()}
30369
30810
  if (sub === "list" && !routeName) usage2();
30370
30811
  if (sub === "add") {
30371
30812
  try {
30372
- const a = parseAddArgs(positional.slice(2), routeNamesOf(configText), (p) => existsSync56(resolvePath(p.replace(/^~(?=\/|$)/, homedir11()))));
30813
+ const a = parseAddArgs(positional.slice(2), routeNamesOf(configText), (p) => existsSync58(resolvePath(p.replace(/^~(?=\/|$)/, homedir11()))));
30373
30814
  routeName = a.route;
30374
30815
  addPath = a.path;
30375
30816
  addName = a.name;
@@ -30399,7 +30840,7 @@ ${cu.tail.trimEnd()}
30399
30840
  const resolvedFile = resolvedPathFor(cfg.ship.stateDir, routeName);
30400
30841
  if (sub === "list" || sub === "add") {
30401
30842
  const liveRoute = cfg.routes.find((r) => r.route === routeName);
30402
- if (liveRoute?.resolved?.reposModelId && existsSync56(resolvedFile) && !dryRun) {
30843
+ if (liveRoute?.resolved?.reposModelId && existsSync58(resolvedFile) && !dryRun) {
30403
30844
  try {
30404
30845
  await hydrateApiKeys([liveRoute]);
30405
30846
  persistRepoRows(cfg.ship.stateDir, liveRoute.route, await new Tracker(liveRoute, cfg.ship).repoRowsForMap());
@@ -30408,16 +30849,16 @@ ${cu.tail.trimEnd()}
30408
30849
  }
30409
30850
  }
30410
30851
  let resolvedRemotes;
30411
- if (existsSync56(resolvedFile)) {
30852
+ if (existsSync58(resolvedFile)) {
30412
30853
  try {
30413
- resolvedRemotes = JSON.parse(readFileSync51(resolvedFile, "utf8"));
30854
+ resolvedRemotes = JSON.parse(readFileSync53(resolvedFile, "utf8"));
30414
30855
  } catch {
30415
30856
  }
30416
30857
  }
30417
30858
  const originOf = (dir) => gitOk(dir, ["remote", "get-url", "origin"]) ?? void 0;
30418
30859
  const text2 = configText;
30419
- const base = dirname36(cfg.configFile);
30420
- const isCheckout = (d) => existsSync56(`${d}/.git`);
30860
+ const base = dirname37(cfg.configFile);
30861
+ const isCheckout = (d) => existsSync58(`${d}/.git`);
30421
30862
  try {
30422
30863
  if (sub === "list") {
30423
30864
  if (flag("json")) {
@@ -30427,12 +30868,12 @@ ${cu.tail.trimEnd()}
30427
30868
  base,
30428
30869
  resolved: resolvedRemotes,
30429
30870
  originOf,
30430
- exists: (d) => existsSync56(d),
30871
+ exists: (d) => existsSync58(d),
30431
30872
  isCheckout,
30432
30873
  repoHasHooks: (d) => REPO_CONFIG_FILENAMES.some((f) => {
30433
30874
  try {
30434
30875
  const path = resolvePath(d, f);
30435
- return Object.keys(parseRepoConfig(readFileSync51(path, "utf8"), path).hooks).length > 0;
30876
+ return Object.keys(parseRepoConfig(readFileSync53(path, "utf8"), path).hooks).length > 0;
30436
30877
  } catch {
30437
30878
  return false;
30438
30879
  }
@@ -30449,7 +30890,7 @@ ${cu.tail.trimEnd()}
30449
30890
  for (const r of repos) {
30450
30891
  const origin2 = originOf(r.dir);
30451
30892
  const row = matchRepoName(origin2, resolvedRemotes);
30452
- const note = !existsSync56(r.dir) ? "missing on disk" : row ? `Repos row: ${row}` : `no Repos row matches ${normalizeRemote(origin2) ?? "this checkout (no origin remote)"}`;
30893
+ const note = !existsSync58(r.dir) ? "missing on disk" : row ? `Repos row: ${row}` : `no Repos row matches ${normalizeRemote2(origin2) ?? "this checkout (no origin remote)"}`;
30453
30894
  process.stdout.write(`${r.name} ${r.dir} ${note}
30454
30895
  `);
30455
30896
  }
@@ -30461,9 +30902,9 @@ ${cu.tail.trimEnd()}
30461
30902
  ` : `${human}
30462
30903
  `);
30463
30904
  const plan2 = planRepoClone({ text: text2, base, route: routeName, name: addName, resolved: resolvedRemotes, dir: value("dir"), isCheckout });
30464
- if (existsSync56(plan2.target) && (existsSync56(`${plan2.target}/.git`) || readdirSync20(plan2.target).length > 0)) {
30905
+ if (existsSync58(plan2.target) && (existsSync58(`${plan2.target}/.git`) || readdirSync20(plan2.target).length > 0)) {
30465
30906
  throw new ReposError(
30466
- 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`
30907
+ existsSync58(`${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`
30467
30908
  );
30468
30909
  }
30469
30910
  if (dryRun) {
@@ -30481,14 +30922,14 @@ ${cu.tail.trimEnd()}
30481
30922
  throw new ReposError(`${e.message}${authHint}
30482
30923
  crew.yaml was not changed`);
30483
30924
  }
30484
- writeFileSync41(cfg.configFile, plan2.text);
30925
+ writeFileSync42(cfg.configFile, plan2.text);
30485
30926
  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:
30486
30927
  `);
30487
30928
  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}`);
30488
30929
  break;
30489
30930
  }
30490
30931
  const target = resolvePath(addPath.replace(/^~(?=\/|$)/, homedir11()));
30491
- const top = existsSync56(target) ? gitOk(target, ["rev-parse", "--show-toplevel"]) : null;
30932
+ const top = existsSync58(target) ? gitOk(target, ["rev-parse", "--show-toplevel"]) : null;
30492
30933
  if (!top) throw new ReposError(`${target} is not a git checkout`);
30493
30934
  const origin = originOf(top);
30494
30935
  const plan = planRepoAdd({
@@ -30540,15 +30981,15 @@ ${cu.tail.trimEnd()}
30540
30981
  const created = await rowTracker.createRepoRow(rowPayload);
30541
30982
  process.stdout.write(`created Repos row ${String(rowPayload.name)} (${String(rowPayload.remote)}) ${created.id}
30542
30983
  `);
30543
- if (existsSync56(resolvedFile)) {
30544
- const raw = JSON.parse(readFileSync51(resolvedFile, "utf8"));
30984
+ if (existsSync58(resolvedFile)) {
30985
+ const raw = JSON.parse(readFileSync53(resolvedFile, "utf8"));
30545
30986
  raw.repoNames = { ...raw.repoNames, [created.id]: String(rowPayload.name) };
30546
30987
  raw.repoRemotes = { ...raw.repoRemotes, [created.id]: String(rowPayload.remote) };
30547
- writeFileSync41(resolvedFile, `${JSON.stringify(raw, null, 2)}
30988
+ writeFileSync42(resolvedFile, `${JSON.stringify(raw, null, 2)}
30548
30989
  `);
30549
30990
  }
30550
30991
  }
30551
- writeFileSync41(cfg.configFile, plan.text);
30992
+ writeFileSync42(cfg.configFile, plan.text);
30552
30993
  process.stdout.write(`added ${top} to ${routeName} as ${plan.mode === "dir" ? "dir" : `repos.${plan.name}`} in ${cfg.configFile}
30553
30994
  `);
30554
30995
  } catch (e) {
@@ -30923,7 +31364,7 @@ Signed in as ${result.identity.email} \u2014 minted an API key in workspace "${r
30923
31364
  process.exit(2);
30924
31365
  }
30925
31366
  if (found.shipNameAdopted && !dryRun) {
30926
- writeFileSync41(cfg.configFile, setShipNameInYaml(readFileSync51(cfg.configFile, "utf8"), found.shipNameAdopted));
31367
+ writeFileSync42(cfg.configFile, setShipNameInYaml(readFileSync53(cfg.configFile, "utf8"), found.shipNameAdopted));
30927
31368
  cfg.ship.name = found.shipNameAdopted;
30928
31369
  }
30929
31370
  if (found.shipRow) {
@@ -30966,10 +31407,10 @@ Signed in as ${result.identity.email} \u2014 minted an API key in workspace "${r
30966
31407
  }
30967
31408
  }
30968
31409
  let previous;
30969
- const hadPreviousFile = existsSync56(resolvedPath);
31410
+ const hadPreviousFile = existsSync58(resolvedPath);
30970
31411
  if (hadPreviousFile) {
30971
31412
  try {
30972
- previous = JSON.parse(readFileSync51(resolvedPath, "utf8"));
31413
+ previous = JSON.parse(readFileSync53(resolvedPath, "utf8"));
30973
31414
  } catch {
30974
31415
  }
30975
31416
  }
@@ -31099,12 +31540,12 @@ Signed in as ${result.identity.email} \u2014 minted an API key in workspace "${r
31099
31540
  process.stderr.write(`(dry run) would write resolved ids to ${resolvedPath}
31100
31541
  `);
31101
31542
  } else {
31102
- mkdirSync41(dirname36(resolvedPath), { recursive: true });
31543
+ mkdirSync42(dirname37(resolvedPath), { recursive: true });
31103
31544
  if (hadPreviousFile) copyFileSync2(resolvedPath, `${resolvedPath}.bak`);
31104
31545
  const tmpPath = `${resolvedPath}.tmp${process.pid}`;
31105
- writeFileSync41(tmpPath, `${JSON.stringify(resolved, null, 2)}
31546
+ writeFileSync42(tmpPath, `${JSON.stringify(resolved, null, 2)}
31106
31547
  `);
31107
- renameSync7(tmpPath, resolvedPath);
31548
+ renameSync8(tmpPath, resolvedPath);
31108
31549
  process.stderr.write(`Resolved ids written to ${resolvedPath}
31109
31550
  `);
31110
31551
  }
@@ -31148,8 +31589,8 @@ Signed in as ${result.identity.email} \u2014 minted an API key in workspace "${r
31148
31589
  process.stderr.write(`(dry run) would write the minted API key to ${apiKeyFile}
31149
31590
  `);
31150
31591
  } else {
31151
- mkdirSync41(dirname36(apiKeyFile), { recursive: true });
31152
- writeFileSync41(apiKeyFile, `${apiKeyVar}=${apiKey}
31592
+ mkdirSync42(dirname37(apiKeyFile), { recursive: true });
31593
+ writeFileSync42(apiKeyFile, `${apiKeyVar}=${apiKey}
31153
31594
  `, { mode: 384 });
31154
31595
  process.stderr.write(`API key written to ${apiKeyFile}
31155
31596
  `);
@@ -31864,10 +32305,10 @@ Signed in as ${result.identity.email} \u2014 minted an API key in workspace "${r
31864
32305
  startupSeconds: cfg.ship.intelStartupSeconds,
31865
32306
  prepare: async (path) => {
31866
32307
  for (const f of repoWt.config.worktrees.copy) {
31867
- const src = join59(repoWt.dir, f);
31868
- if (!existsSync56(src) || existsSync56(join59(path, f))) continue;
31869
- mkdirSync41(dirOf2(join59(path, f)), { recursive: true });
31870
- copyFileSync2(src, join59(path, f));
32308
+ const src = join61(repoWt.dir, f);
32309
+ if (!existsSync58(src) || existsSync58(join61(path, f))) continue;
32310
+ mkdirSync42(dirOf2(join61(path, f)), { recursive: true });
32311
+ copyFileSync2(src, join61(path, f));
31871
32312
  }
31872
32313
  const setup = repoWt.config.hooks.setup;
31873
32314
  return setup ? runScript(setup, { cwd: path, shell: shellWt }) : null;
@@ -32093,7 +32534,7 @@ Signed in as ${result.identity.email} \u2014 minted an API key in workspace "${r
32093
32534
  const shellR = hit && resolveShell(hit.repo.config.shell ?? cfg.ship.shell);
32094
32535
  const resumed = await runPeriscopeResume({
32095
32536
  find: async () => hit && { row: hit.row, tag: hit.tag },
32096
- worktreeExists: (p) => existsSync56(p),
32537
+ worktreeExists: (p) => existsSync58(p),
32097
32538
  prepareDropFile,
32098
32539
  startProxy: (wt, url, n) => launchProxy(crewInvocation(CREW_HOME), wt, url, Number(n), { host: hit.row.host || "localhost", inject: hit.repo.config.periscope?.inspector !== "repo" }),
32099
32540
  relay: hit && previewRelayFor(hit.route) && {
@@ -32196,10 +32637,10 @@ ${where.join("\n")}`);
32196
32637
  },
32197
32638
  prepare: async (path) => {
32198
32639
  for (const f of repoP.config.worktrees.copy) {
32199
- const src = join59(repoP.dir, f);
32200
- if (!existsSync56(src)) continue;
32201
- mkdirSync41(dirOf2(join59(path, f)), { recursive: true });
32202
- copyFileSync2(src, join59(path, f));
32640
+ const src = join61(repoP.dir, f);
32641
+ if (!existsSync58(src)) continue;
32642
+ mkdirSync42(dirOf2(join61(path, f)), { recursive: true });
32643
+ copyFileSync2(src, join61(path, f));
32203
32644
  }
32204
32645
  const setup = repoP.config.hooks.setup;
32205
32646
  return setup ? runScript(setup, { cwd: path, shell: shellP, onLine: (l) => {
@@ -32511,7 +32952,7 @@ ${where.join("\n")}`);
32511
32952
  };
32512
32953
  const droppedRoutes = [];
32513
32954
  try {
32514
- const rawCfg = parseYaml3(readFileSync51(cfg.configFile, "utf8"));
32955
+ const rawCfg = parseYaml3(readFileSync53(cfg.configFile, "utf8"));
32515
32956
  for (const r of rawCfg?.routes ?? []) {
32516
32957
  if (typeof r?.route !== "string" || cfg.routes.some((x) => x.route === r.route)) continue;
32517
32958
  try {
@@ -32575,8 +33016,8 @@ ${where.join("\n")}`);
32575
33016
  process.stdout.write("crew reload: no daemon unit is running \u2014 nothing to reload (the next run reads crew.yaml fresh)\n");
32576
33017
  break;
32577
33018
  }
32578
- mkdirSync41(cfg.ship.stateDir, { recursive: true });
32579
- writeFileSync41(sentinel, `${(/* @__PURE__ */ new Date()).toISOString()}
33019
+ mkdirSync42(cfg.ship.stateDir, { recursive: true });
33020
+ writeFileSync42(sentinel, `${(/* @__PURE__ */ new Date()).toISOString()}
32580
33021
  `);
32581
33022
  process.stdout.write(
32582
33023
  "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"
@@ -32641,7 +33082,7 @@ ${where.join("\n")}`);
32641
33082
  }
32642
33083
  case "log": {
32643
33084
  try {
32644
- const text2 = readFileSync51(cfg.ship.logFile, "utf8").split("\n");
33085
+ const text2 = readFileSync53(cfg.ship.logFile, "utf8").split("\n");
32645
33086
  process.stdout.write(`${text2.slice(-(Number(value("tail")) || 40)).join("\n")}
32646
33087
  `);
32647
33088
  } catch {
@@ -32664,8 +33105,8 @@ ${where.join("\n")}`);
32664
33105
  };
32665
33106
  if (!route2.resolved) fail2(`route ${route2.route} is not connected \u2014 run \`crew connect\` first`);
32666
33107
  const tracker = new Tracker(route2, cfg.ship);
32667
- const configText = readFileSync51(cfg.configFile, "utf8");
32668
- const cfgBase = dirname36(cfg.configFile);
33108
+ const configText = readFileSync53(cfg.configFile, "utf8");
33109
+ const cfgBase = dirname37(cfg.configFile);
32669
33110
  const configured2 = configuredRepos(configText, route2.route, cfgBase);
32670
33111
  const dir = configured2.find((r) => r.name === SAMPLE_REPO)?.dir ?? sampleDir(configured2.map((r) => r.dir), route2.reposBasePath, route2.route.split("/")[0]);
32671
33112
  const resolvedFile = resolvedPathFor(cfg.ship.stateDir, route2.route);
@@ -32693,7 +33134,7 @@ ${where.join("\n")}`);
32693
33134
  }
32694
33135
  if (configured2.some((r) => r.dir === dir)) {
32695
33136
  try {
32696
- writeFileSync41(cfg.configFile, planRepoRemove(configText, cfgBase, route2.route, dir).text);
33137
+ writeFileSync42(cfg.configFile, planRepoRemove(configText, cfgBase, route2.route, dir).text);
32697
33138
  } catch (e) {
32698
33139
  if (e instanceof ReposError) fail2(e.message);
32699
33140
  throw e;
@@ -32701,29 +33142,29 @@ ${where.join("\n")}`);
32701
33142
  }
32702
33143
  if (row) {
32703
33144
  await tracker.deleteRepoRow(row.id);
32704
- if (existsSync56(resolvedFile)) {
32705
- const raw = JSON.parse(readFileSync51(resolvedFile, "utf8"));
33145
+ if (existsSync58(resolvedFile)) {
33146
+ const raw = JSON.parse(readFileSync53(resolvedFile, "utf8"));
32706
33147
  if (raw.repoNames) delete raw.repoNames[row.id];
32707
33148
  if (raw.repoRemotes) delete raw.repoRemotes[row.id];
32708
- writeFileSync41(resolvedFile, `${JSON.stringify(raw, null, 2)}
33149
+ writeFileSync42(resolvedFile, `${JSON.stringify(raw, null, 2)}
32709
33150
  `);
32710
33151
  }
32711
33152
  }
32712
- if (existsSync56(join59(dir, ".git")) && basename16(dir) === SAMPLE_REPO) rmSync25(dir, { recursive: true, force: true });
33153
+ if (existsSync58(join61(dir, ".git")) && basename16(dir) === SAMPLE_REPO) rmSync26(dir, { recursive: true, force: true });
32713
33154
  say("removed", { dir, closed }, `removed the sample repo${closed.length ? `, closed ${closed.join(", ")}` : ""}`);
32714
33155
  break;
32715
33156
  }
32716
33157
  const projectId = route2.resolved.areaId ?? resolveRepoProject(await tracker.projectRows(), value("project"));
32717
- const fresh = !existsSync56(join59(dir, ".git"));
32718
- if (existsSync56(dir) && fresh && readdirSync20(dir).length > 0) fail2(`${dir} exists and is not a git checkout \u2014 move it aside`);
33158
+ const fresh = !existsSync58(join61(dir, ".git"));
33159
+ if (existsSync58(dir) && fresh && readdirSync20(dir).length > 0) fail2(`${dir} exists and is not a git checkout \u2014 move it aside`);
32719
33160
  if (dryRun) {
32720
33161
  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`);
32721
33162
  break;
32722
33163
  }
32723
33164
  if (fresh) {
32724
- mkdirSync41(dir, { recursive: true });
32725
- writeFileSync41(join59(dir, "README.md"), SAMPLE_README);
32726
- writeFileSync41(join59(dir, ".crew.yaml"), SAMPLE_CREW_YAML);
33165
+ mkdirSync42(dir, { recursive: true });
33166
+ writeFileSync42(join61(dir, "README.md"), SAMPLE_README);
33167
+ writeFileSync42(join61(dir, ".crew.yaml"), SAMPLE_CREW_YAML);
32727
33168
  const g = (...a) => {
32728
33169
  const r = spawnSync13("git", a, { cwd: dir, encoding: "utf8" });
32729
33170
  if (r.status !== 0) fail2(`git ${a[0]} failed in ${dir}: ${(r.stderr || r.stdout).trim()}`);
@@ -32741,17 +33182,17 @@ ${where.join("\n")}`);
32741
33182
  spec: { platform: "unix", releaseMode: "integrate", ciProvider: "none" }
32742
33183
  });
32743
33184
  repoId = (await tracker.createRepoRow(payload)).id;
32744
- if (existsSync56(resolvedFile)) {
32745
- const raw = JSON.parse(readFileSync51(resolvedFile, "utf8"));
33185
+ if (existsSync58(resolvedFile)) {
33186
+ const raw = JSON.parse(readFileSync53(resolvedFile, "utf8"));
32746
33187
  raw.repoNames = { ...raw.repoNames, [repoId]: SAMPLE_REPO };
32747
33188
  raw.repoRemotes = { ...raw.repoRemotes, [repoId]: SAMPLE_REMOTE };
32748
- writeFileSync41(resolvedFile, `${JSON.stringify(raw, null, 2)}
33189
+ writeFileSync42(resolvedFile, `${JSON.stringify(raw, null, 2)}
32749
33190
  `);
32750
33191
  }
32751
33192
  }
32752
33193
  if (!configured2.some((r) => r.dir === dir)) {
32753
33194
  try {
32754
- writeFileSync41(cfg.configFile, planRepoAdd({ text: configText, base: cfgBase, route: route2.route, path: dir, name: SAMPLE_REPO }).text);
33195
+ writeFileSync42(cfg.configFile, planRepoAdd({ text: configText, base: cfgBase, route: route2.route, path: dir, name: SAMPLE_REPO }).text);
32755
33196
  } catch (e) {
32756
33197
  if (e instanceof ReposError) fail2(e.message);
32757
33198
  throw e;
@@ -32940,6 +33381,8 @@ ${where.join("\n")}`);
32940
33381
  model: x.model
32941
33382
  })),
32942
33383
  stateDir: cfg.ship.stateDir,
33384
+ // CREW-3084: how many repositories carry environment; never their names or values.
33385
+ repositoriesWithEnv: repositoryEnvCount(cfg.ship.stateDir),
32943
33386
  logFile: cfg.ship.logFile,
32944
33387
  eventFile: eventFileFor(cfg.ship.stateDir),
32945
33388
  // Additive (CREW-1373): open ship-level items, including the
@@ -33118,7 +33561,7 @@ watermark: ${state.watermark(routeSlug(route2.route))}
33118
33561
  plan,
33119
33562
  label,
33120
33563
  uid: process.getuid?.() ?? 0,
33121
- system: plan.mechanism === "systemd" && existsSync56(systemUnitPathFor(label)),
33564
+ system: plan.mechanism === "systemd" && existsSync58(systemUnitPathFor(label)),
33122
33565
  stamp: readDaemonStamp(cfg.ship.stateDir)
33123
33566
  });
33124
33567
  })();
@@ -33134,7 +33577,7 @@ watermark: ${state.watermark(routeSlug(route2.route))}
33134
33577
  }
33135
33578
  for (const r of repos) {
33136
33579
  const remote = r.config.branch.remote;
33137
- if (existsSync56(r.dir)) {
33580
+ if (existsSync58(r.dir)) {
33138
33581
  pushAuth.push({
33139
33582
  route: c.route,
33140
33583
  repo: r.name,
@@ -33211,12 +33654,13 @@ watermark: ${state.watermark(routeSlug(route2.route))}
33211
33654
  }
33212
33655
  }
33213
33656
  for (const message of roleCapWarnings(cfg.ship)) problems.push({ severity: "note", kind: "role_cap_above_ship_cap", message });
33657
+ for (const f of routeAvatarFailures(cfg.ship.stateDir, route2.route)) problems.push({ severity: "note", kind: "persona_avatar_upload_failed", route: route2.route, message: `${f.role} persona avatar failed to upload: ${f.detail}`, remedy: "run `crew agents sync` again" });
33214
33658
  if (daemonLiveness) {
33215
33659
  const dp = daemonProblem(daemonLiveness, route2.route);
33216
33660
  if (dp) problems.push(dp);
33217
33661
  else passed++;
33218
33662
  }
33219
- const runtimeDir = runtimeDirWarning(process.platform, process.getuid?.() ?? null, existsSync56, userInfo2().username);
33663
+ const runtimeDir = runtimeDirWarning(process.platform, process.getuid?.() ?? null, existsSync58, userInfo2().username);
33220
33664
  if (runtimeDir) problems.push({ severity: "attention", kind: "runtime_dir_missing", message: runtimeDir });
33221
33665
  if (!flag("offline")) {
33222
33666
  const shipKind = await doctorShipKind(route2, cfg.ship);
@@ -33263,6 +33707,8 @@ routes: ${cfg.routes.map((c) => c.route).join(", ")}
33263
33707
  `
33264
33708
  );
33265
33709
  for (const w of roleCapWarnings(cfg.ship)) process.stdout.write(`role concurrency: WARN ${w}
33710
+ `);
33711
+ for (const r of cfg.routes) for (const f of routeAvatarFailures(cfg.ship.stateDir, r.route)) process.stdout.write(`persona avatar: WARN ${r.route}: ${f.role} avatar failed to upload (${f.detail}); run \`crew agents sync\` again
33266
33712
  `);
33267
33713
  for (const t of rejectedTunnels(cfg.ship.stateDir)) process.stdout.write(`relay tunnel: ATTENTION ${tunnelRejectedMessage(t.workspaceId, t.quickExits)}
33268
33714
  `);
@@ -33281,7 +33727,7 @@ routes: ${cfg.routes.map((c) => c.route).join(", ")}
33281
33727
  }
33282
33728
  try {
33283
33729
  const evFile = eventFileFor(cfg.ship.stateDir);
33284
- const evSize = existsSync56(evFile) ? statSync17(evFile).size : 0;
33730
+ const evSize = existsSync58(evFile) ? statSync17(evFile).size : 0;
33285
33731
  process.stdout.write(
33286
33732
  evSize > cfg.ship.eventsRotateBytes * 4 ? `events log: WARN ${evFile} is ${Math.round(evSize / 1048576)} MB (> 4x eventsRotateBytes); run \`crew reap\` to rotate it
33287
33733
  ` : "events log: ok\n"
@@ -33292,7 +33738,7 @@ routes: ${cfg.routes.map((c) => c.route).join(", ")}
33292
33738
  const unitPlan = planInstall(cfg.ship, CREW_HOME, host, detectSystemd(), "run", installContext());
33293
33739
  const abandons = unitAbandonsAgents(unitPlan, (p) => {
33294
33740
  try {
33295
- return readFileSync51(p, "utf8");
33741
+ return readFileSync53(p, "utf8");
33296
33742
  } catch {
33297
33743
  return null;
33298
33744
  }
@@ -33307,7 +33753,7 @@ routes: ${cfg.routes.map((c) => c.route).join(", ")}
33307
33753
  const pPlan = planInstall(cfg.ship, CREW_HOME, host, true, "passengers", installContext());
33308
33754
  const keeps = unitAbandonsAgents(pPlan, (p) => {
33309
33755
  try {
33310
- return readFileSync51(p, "utf8");
33756
+ return readFileSync53(p, "utf8");
33311
33757
  } catch {
33312
33758
  return null;
33313
33759
  }
@@ -33321,7 +33767,7 @@ routes: ${cfg.routes.map((c) => c.route).join(", ")}
33321
33767
  if (host === "linux" && detectSystemd()) {
33322
33768
  const ctl = planDaemonControl(CREW_HOME, host, true);
33323
33769
  const unitPlan = planInstall(cfg.ship, CREW_HOME, host, true, "run", installContext());
33324
- if (ctl.statusCommand && unitPlan.unitPaths.some((p) => existsSync56(p))) {
33770
+ if (ctl.statusCommand && unitPlan.unitPaths.some((p) => existsSync58(p))) {
33325
33771
  const st = spawnSync13(ctl.statusCommand[0], ctl.statusCommand.slice(1), { cwd: CREW_HOME, encoding: "utf8" });
33326
33772
  if (!st.error && st.status !== 0) {
33327
33773
  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");