@tablation/crew 0.170.0 → 0.171.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/cli.js +276 -188
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -17891,7 +17891,7 @@ async function runSelfLaunchCheck(own, spawnFn = spawnChild, launch = selfLaunch
17891
17891
  }
17892
17892
 
17893
17893
  // src/cli.ts
17894
- import { resolve as resolve8, dirname as dirname38, join as join67, basename as basename17 } from "path";
17894
+ import { resolve as resolve8, dirname as dirname39, join as join68, basename as basename18 } from "path";
17895
17895
  import { fileURLToPath as fileURLToPath2 } from "url";
17896
17896
  import { hostname as hostname5, homedir as homedir11, userInfo as userInfo2 } from "os";
17897
17897
  import { spawnSync as spawnSync15 } from "child_process";
@@ -29368,6 +29368,73 @@ function planSampleTicket(i) {
29368
29368
  };
29369
29369
  }
29370
29370
 
29371
+ // src/connect-append.ts
29372
+ import { chmodSync as chmodSync4, existsSync as existsSync54, readFileSync as readFileSync55, renameSync as renameSync10, statSync as statSync16, unlinkSync as unlinkSync5, writeFileSync as writeFileSync43 } from "fs";
29373
+ import { basename as basename14, dirname as dirname34, join as join59 } from "path";
29374
+ import { isMap as isMap4, isSeq as isSeq2, parseDocument as parseDocument7 } from "yaml";
29375
+ function appendRouteBlock(config, block) {
29376
+ const doc = parseDocument7(config);
29377
+ if (doc.errors.length > 0) return { ok: false, reason: "crew.yaml is not valid YAML" };
29378
+ if (!isMap4(doc.contents)) return { ok: false, reason: "crew.yaml has no routes: list" };
29379
+ const routes = doc.contents.get("routes", true);
29380
+ if (!isSeq2(routes) || !routes.range) return { ok: false, reason: "crew.yaml has no routes: list to extend" };
29381
+ const body = block.replace(/\n+$/, "");
29382
+ if (routes.items.length === 0) {
29383
+ if (!routes.flow) return { ok: false, reason: "routes: is written in a form that cannot be extended" };
29384
+ let start = routes.range[0];
29385
+ while (start > 0 && (config[start - 1] === " " || config[start - 1] === " ")) start--;
29386
+ return { ok: true, text: `${config.slice(0, start)}
29387
+ ${body}${config.slice(routes.range[1])}` };
29388
+ }
29389
+ if (routes.flow) return { ok: false, reason: "routes: is written as an inline list that cannot be extended" };
29390
+ const first = routes.items[0];
29391
+ if (!isMap4(first) || !first.range) return { ok: false, reason: "routes: holds an entry that is not a mapping" };
29392
+ const lineStart = config.lastIndexOf("\n", first.range[0] - 1) + 1;
29393
+ const dashCol = config.slice(lineStart, first.range[0]).indexOf("-");
29394
+ if (dashCol < 0) return { ok: false, reason: "routes: is written in a form that cannot be extended" };
29395
+ const shift = dashCol - 2;
29396
+ const lines2 = body.split("\n").map((l) => shift >= 0 ? " ".repeat(shift) + l : l.slice(Math.min(-shift, l.length - l.trimStart().length)));
29397
+ const indented = lines2.join("\n");
29398
+ const lastEnd = routes.range[1];
29399
+ let eol = config.indexOf("\n", Math.max(0, lastEnd - 1));
29400
+ if (eol < 0) return { ok: true, text: `${config}
29401
+ ${indented}
29402
+ ` };
29403
+ eol += 1;
29404
+ return { ok: true, text: `${config.slice(0, eol)}${indented}
29405
+ ${config.slice(eol)}` };
29406
+ }
29407
+ function replaceFileKeepingMode(path, text2) {
29408
+ const mode = statSync16(path).mode & 4095;
29409
+ const tmp = join59(dirname34(path), `.${basename14(path)}.${process.pid}.tmp`);
29410
+ try {
29411
+ writeFileSync43(tmp, text2, { mode });
29412
+ chmodSync4(tmp, mode);
29413
+ renameSync10(tmp, path);
29414
+ } catch (e) {
29415
+ if (existsSync54(tmp)) unlinkSync5(tmp);
29416
+ throw e;
29417
+ }
29418
+ }
29419
+ function planAppendToConfig(crewHome, configFile, route2, block, keyPersisted) {
29420
+ if (!keyPersisted) return { ok: false, reason: "no stored key to name" };
29421
+ let current;
29422
+ try {
29423
+ current = readFileSync55(configFile, "utf8");
29424
+ } catch (e) {
29425
+ return { ok: false, reason: `could not read the file: ${e.message}` };
29426
+ }
29427
+ const r = appendRouteBlock(current, block);
29428
+ if (!r.ok) return r;
29429
+ try {
29430
+ const loaded = loadConfig(crewHome, configFile, { text: r.text });
29431
+ if (!loaded.routes.some((x) => x.route === route2)) return { ok: false, reason: "the config loader dropped the new route" };
29432
+ } catch (e) {
29433
+ return { ok: false, reason: `the config loader rejected the result: ${e.message.split("\n")[0]}` };
29434
+ }
29435
+ return r;
29436
+ }
29437
+
29371
29438
  // src/snapshot-staleness.ts
29372
29439
  var SNAPSHOT_TABLES = [
29373
29440
  { key: "periscopesModelId", name: "Periscopes" },
@@ -29593,8 +29660,8 @@ function fixPhaseNothingToOffer(o) {
29593
29660
  }
29594
29661
 
29595
29662
  // src/worktree-sweep.ts
29596
- import { existsSync as existsSync54, readFileSync as readFileSync55, readdirSync as readdirSync16 } from "fs";
29597
- import { basename as basename14, dirname as dirname34, join as join59, resolve as resolve6 } from "path";
29663
+ import { existsSync as existsSync55, readFileSync as readFileSync56, readdirSync as readdirSync16 } from "fs";
29664
+ import { basename as basename15, dirname as dirname35, join as join60, resolve as resolve6 } from "path";
29598
29665
  function planWorktreeSweep(target, tickets, contract) {
29599
29666
  const terminal = new Set(contract.statuses.resolved.filter((s) => s !== contract.statuses.verified));
29600
29667
  const verified = contract.statuses.verified;
@@ -29635,7 +29702,7 @@ function ticketForWorktree(w, byNumber, contract) {
29635
29702
  const t = num2 ? byNumber.get(num2) : void 0;
29636
29703
  if (t && ticketStems(t).has(stem)) return t;
29637
29704
  }
29638
- const dir = basename14(w.path);
29705
+ const dir = basename15(w.path);
29639
29706
  const m = DIR_NUMBER.exec(dir);
29640
29707
  if (m && byNumber.has(m[1])) return byNumber.get(m[1]);
29641
29708
  if (!w.branch) {
@@ -29651,15 +29718,15 @@ function worktreeTicketNumbers(target) {
29651
29718
  const n = /-(\d+)$/.exec(BRANCH_STEM.exec(w.branch)?.[1] ?? "")?.[1];
29652
29719
  if (n) nums.add(n);
29653
29720
  }
29654
- const m = DIR_NUMBER_SUFFIXED.exec(basename14(w.path));
29721
+ const m = DIR_NUMBER_SUFFIXED.exec(basename15(w.path));
29655
29722
  if (m) nums.add(m[1]);
29656
29723
  }
29657
29724
  for (const d of siblingWorktreeDirs(target)) nums.add(d.number);
29658
29725
  return [...nums];
29659
29726
  }
29660
29727
  function siblingWorktreeDirs(target) {
29661
- const parent = dirname34(target.dir.replace(/[/\\]+$/, ""));
29662
- const stem = `${basename14(target.dir.replace(/[/\\]+$/, ""))}-`;
29728
+ const parent = dirname35(target.dir.replace(/[/\\]+$/, ""));
29729
+ const stem = `${basename15(target.dir.replace(/[/\\]+$/, ""))}-`;
29663
29730
  const registered = new Set(worktrees(target.dir).map((w) => resolve6(w.path)));
29664
29731
  let names;
29665
29732
  try {
@@ -29671,7 +29738,7 @@ function siblingWorktreeDirs(target) {
29671
29738
  for (const name of names) {
29672
29739
  if (!name.startsWith(stem)) continue;
29673
29740
  const m = DIR_NUMBER_SUFFIXED.exec(name);
29674
- const path = join59(parent, name);
29741
+ const path = join60(parent, name);
29675
29742
  if (m && !registered.has(resolve6(path))) out.push({ path, number: m[1] });
29676
29743
  }
29677
29744
  return out;
@@ -29684,7 +29751,7 @@ function orphanedWorktreeDirs(target, tickets, contract) {
29684
29751
  }
29685
29752
  function warnOrphanedWorktreeDirs(paths, log, held) {
29686
29753
  for (const p of paths) {
29687
- const number = DIR_NUMBER_SUFFIXED.exec(basename14(p))?.[1];
29754
+ const number = DIR_NUMBER_SUFFIXED.exec(basename15(p))?.[1];
29688
29755
  const when = held && number ? noteHeldWorktree(held.state, { repo: held.repo, path: p, ticket: number, status: "deployed", reason: "orphaned directory" }) : "first";
29689
29756
  if (when) {
29690
29757
  log.warn(`orphaned directory ${p}: its ticket is deployed but it is not a registered worktree; the sweep will not delete it \u2014 remove it by hand`, { step: "worktree" });
@@ -29706,7 +29773,7 @@ async function applyWorktreeSweep(cwd, actions, dryRun, log, remote = "origin",
29706
29773
  let removed = 0;
29707
29774
  let keptBranches = 0;
29708
29775
  for (const a of actions) {
29709
- if (!dryRun && base && !a.keepBranch && existsSync54(a.path) && isHandBackMerge(a.path, base)) {
29776
+ if (!dryRun && base && !a.keepBranch && existsSync55(a.path) && isHandBackMerge(a.path, base)) {
29710
29777
  if (gitOk(a.path, ["merge", "--abort"]) !== null) {
29711
29778
  log.emit(
29712
29779
  `abandoned the hand-back merge of ${base} in ${a.path}: ${displayKey(a.ticket)} deployed without it`,
@@ -29723,11 +29790,11 @@ async function applyWorktreeSweep(cwd, actions, dryRun, log, remote = "origin",
29723
29790
  { ticket: a.ticket.issue_id, step: "worktree" }
29724
29791
  );
29725
29792
  };
29726
- if (!dryRun && liveRun && existsSync54(a.path)) {
29793
+ if (!dryRun && liveRun && existsSync55(a.path)) {
29727
29794
  defer();
29728
29795
  continue;
29729
29796
  }
29730
- if (!dryRun && existsSync54(a.path)) {
29797
+ if (!dryRun && existsSync55(a.path)) {
29731
29798
  let dirty = false;
29732
29799
  try {
29733
29800
  dirty = status(a.path).length > 0;
@@ -29742,7 +29809,7 @@ async function applyWorktreeSweep(cwd, actions, dryRun, log, remote = "origin",
29742
29809
  continue;
29743
29810
  }
29744
29811
  }
29745
- if (!dryRun && a.requirePushed && a.branch && existsSync54(a.path) && remoteConfigured(cwd, remote) && worktreeHoldsUnpushed(a.path, remote)) {
29812
+ if (!dryRun && a.requirePushed && a.branch && existsSync55(a.path) && remoteConfigured(cwd, remote) && worktreeHoldsUnpushed(a.path, remote)) {
29746
29813
  if (pids.length) {
29747
29814
  defer();
29748
29815
  continue;
@@ -29798,7 +29865,7 @@ function isHandBackMerge(path, base) {
29798
29865
  if (!msgPath) return false;
29799
29866
  let first;
29800
29867
  try {
29801
- first = readFileSync55(resolve6(path, msgPath), "utf8").split("\n")[0] ?? "";
29868
+ first = readFileSync56(resolve6(path, msgPath), "utf8").split("\n")[0] ?? "";
29802
29869
  } catch {
29803
29870
  return false;
29804
29871
  }
@@ -29852,7 +29919,7 @@ function isTicketBranch(name, base, stems) {
29852
29919
  }
29853
29920
  function sweepCandidatesExist(cwd, base) {
29854
29921
  const linked = worktrees(cwd).slice(1);
29855
- if (linked.some((w) => DIR_NUMBER_SUFFIXED.test(basename14(w.path)) || w.branch && BRANCH_STEM.test(w.branch))) return true;
29922
+ if (linked.some((w) => DIR_NUMBER_SUFFIXED.test(basename15(w.path)) || w.branch && BRANCH_STEM.test(w.branch))) return true;
29856
29923
  if (siblingWorktreeDirs({ name: "", dir: cwd }).length) return true;
29857
29924
  return localBranches(cwd).some((b) => b !== base && /-\d+(?:-.*)?$/.test(b));
29858
29925
  }
@@ -29903,16 +29970,16 @@ function applyRemoteBranchCleanup(cwd, remote, branches2, dryRun, log) {
29903
29970
  }
29904
29971
 
29905
29972
  // src/stream-sweep.ts
29906
- import { existsSync as existsSync55, readdirSync as readdirSync17, rmSync as rmSync24, statSync as statSync16 } from "fs";
29907
- import { join as join60 } from "path";
29973
+ import { existsSync as existsSync56, readdirSync as readdirSync17, rmSync as rmSync24, statSync as statSync17 } from "fs";
29974
+ import { join as join61 } from "path";
29908
29975
  var DAY_MS2 = 24 * 60 * 60 * 1e3;
29909
29976
  function planStreamSweep(stateDir, retentionDays, now = Date.now()) {
29910
- const dir = join60(stateDir, "streams");
29911
- if (!existsSync55(dir)) return [];
29977
+ const dir = join61(stateDir, "streams");
29978
+ if (!existsSync56(dir)) return [];
29912
29979
  const cutoff = now - retentionDays * DAY_MS2;
29913
- return readdirSync17(dir).map((name) => join60(dir, name)).filter((path) => {
29980
+ return readdirSync17(dir).map((name) => join61(dir, name)).filter((path) => {
29914
29981
  try {
29915
- return statSync16(path).mtimeMs < cutoff;
29982
+ return statSync17(path).mtimeMs < cutoff;
29916
29983
  } catch {
29917
29984
  return false;
29918
29985
  }
@@ -29936,11 +30003,11 @@ function applyStreamSweep(paths, dryRun, log) {
29936
30003
  return removed;
29937
30004
  }
29938
30005
  function planEventsSweep(stateDir, retentionDays, now = Date.now()) {
29939
- if (!existsSync55(stateDir)) return [];
30006
+ if (!existsSync56(stateDir)) return [];
29940
30007
  const cutoff = now - retentionDays * DAY_MS2;
29941
- return readdirSync17(stateDir).filter((name) => ROTATED_EVENTS_RE.test(name)).map((name) => join60(stateDir, name)).filter((path) => {
30008
+ return readdirSync17(stateDir).filter((name) => ROTATED_EVENTS_RE.test(name)).map((name) => join61(stateDir, name)).filter((path) => {
29942
30009
  try {
29943
- return statSync16(path).mtimeMs < cutoff;
30010
+ return statSync17(path).mtimeMs < cutoff;
29944
30011
  } catch {
29945
30012
  return false;
29946
30013
  }
@@ -29949,18 +30016,18 @@ function planEventsSweep(stateDir, retentionDays, now = Date.now()) {
29949
30016
  function planSizeCapSweep(stateDir, maxBytes, now = Date.now()) {
29950
30017
  const files = [];
29951
30018
  const add = (dir, keep) => {
29952
- if (!existsSync55(dir)) return;
30019
+ if (!existsSync56(dir)) return;
29953
30020
  for (const name of readdirSync17(dir)) {
29954
30021
  if (!keep(name)) continue;
29955
- const path = join60(dir, name);
30022
+ const path = join61(dir, name);
29956
30023
  try {
29957
- const st = statSync16(path);
30024
+ const st = statSync17(path);
29958
30025
  if (st.isFile()) files.push({ path, mtime: st.mtimeMs, size: st.size });
29959
30026
  } catch {
29960
30027
  }
29961
30028
  }
29962
30029
  };
29963
- add(join60(stateDir, "streams"), () => true);
30030
+ add(join61(stateDir, "streams"), () => true);
29964
30031
  add(stateDir, (name) => ROTATED_EVENTS_RE.test(name));
29965
30032
  let total = files.reduce((n, f2) => n + f2.size, 0);
29966
30033
  const out = [];
@@ -29980,7 +30047,7 @@ function planStateSweep(stateDir, retentionDays, maxBytes, now = Date.now()) {
29980
30047
  }
29981
30048
 
29982
30049
  // src/cli.ts
29983
- import { realpathSync as realpathSync4, readFileSync as readFileSync58, existsSync as existsSync60, mkdirSync as mkdirSync44, writeFileSync as writeFileSync45, rmSync as rmSync27, unlinkSync as unlinkSync6, copyFileSync as copyFileSync2, renameSync as renameSync10, statSync as statSync19, readdirSync as readdirSync22 } from "fs";
30050
+ import { realpathSync as realpathSync4, readFileSync as readFileSync59, existsSync as existsSync61, mkdirSync as mkdirSync44, writeFileSync as writeFileSync46, rmSync as rmSync27, unlinkSync as unlinkSync7, copyFileSync as copyFileSync2, renameSync as renameSync11, statSync as statSync20, readdirSync as readdirSync22 } from "fs";
29984
30051
  import { createInterface } from "readline/promises";
29985
30052
 
29986
30053
  // src/periscope-resume.ts
@@ -30056,33 +30123,33 @@ ${tail2(preview.output)}`);
30056
30123
  import { dirname as dirOf2, resolve as resolvePath } from "path";
30057
30124
 
30058
30125
  // src/bundle-staleness.ts
30059
- import { existsSync as existsSync56, readdirSync as readdirSync18, statSync as statSync17 } from "fs";
30060
- import { join as join61 } from "path";
30126
+ import { existsSync as existsSync57, readdirSync as readdirSync18, statSync as statSync18 } from "fs";
30127
+ import { join as join62 } from "path";
30061
30128
  function builtVersion() {
30062
- return true ? "0.170.0" : null;
30129
+ return true ? "0.171.0" : null;
30063
30130
  }
30064
30131
  var REBUILD_HINT = "rebuild with npm run build";
30065
30132
  function newestMtime(path) {
30066
30133
  let stat2;
30067
30134
  try {
30068
- stat2 = statSync17(path);
30135
+ stat2 = statSync18(path);
30069
30136
  } catch {
30070
30137
  return 0;
30071
30138
  }
30072
30139
  if (stat2.isFile()) return stat2.mtimeMs;
30073
30140
  if (!stat2.isDirectory()) return 0;
30074
30141
  let latest = stat2.mtimeMs;
30075
- for (const e of readdirSync18(path, { withFileTypes: true })) latest = Math.max(latest, newestMtime(join61(path, e.name)));
30142
+ for (const e of readdirSync18(path, { withFileTypes: true })) latest = Math.max(latest, newestMtime(join62(path, e.name)));
30076
30143
  return latest;
30077
30144
  }
30078
30145
  function bundleStaleness(i) {
30079
30146
  if (i.built === null || i.compiled) return null;
30080
- const src = join61(i.home, "src");
30081
- if (!existsSync56(src)) return null;
30147
+ const src = join62(i.home, "src");
30148
+ if (!existsSync57(src)) return null;
30082
30149
  if (i.built !== i.current) {
30083
30150
  return { kind: "version", builtVersion: i.built, message: `running a bundle built from ${i.built} (package.json names ${i.current}); ${REBUILD_HINT}` };
30084
30151
  }
30085
- const bundle = statSafe(join61(i.home, "dist", "cli.js"));
30152
+ const bundle = statSafe(join62(i.home, "dist", "cli.js"));
30086
30153
  if (bundle === null) return null;
30087
30154
  if (newestMtime(src) > bundle) {
30088
30155
  return { kind: "source", builtVersion: i.built, message: `running a bundle older than the source in src/ (both ${i.current}); ${REBUILD_HINT}` };
@@ -30091,7 +30158,7 @@ function bundleStaleness(i) {
30091
30158
  }
30092
30159
  function statSafe(p) {
30093
30160
  try {
30094
- return statSync17(p).mtimeMs;
30161
+ return statSync18(p).mtimeMs;
30095
30162
  } catch {
30096
30163
  return null;
30097
30164
  }
@@ -30300,8 +30367,8 @@ async function unregisterEndpoint(workspaceId, info, d) {
30300
30367
  import { createServer as createHttpServer } from "http";
30301
30368
  import { spawn as spawn10 } from "child_process";
30302
30369
  import { randomBytes as randomBytes2 } from "crypto";
30303
- import { existsSync as existsSync57, mkdirSync as mkdirSync41, readFileSync as readFileSync56, writeFileSync as writeFileSync43, unlinkSync as unlinkSync5, readdirSync as readdirSync19 } from "fs";
30304
- import { join as join62 } from "path";
30370
+ import { existsSync as existsSync58, mkdirSync as mkdirSync41, readFileSync as readFileSync57, writeFileSync as writeFileSync44, unlinkSync as unlinkSync6, readdirSync as readdirSync19 } from "fs";
30371
+ import { join as join63 } from "path";
30305
30372
 
30306
30373
  // src/secret-compare.ts
30307
30374
  import { timingSafeEqual } from "crypto";
@@ -30394,27 +30461,27 @@ var defaultSpawn2 = (cmd, args, env) => {
30394
30461
  return child;
30395
30462
  };
30396
30463
  function syncDaemonStatePath(stateDir, workspaceId) {
30397
- return join62(stateDir, "passengers", `${workspaceId}-sync.json`);
30464
+ return join63(stateDir, "passengers", `${workspaceId}-sync.json`);
30398
30465
  }
30399
30466
  function readPersistedSyncDaemon(stateDir, workspaceId) {
30400
30467
  const path = syncDaemonStatePath(stateDir, workspaceId);
30401
- if (!existsSync57(path)) return void 0;
30468
+ if (!existsSync58(path)) return void 0;
30402
30469
  try {
30403
- return JSON.parse(readFileSync56(path, "utf8"));
30470
+ return JSON.parse(readFileSync57(path, "utf8"));
30404
30471
  } catch {
30405
30472
  return void 0;
30406
30473
  }
30407
30474
  }
30408
30475
  function writePersistedSyncDaemon(stateDir, state) {
30409
30476
  const path = syncDaemonStatePath(stateDir, state.workspaceId);
30410
- mkdirSync41(join62(stateDir, "passengers"), { recursive: true });
30411
- writeFileSync43(path, `${JSON.stringify(state, null, 2)}
30477
+ mkdirSync41(join63(stateDir, "passengers"), { recursive: true });
30478
+ writeFileSync44(path, `${JSON.stringify(state, null, 2)}
30412
30479
  `);
30413
30480
  }
30414
30481
  function removePersistedSyncDaemon(stateDir, workspaceId) {
30415
30482
  const path = syncDaemonStatePath(stateDir, workspaceId);
30416
30483
  try {
30417
- unlinkSync5(path);
30484
+ unlinkSync6(path);
30418
30485
  } catch {
30419
30486
  }
30420
30487
  }
@@ -30425,8 +30492,8 @@ function waitForExit(pid, alive, timeoutMs = 5e3) {
30425
30492
  }
30426
30493
  }
30427
30494
  function readAllPersistedSyncWorkspaceIds(stateDir) {
30428
- const dir = join62(stateDir, "passengers");
30429
- if (!existsSync57(dir)) return [];
30495
+ const dir = join63(stateDir, "passengers");
30496
+ if (!existsSync58(dir)) return [];
30430
30497
  const suffix = "-sync.json";
30431
30498
  return readdirSync19(dir).filter((f2) => f2.endsWith(suffix)).map((f2) => f2.slice(0, -suffix.length));
30432
30499
  }
@@ -30490,7 +30557,7 @@ import { createServer, request as httpRequest } from "http";
30490
30557
  import { request as httpsRequest } from "https";
30491
30558
  import { connect as netConnect } from "net";
30492
30559
  import { connect as tlsConnect } from "tls";
30493
- import { dirname as dirname35, isAbsolute as isAbsolute4 } from "path";
30560
+ import { dirname as dirname36, isAbsolute as isAbsolute4 } from "path";
30494
30561
  import { brotliDecompressSync, gunzipSync, inflateSync } from "zlib";
30495
30562
 
30496
30563
  // src/periscope-inspector.ts
@@ -30604,7 +30671,7 @@ function parsePointedBody(raw) {
30604
30671
  return entry;
30605
30672
  }
30606
30673
  function appendPointed(file, entry, now = /* @__PURE__ */ new Date()) {
30607
- mkdirSync42(dirname35(file), { recursive: true });
30674
+ mkdirSync42(dirname36(file), { recursive: true });
30608
30675
  appendFileSync4(file, `${JSON.stringify({ ...entry, at: now.toISOString() })}
30609
30676
  `);
30610
30677
  }
@@ -30893,7 +30960,7 @@ async function startWorktreeIntel(d) {
30893
30960
  }
30894
30961
 
30895
30962
  // src/contract-refusal.ts
30896
- import { join as join63 } from "path";
30963
+ import { join as join64 } from "path";
30897
30964
  function contractFixers(dir, baseRef, tickets, locate) {
30898
30965
  const out = [];
30899
30966
  for (const t of tickets) {
@@ -30905,7 +30972,7 @@ function contractFixers(dir, baseRef, tickets, locate) {
30905
30972
  const text2 = gitOk(dir, ["show", `${branch}:${file}`]);
30906
30973
  if (text2 === null) continue;
30907
30974
  try {
30908
- parseRepoConfig(text2, join63(dir, file));
30975
+ parseRepoConfig(text2, join64(dir, file));
30909
30976
  } catch (e) {
30910
30977
  if (e instanceof RepoConfigError) continue;
30911
30978
  throw e;
@@ -30918,20 +30985,20 @@ function contractFixers(dir, baseRef, tickets, locate) {
30918
30985
  // src/control-api.ts
30919
30986
  import { createHash as createHash12 } from "crypto";
30920
30987
  import {
30921
- chmodSync as chmodSync4,
30988
+ chmodSync as chmodSync5,
30922
30989
  closeSync as closeSync7,
30923
- existsSync as existsSync58,
30990
+ existsSync as existsSync59,
30924
30991
  fstatSync as fstatSync2,
30925
30992
  openSync as openSync7,
30926
30993
  readSync as readSync4,
30927
30994
  readdirSync as readdirSync20,
30928
30995
  rmSync as rmSync25,
30929
- statSync as statSync18,
30996
+ statSync as statSync19,
30930
30997
  watch
30931
30998
  } from "fs";
30932
30999
  import { createConnection } from "net";
30933
31000
  import { createServer as createServer2 } from "http";
30934
- import { basename as basename15, dirname as dirname36, join as join64 } from "path";
31001
+ import { basename as basename16, dirname as dirname37, join as join65 } from "path";
30935
31002
  import { execFile as execFile6, spawn as spawn13 } from "child_process";
30936
31003
 
30937
31004
  // src/periscope-control.ts
@@ -31169,7 +31236,7 @@ function runCrew(args, onLine, timeoutMs = 20 * 6e4) {
31169
31236
  // src/control-api.ts
31170
31237
  var PAUSABLE = ["dev", "design", "qa"];
31171
31238
  var CONTROL_SOCKET_NAME = "control.sock";
31172
- var controlSocketFor = (stateDir) => join64(stateDir, CONTROL_SOCKET_NAME);
31239
+ var controlSocketFor = (stateDir) => join65(stateDir, CONTROL_SOCKET_NAME);
31173
31240
  var MAX_SOCKET_PATH = 100;
31174
31241
  var MAX_TAIL_BYTES = 1024 * 1024;
31175
31242
  var MAX_WAIT_SECONDS = 30;
@@ -31256,7 +31323,7 @@ function candidates(live2, rotated) {
31256
31323
  const out = [live2];
31257
31324
  if (!rotated) return out;
31258
31325
  try {
31259
- for (const n of readdirSync20(dirname36(live2))) if (ROTATED_EVENTS_RE.test(n)) out.push(join64(dirname36(live2), n));
31326
+ for (const n of readdirSync20(dirname37(live2))) if (ROTATED_EVENTS_RE.test(n)) out.push(join65(dirname37(live2), n));
31260
31327
  } catch {
31261
31328
  }
31262
31329
  return out;
@@ -31279,7 +31346,7 @@ function readRange(path, from, max) {
31279
31346
  }
31280
31347
  }
31281
31348
  function lastLines2(path, n) {
31282
- const st = statSync18(path);
31349
+ const st = statSync19(path);
31283
31350
  const cursorAt = (off) => encodeCursor({ dev: st.dev, ino: st.ino, off });
31284
31351
  if (n <= 0 || st.size === 0) return { lines: [], cursor: cursorAt(st.size), reset: false };
31285
31352
  let start = st.size;
@@ -31300,7 +31367,7 @@ function lastLines2(path, n) {
31300
31367
  }
31301
31368
  function readTail(live2, opts) {
31302
31369
  const max = opts.maxBytes ?? MAX_TAIL_BYTES;
31303
- if (!existsSync58(live2)) {
31370
+ if (!existsSync59(live2)) {
31304
31371
  return { lines: [], cursor: opts.after ?? encodeCursor({ dev: 0, ino: 0, off: 0 }), reset: false };
31305
31372
  }
31306
31373
  const cur = opts.after ? decodeCursor(opts.after) : null;
@@ -31313,7 +31380,7 @@ function readTail(live2, opts) {
31313
31380
  } else {
31314
31381
  const found = candidates(live2, opts.rotated ?? false).find((p) => {
31315
31382
  try {
31316
- const s = statSync18(p);
31383
+ const s = statSync19(p);
31317
31384
  return s.ino === cur.ino && s.dev === cur.dev;
31318
31385
  } catch {
31319
31386
  return false;
@@ -31324,7 +31391,7 @@ function readTail(live2, opts) {
31324
31391
  off = cur.off;
31325
31392
  } else reset = true;
31326
31393
  }
31327
- let size = statSync18(path).size;
31394
+ let size = statSync19(path).size;
31328
31395
  if (off > size) {
31329
31396
  off = 0;
31330
31397
  reset = true;
@@ -31332,12 +31399,12 @@ function readTail(live2, opts) {
31332
31399
  if (off >= size && path !== live2) {
31333
31400
  path = live2;
31334
31401
  off = 0;
31335
- size = statSync18(path).size;
31402
+ size = statSync19(path).size;
31336
31403
  }
31337
31404
  const { text: text2 } = readRange(path, off, max);
31338
31405
  const cut = text2.lastIndexOf("\n");
31339
31406
  const whole = cut < 0 ? "" : text2.slice(0, cut + 1);
31340
- const st = statSync18(path);
31407
+ const st = statSync19(path);
31341
31408
  return {
31342
31409
  lines: whole.split("\n").filter((l) => l.length),
31343
31410
  cursor: encodeCursor({ dev: st.dev, ino: st.ino, off: off + Buffer.byteLength(whole) }),
@@ -31387,7 +31454,7 @@ function pauseDoc(state) {
31387
31454
  }
31388
31455
  function describeStream(r) {
31389
31456
  return {
31390
- run: basename15(r.streamPath).replace(/\.jsonl$/, ""),
31457
+ run: basename16(r.streamPath).replace(/\.jsonl$/, ""),
31391
31458
  pid: r.pid,
31392
31459
  ticket: r.ticket,
31393
31460
  role: r.role,
@@ -31424,7 +31491,7 @@ async function tailReply(path, q2, rotated, abort) {
31424
31491
  const deadline = Date.now() + Math.min(wait, MAX_WAIT_SECONDS) * 1e3;
31425
31492
  let r = readTail(path, { after, tail: tail3, rotated });
31426
31493
  while (after && !r.lines.length && !r.reset && Date.now() < deadline && !abort.aborted) {
31427
- await waitForChange(dirname36(path), deadline - Date.now(), abort);
31494
+ await waitForChange(dirname37(path), deadline - Date.now(), abort);
31428
31495
  r = readTail(path, { after: r.cursor, rotated });
31429
31496
  }
31430
31497
  return reply2(200, r);
@@ -31433,14 +31500,14 @@ var NOTE_MAX_CHARS = 4e3;
31433
31500
  var SEAT_ROLES = ["dev", "design", "qa", "triage", "pair"];
31434
31501
  async function postRunMessage(deps, run4, body) {
31435
31502
  if (!RUN_NAME_RE.test(run4) || run4.includes("..")) return err2(400, "not a run name");
31436
- const live2 = liveRuns(deps.stateDir).find((r) => basename15(r.streamPath, ".jsonl") === run4.replace(/\.jsonl$/, ""));
31503
+ const live2 = liveRuns(deps.stateDir).find((r) => basename16(r.streamPath, ".jsonl") === run4.replace(/\.jsonl$/, ""));
31437
31504
  const carry = "A note for the work item posted from the platform is carried forward into its next run's brief.";
31438
31505
  if (!live2) return err2(404, `no live run ${run4}: it is unknown or has finished. ${carry}`);
31439
31506
  if (!body) return err2(400, "body must be a small JSON object");
31440
31507
  const text2 = typeof body.text === "string" ? body.text.trim() : "";
31441
31508
  if (!text2 || text2.length > NOTE_MAX_CHARS) return err2(400, `text must be a string of 1 to ${NOTE_MAX_CHARS} characters`);
31442
31509
  if (body.author !== void 0 && typeof body.author !== "string") return err2(400, "author must be a string");
31443
- const input = runInputFor(basename15(live2.streamPath, ".jsonl"));
31510
+ const input = runInputFor(basename16(live2.streamPath, ".jsonl"));
31444
31511
  const rowId = input?.agentLogRowId();
31445
31512
  if (!input?.target || !rowId) return err2(409, `run ${run4} is live but this daemon cannot record a note on it (it did not start the run, or the run has no Agent Log row). ${carry}`);
31446
31513
  try {
@@ -31515,8 +31582,8 @@ async function route(deps, method, url, req, abort) {
31515
31582
  if (p.startsWith("/streams/") && get2) {
31516
31583
  const run4 = decodeURIComponent(p.slice("/streams/".length));
31517
31584
  if (!RUN_NAME_RE.test(run4) || run4.includes("..") || /\.(pid|meta\.json|events\.jsonl)$/.test(run4)) return err2(400, "not a run name");
31518
- const file = join64(deps.stateDir, "streams", run4.endsWith(".jsonl") ? run4 : `${run4}.jsonl`);
31519
- if (!existsSync58(file)) return err2(404, "no such run");
31585
+ const file = join65(deps.stateDir, "streams", run4.endsWith(".jsonl") ? run4 : `${run4}.jsonl`);
31586
+ if (!existsSync59(file)) return err2(404, "no such run");
31520
31587
  return tailReply(file, url.searchParams, false, abort);
31521
31588
  }
31522
31589
  const note = /^\/streams\/([^/]+)\/messages$/.exec(p);
@@ -31565,7 +31632,7 @@ function send2(res, r) {
31565
31632
  res.end(body);
31566
31633
  }
31567
31634
  async function socketIsStale(path) {
31568
- if (!existsSync58(path)) return false;
31635
+ if (!existsSync59(path)) return false;
31569
31636
  return new Promise((resolve9) => {
31570
31637
  const c = createConnection(path);
31571
31638
  c.once("connect", () => {
@@ -31584,7 +31651,7 @@ async function startControlServer(deps) {
31584
31651
  return null;
31585
31652
  }
31586
31653
  if (await socketIsStale(path)) rmSync25(path, { force: true });
31587
- else if (existsSync58(path)) {
31654
+ else if (existsSync59(path)) {
31588
31655
  log(`control API not started: ${path} is in use by another process`);
31589
31656
  return null;
31590
31657
  }
@@ -31621,7 +31688,7 @@ async function startControlServer(deps) {
31621
31688
  });
31622
31689
  server.listen(path, () => {
31623
31690
  try {
31624
- chmodSync4(path, 384);
31691
+ chmodSync5(path, 384);
31625
31692
  } catch {
31626
31693
  }
31627
31694
  server.on("error", (e) => log(`control API error: ${e.message}`));
@@ -31683,31 +31750,31 @@ function crewJson(args, timeoutMs = CREW_JSON_TIMEOUT_MS) {
31683
31750
 
31684
31751
  // src/periscope-mcp.ts
31685
31752
  import { lstat, mkdir, readdir, readFile, readlink, realpath, rm, stat, writeFile } from "fs/promises";
31686
- import { basename as basename16, dirname as dirname37, isAbsolute as isAbsolute5, join as join66, relative as relative2, resolve as resolve7, sep } from "path";
31753
+ import { basename as basename17, dirname as dirname38, isAbsolute as isAbsolute5, join as join67, relative as relative2, resolve as resolve7, sep } from "path";
31687
31754
  import { z } from "zod";
31688
31755
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
31689
31756
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
31690
31757
 
31691
31758
  // src/periscope-endpoints.ts
31692
31759
  import { randomBytes as randomBytes3 } from "crypto";
31693
- import { chmodSync as chmodSync5, existsSync as existsSync59, mkdirSync as mkdirSync43, readdirSync as readdirSync21, readFileSync as readFileSync57, rmSync as rmSync26, writeFileSync as writeFileSync44 } from "fs";
31694
- import { join as join65 } from "path";
31695
- var secretDir = (stateDir) => join65(stateDir, "periscope-mcp");
31696
- var secretFile = (stateDir, id) => join65(secretDir(stateDir), `${id}.json`);
31697
- var endpointDir = (stateDir) => join65(stateDir, "periscope-endpoints");
31698
- var endpointFile = (stateDir, id) => join65(endpointDir(stateDir), `${id}.json`);
31760
+ import { chmodSync as chmodSync6, existsSync as existsSync60, mkdirSync as mkdirSync43, readdirSync as readdirSync21, readFileSync as readFileSync58, rmSync as rmSync26, writeFileSync as writeFileSync45 } from "fs";
31761
+ import { join as join66 } from "path";
31762
+ var secretDir = (stateDir) => join66(stateDir, "periscope-mcp");
31763
+ var secretFile = (stateDir, id) => join66(secretDir(stateDir), `${id}.json`);
31764
+ var endpointDir = (stateDir) => join66(stateDir, "periscope-endpoints");
31765
+ var endpointFile = (stateDir, id) => join66(endpointDir(stateDir), `${id}.json`);
31699
31766
  function mintPeriscopeSecret(stateDir, ticketRecordId) {
31700
31767
  mkdirSync43(secretDir(stateDir), { recursive: true, mode: 448 });
31701
31768
  const secret = randomBytes3(32).toString("base64url");
31702
31769
  const file = secretFile(stateDir, ticketRecordId);
31703
- writeFileSync44(file, `${JSON.stringify({ secret })}
31770
+ writeFileSync45(file, `${JSON.stringify({ secret })}
31704
31771
  `, { mode: 384 });
31705
- chmodSync5(file, 384);
31772
+ chmodSync6(file, 384);
31706
31773
  return secret;
31707
31774
  }
31708
31775
  function readPeriscopeSecret(stateDir, ticketRecordId) {
31709
31776
  try {
31710
- const v = JSON.parse(readFileSync57(secretFile(stateDir, ticketRecordId), "utf8"));
31777
+ const v = JSON.parse(readFileSync58(secretFile(stateDir, ticketRecordId), "utf8"));
31711
31778
  return typeof v.secret === "string" && v.secret ? v.secret : void 0;
31712
31779
  } catch {
31713
31780
  return void 0;
@@ -31718,14 +31785,14 @@ function removePeriscopeSecret(stateDir, ticketRecordId) {
31718
31785
  }
31719
31786
  function readPeriscopeEndpoint(stateDir, ticketRecordId) {
31720
31787
  try {
31721
- return JSON.parse(readFileSync57(endpointFile(stateDir, ticketRecordId), "utf8"));
31788
+ return JSON.parse(readFileSync58(endpointFile(stateDir, ticketRecordId), "utf8"));
31722
31789
  } catch {
31723
31790
  return void 0;
31724
31791
  }
31725
31792
  }
31726
31793
  function writePeriscopeEndpoint(stateDir, rec) {
31727
31794
  mkdirSync43(endpointDir(stateDir), { recursive: true });
31728
- writeFileSync44(endpointFile(stateDir, rec.ticketRecordId), `${JSON.stringify(rec, null, 2)}
31795
+ writeFileSync45(endpointFile(stateDir, rec.ticketRecordId), `${JSON.stringify(rec, null, 2)}
31729
31796
  `);
31730
31797
  }
31731
31798
  function removePeriscopeEndpointRecord(stateDir, ticketRecordId) {
@@ -31733,7 +31800,7 @@ function removePeriscopeEndpointRecord(stateDir, ticketRecordId) {
31733
31800
  }
31734
31801
  function listPeriscopeEndpoints(stateDir) {
31735
31802
  const dir = endpointDir(stateDir);
31736
- if (!existsSync59(dir)) return [];
31803
+ if (!existsSync60(dir)) return [];
31737
31804
  const out = [];
31738
31805
  for (const name of readdirSync21(dir)) {
31739
31806
  if (!name.endsWith(".json")) continue;
@@ -31821,12 +31888,12 @@ async function realAncestor(p) {
31821
31888
  }
31822
31889
  if (isLink) {
31823
31890
  if (++hops > 40) throw new PathRefusal(`too many symbolic links resolving ${p}`);
31824
- cur = resolve7(dirname37(cur), await readlink(cur));
31891
+ cur = resolve7(dirname38(cur), await readlink(cur));
31825
31892
  continue;
31826
31893
  }
31827
- const parent = dirname37(cur);
31894
+ const parent = dirname38(cur);
31828
31895
  if (parent === cur) throw new PathRefusal(`cannot resolve ${p}`);
31829
- tail3.push(basename16(cur));
31896
+ tail3.push(basename17(cur));
31830
31897
  cur = parent;
31831
31898
  }
31832
31899
  }
@@ -31836,13 +31903,13 @@ async function resolveInWorktree(root, requested) {
31836
31903
  let abs;
31837
31904
  if (isAbsolute5(requested)) {
31838
31905
  abs = resolve7(requested);
31839
- if (isInside(root, abs)) abs = join66(realRoot, relative2(root, abs));
31906
+ if (isInside(root, abs)) abs = join67(realRoot, relative2(root, abs));
31840
31907
  } else {
31841
31908
  abs = resolve7(realRoot, requested);
31842
31909
  }
31843
31910
  if (!isInside(realRoot, abs)) throw new PathRefusal(`${requested} is outside this periscope's worktree`);
31844
31911
  const { real, rest } = await realAncestor(abs);
31845
- const final = rest ? join66(real, rest) : real;
31912
+ const final = rest ? join67(real, rest) : real;
31846
31913
  if (!isInside(realRoot, final)) throw new PathRefusal(`${requested} is outside this periscope's worktree`);
31847
31914
  if (relative2(realRoot, final).split(sep).includes(".git")) throw new PathRefusal(".git is not reachable from a periscope");
31848
31915
  return final;
@@ -31910,7 +31977,7 @@ function createPeriscopeMcpServer(d, sc) {
31910
31977
  const entries = (await readdir(abs, { withFileTypes: true })).filter((e) => e.name !== ".git");
31911
31978
  const lines2 = await Promise.all(entries.map(async (e) => {
31912
31979
  if (e.isDirectory()) return `[DIR] ${e.name}`;
31913
- const size = (await lstat(join66(abs, e.name))).size;
31980
+ const size = (await lstat(join67(abs, e.name))).size;
31914
31981
  return `[FILE] ${e.name} (${size} bytes)`;
31915
31982
  }));
31916
31983
  return text(lines2.join("\n") || "(empty)");
@@ -31935,7 +32002,7 @@ function createPeriscopeMcpServer(d, sc) {
31935
32002
  if (Buffer.byteLength(content) > MAX_WRITE_BYTES) return text(`content exceeds ${MAX_WRITE_BYTES} bytes`, true);
31936
32003
  const abs = await inTree(path);
31937
32004
  if (abs === await realpath(root)) return text("path must name a file", true);
31938
- await mkdir(dirname37(abs), { recursive: true });
32005
+ await mkdir(dirname38(abs), { recursive: true });
31939
32006
  await inTree(path);
31940
32007
  await writeFile(abs, content);
31941
32008
  return text(`Wrote ${Buffer.byteLength(content)} bytes to ${await rel(abs)}`);
@@ -31975,9 +32042,9 @@ function createPeriscopeMcpServer(d, sc) {
31975
32042
  inputSchema: { path: z.string() },
31976
32043
  annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: false }
31977
32044
  }, async ({ path }) => {
31978
- const parent = await inTree(dirname37(path) === "" ? "." : dirname37(path));
31979
- const abs = join66(parent, basename16(path));
31980
- if (basename16(path) === ".git" || abs === parent) return text("path must name a file", true);
32045
+ const parent = await inTree(dirname38(path) === "" ? "." : dirname38(path));
32046
+ const abs = join67(parent, basename17(path));
32047
+ if (basename17(path) === ".git" || abs === parent) return text("path must name a file", true);
31981
32048
  const st = await lstat(abs).catch(() => void 0);
31982
32049
  if (!st) return text(`${path} does not exist`, true);
31983
32050
  if (st.isDirectory()) return text(`${path} is a directory; only files are deleted`, true);
@@ -32097,7 +32164,7 @@ function findPeriscope(sidecars, segment) {
32097
32164
  }
32098
32165
 
32099
32166
  // src/cli.ts
32100
- var CREW_HOME = isCompiledBinary(import.meta.url) ? dirname38(process.execPath) : resolve8(dirname38(fileURLToPath2(import.meta.url)), "..");
32167
+ var CREW_HOME = isCompiledBinary(import.meta.url) ? dirname39(process.execPath) : resolve8(dirname39(fileURLToPath2(import.meta.url)), "..");
32101
32168
  {
32102
32169
  const v = crewVersion(CREW_HOME);
32103
32170
  if (v !== "0.0.0") setRunningCrewVersion(v);
@@ -32511,7 +32578,7 @@ if (command === "provision") {
32511
32578
  process.exit(outcome.code);
32512
32579
  }
32513
32580
  if (command === "pool-member") {
32514
- const pool = poolConfigFrom(argv, process.env, () => readFileSync58(0, "utf8"));
32581
+ const pool = poolConfigFrom(argv, process.env, () => readFileSync59(0, "utf8"));
32515
32582
  if (typeof pool === "string") {
32516
32583
  process.stderr.write(`crew pool-member: ${pool}
32517
32584
  `);
@@ -32856,7 +32923,7 @@ if (command === "passenger-sync-daemon") {
32856
32923
  } else {
32857
32924
  const toleratesNoRoutes = command === "routes" || command === "credential" || command === "forge" || command === "repos" || command === "ship" || command === "disconnect" && flag("reset") || command === "deprovision" || command === "connect" && flag("sign-out");
32858
32925
  const configless = command === "routes" || command === "connect" && flag("sign-out") || command === "disconnect" && flag("reset") || command === "deprovision";
32859
- if (configless && !existsSync60(findConfigFile(CREW_HOME))) {
32926
+ if (configless && !existsSync61(findConfigFile(CREW_HOME))) {
32860
32927
  cfg = loadConfig(CREW_HOME, firstRunConfigPath(), { text: "ship: {}\n", allowNoRoutes: true });
32861
32928
  } else {
32862
32929
  cfg = loadConfig(CREW_HOME, void 0, toleratesNoRoutes ? { allowNoRoutes: true } : {});
@@ -32879,7 +32946,7 @@ if (command === "passenger-sync-daemon") {
32879
32946
  throw e;
32880
32947
  }
32881
32948
  if (command === "credential") {
32882
- const r = runCredential(positional[1], readFileSync58(0, "utf8"), cfg.ship.forges, cfg.ship.stateDir, process.env, !flag("no-miss"));
32949
+ const r = runCredential(positional[1], readFileSync59(0, "utf8"), cfg.ship.forges, cfg.ship.stateDir, process.env, !flag("no-miss"));
32883
32950
  process.stdout.write(r.out);
32884
32951
  process.stderr.write(r.err);
32885
32952
  process.exit(r.code);
@@ -32891,9 +32958,9 @@ if (command === "passenger-sync-daemon") {
32891
32958
  forges: cfg.ship.forges,
32892
32959
  stateDir: cfg.ship.stateDir,
32893
32960
  configFile: cfg.configFile,
32894
- readFile: (p) => readFileSync58(p, "utf8"),
32895
- writeFile: (p, t) => writeFileSync45(p, t),
32896
- stdin: () => readFileSync58(0, "utf8"),
32961
+ readFile: (p) => readFileSync59(p, "utf8"),
32962
+ writeFile: (p, t) => writeFileSync46(p, t),
32963
+ stdin: () => readFileSync59(0, "utf8"),
32897
32964
  env: process.env
32898
32965
  }
32899
32966
  );
@@ -33253,15 +33320,15 @@ if (command === "passenger-sync-daemon") {
33253
33320
  for (const l of summarizeJobs(results, { dryRun, verbose: flag("verbose"), host })) emit.emit(l);
33254
33321
  if (host === "linux" && hasSystemd) {
33255
33322
  const label = labelFor(CREW_HOME, "run");
33256
- const staleTimer = join67(homedir11(), ".config", "systemd", "user", `${label}.timer`);
33257
- if (existsSync60(staleTimer)) {
33323
+ const staleTimer = join68(homedir11(), ".config", "systemd", "user", `${label}.timer`);
33324
+ if (existsSync61(staleTimer)) {
33258
33325
  emit.emit(
33259
33326
  `removing stale run timer from before the persistent-service cutover: ${staleTimer}${dryRun ? " (dry run, not applied)" : ""}`
33260
33327
  );
33261
33328
  if (!dryRun) {
33262
33329
  spawnSync15("systemctl", ["--user", "disable", "--now", `${label}.timer`], { cwd: CREW_HOME, env: withUserBusEnv() });
33263
33330
  try {
33264
- unlinkSync6(staleTimer);
33331
+ unlinkSync7(staleTimer);
33265
33332
  } catch {
33266
33333
  }
33267
33334
  }
@@ -33303,7 +33370,7 @@ if (command === "passenger-sync-daemon") {
33303
33370
  const { settled: doctorRepos, errors: refusedRepos } = await settleRepos(reposOf(c), (t) => t.name, (t) => resolveOneRepo(c, t));
33304
33371
  for (const e of refusedRepos) problems.push(`repo ${e.repo}: ${e.detail}`);
33305
33372
  for (const r of doctorRepos) {
33306
- if (!existsSync60(r.dir)) problems.push(`repo ${r.name}: ${r.dir} is missing on disk`);
33373
+ if (!existsSync61(r.dir)) problems.push(`repo ${r.name}: ${r.dir} is missing on disk`);
33307
33374
  if (!satisfies(host, r.config.platform)) problems.push(`repo ${r.name}: requires ${r.config.platform}, this host is ${host}`);
33308
33375
  readiness.push(...validateEffective(r.config).map((p) => `repo ${r.name}: ${p}`));
33309
33376
  }
@@ -33343,7 +33410,7 @@ if (command === "passenger-sync-daemon") {
33343
33410
  }
33344
33411
  async function doctorFix(o) {
33345
33412
  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))));
33346
- const unitExists = (p) => existsSync60(p);
33413
+ const unitExists = (p) => existsSync61(p);
33347
33414
  const crontab = o.host === "linux" ? spawnSync15("crontab", ["-l"], { encoding: "utf8" }).stdout ?? "" : "";
33348
33415
  const schedulerAbsent = o.host !== "windows" ? !schedulerInstalled(planInstall(cfg.ship, CREW_HOME, o.host, detectSystemd(), "run", installContext()), unitExists, crontab) : true;
33349
33416
  const plan = planFix({ routes, schedulerAbsent, host: o.host });
@@ -33373,7 +33440,7 @@ if (command === "passenger-sync-daemon") {
33373
33440
  changed2.push(`refreshed the connect snapshot for ${a.route} (\`crew connect\`)${rel.status === 0 ? " and reloaded the daemon" : "; `crew reload` failed \u2014 run it by hand"}`);
33374
33441
  } else if (a.kind === "enable") {
33375
33442
  if (prompter && !await prompter.confirm(`Route ${a.route} passes every check \u2014 set enabled: true in ${cfg.configFile}?`, false)) continue;
33376
- writeFileSync45(cfg.configFile, planEnable(readFileSync58(cfg.configFile, "utf8"), a.route));
33443
+ writeFileSync46(cfg.configFile, planEnable(readFileSync59(cfg.configFile, "utf8"), a.route));
33377
33444
  enabledSound.add(a.route);
33378
33445
  changed2.push(`enabled route ${a.route} in ${cfg.configFile}`);
33379
33446
  } else {
@@ -33626,7 +33693,7 @@ ${changed2.map((c) => ` - ${c}
33626
33693
  harnessBin: "claude",
33627
33694
  ...contract.sandboxNetwork ? { extraHosts: contract.sandboxNetwork.hosts, toolchains: contract.sandboxNetwork.toolchains } : {}
33628
33695
  },
33629
- policyFile: join67(cfg.ship.stateDir, "release", `${target.name}.policy.yaml`),
33696
+ policyFile: join68(cfg.ship.stateDir, "release", `${target.name}.policy.yaml`),
33630
33697
  repo: mirror,
33631
33698
  origin: forgeDescriptorFor(forgeHost).httpsUrl(mirror.host, mirror.path),
33632
33699
  base: effective.branch.base,
@@ -35049,7 +35116,7 @@ ${f2.tail.trimEnd()}
35049
35116
  logFile: cfg.ship.logFile
35050
35117
  });
35051
35118
  }
35052
- const watchPaths = isCompiledBinary(import.meta.url) ? [process.execPath] : [join67(CREW_HOME, "src"), join67(CREW_HOME, "dist"), join67(CREW_HOME, "bin")];
35119
+ const watchPaths = isCompiledBinary(import.meta.url) ? [process.execPath] : [join68(CREW_HOME, "src"), join68(CREW_HOME, "dist"), join68(CREW_HOME, "bin")];
35053
35120
  const configPaths = daemonConfigPaths(cfg);
35054
35121
  watchPaths.push(...configPaths);
35055
35122
  noteDaemonStarted(cfg.ship.stateDir);
@@ -35358,10 +35425,10 @@ ${f2.tail.trimEnd()}
35358
35425
  for (const w of result.warnings) emit.warn(w);
35359
35426
  if (!dryRun) {
35360
35427
  const resolvedPath = resolvedPathFor(cfg.ship.stateDir, target.route);
35361
- const raw = existsSync60(resolvedPath) ? JSON.parse(readFileSync58(resolvedPath, "utf8")) : {};
35428
+ const raw = existsSync61(resolvedPath) ? JSON.parse(readFileSync59(resolvedPath, "utf8")) : {};
35362
35429
  raw.agentSkills = result.agentSkills;
35363
35430
  mkdirSync44(dirOf2(resolvedPath), { recursive: true });
35364
- writeFileSync45(resolvedPath, `${JSON.stringify(raw, null, 2)}
35431
+ writeFileSync46(resolvedPath, `${JSON.stringify(raw, null, 2)}
35365
35432
  `);
35366
35433
  }
35367
35434
  if (result.outcomes.some((o) => o.action === "diverged")) process.exitCode = 1;
@@ -35382,7 +35449,7 @@ ${f2.tail.trimEnd()}
35382
35449
  throw e;
35383
35450
  }
35384
35451
  const oldName = cfg.ship.name;
35385
- writeFileSync45(cfg.configFile, setShipNameInYaml(readFileSync58(cfg.configFile, "utf8"), newName));
35452
+ writeFileSync46(cfg.configFile, setShipNameInYaml(readFileSync59(cfg.configFile, "utf8"), newName));
35386
35453
  cfg.ship.name = newName;
35387
35454
  let renameMachineId;
35388
35455
  try {
@@ -35429,14 +35496,14 @@ ${f2.tail.trimEnd()}
35429
35496
  process.exit(2);
35430
35497
  };
35431
35498
  if (sub !== "add" && sub !== "list" && sub !== "clone" && sub !== "hooks" && sub !== "check") usage2();
35432
- const configText = readFileSync58(cfg.configFile, "utf8");
35499
+ const configText = readFileSync59(cfg.configFile, "utf8");
35433
35500
  if (sub === "check") {
35434
35501
  try {
35435
35502
  const routeArg = value("route") ?? positional[2];
35436
35503
  const found = cfg.routes.find((r) => r.route === routeArg);
35437
35504
  if (!found) throw new ReposError(`no route "${routeArg}" in the config (have: ${cfg.routes.map((r) => r.route).join(", ") || "none"})`);
35438
35505
  const named2 = value("route") ? void 0 : positional[3];
35439
- const dir = named2 ? repoDirOf(configText, dirname38(cfg.configFile), found.route, named2) : resolvePath(positional[value("route") ? 2 : 3] ?? ".");
35506
+ const dir = named2 ? repoDirOf(configText, dirname39(cfg.configFile), found.route, named2) : resolvePath(positional[value("route") ? 2 : 3] ?? ".");
35440
35507
  const target = reposOf(found).find((t) => resolvePath(t.dir) === dir || t.name === named2);
35441
35508
  const o = target ? found.repoOverrides[target.name] : void 0;
35442
35509
  runReposCheck(dir, {
@@ -35458,9 +35525,9 @@ ${f2.tail.trimEnd()}
35458
35525
  if (sub === "hooks") {
35459
35526
  try {
35460
35527
  const a = parseHooksArgs(positional.slice(2), routeNamesOf(configText));
35461
- const dir = repoDirOf(configText, dirname38(cfg.configFile), a.route, a.name);
35462
- if (!existsSync60(dir)) throw new ReposError(`${dir} does not exist on disk`);
35463
- const files = { exists: (r) => existsSync60(resolvePath(dir, r)), list: (r) => {
35528
+ const dir = repoDirOf(configText, dirname39(cfg.configFile), a.route, a.name);
35529
+ if (!existsSync61(dir)) throw new ReposError(`${dir} does not exist on disk`);
35530
+ const files = { exists: (r) => existsSync61(resolvePath(dir, r)), list: (r) => {
35464
35531
  try {
35465
35532
  return readdirSync22(resolvePath(dir, r));
35466
35533
  } catch {
@@ -35468,7 +35535,7 @@ ${f2.tail.trimEnd()}
35468
35535
  }
35469
35536
  }, read: (r) => {
35470
35537
  try {
35471
- return readFileSync58(resolvePath(dir, r), "utf8");
35538
+ return readFileSync59(resolvePath(dir, r), "utf8");
35472
35539
  } catch {
35473
35540
  return void 0;
35474
35541
  }
@@ -35510,19 +35577,19 @@ ${f2.tail.trimEnd()}
35510
35577
  let cleared;
35511
35578
  if (clear2) {
35512
35579
  const plan = clearRouteHooks(configText, a.route, a.name);
35513
- if (plan.removed.length > 0) writeFileSync45(cfg.configFile, plan.text);
35580
+ if (plan.removed.length > 0) writeFileSync46(cfg.configFile, plan.text);
35514
35581
  cleared = { file: cfg.configFile, removed: plan.removed };
35515
35582
  }
35516
35583
  if (write && suggestion.source === null && recipeIds.length === 0 && hookSpecs.length === 0) throw new ReposError(`nothing to write: ${suggestion.notes[0]}`);
35517
35584
  if (write === "route") {
35518
35585
  const plan = planRouteHooks(configText, a.route, a.name, picked.hooks, { replace: flag("replace") });
35519
- writeFileSync45(cfg.configFile, plan.text);
35586
+ writeFileSync46(cfg.configFile, plan.text);
35520
35587
  written = { target: "route", file: cfg.configFile, hooks: plan.written, kept: plan.kept, replaced: plan.replaced };
35521
35588
  } else if (write === "repo") {
35522
35589
  const have = existingRepoConfig(files);
35523
35590
  if (have) throw new ReposError(`${resolvePath(dir, have)} already exists; not overwriting it`);
35524
35591
  const file = resolvePath(dir, ".crew.yaml");
35525
- writeFileSync45(file, starterRepoConfig(picked.hooks, picked.release), { flag: "wx" });
35592
+ writeFileSync46(file, starterRepoConfig(picked.hooks, picked.release), { flag: "wx" });
35526
35593
  written = { target: "repo", file, hooks: Object.keys(picked.hooks), kept: [], replaced: [] };
35527
35594
  }
35528
35595
  if (flag("json")) {
@@ -35575,7 +35642,7 @@ ${f2.tail.trimEnd()}
35575
35642
  if (sub === "list" && !routeName) usage2();
35576
35643
  if (sub === "add") {
35577
35644
  try {
35578
- const a = parseAddArgs(positional.slice(2), routeNamesOf(configText), (p) => existsSync60(resolvePath(p.replace(/^~(?=\/|$)/, homedir11()))));
35645
+ const a = parseAddArgs(positional.slice(2), routeNamesOf(configText), (p) => existsSync61(resolvePath(p.replace(/^~(?=\/|$)/, homedir11()))));
35579
35646
  routeName = a.route;
35580
35647
  addPath = a.path;
35581
35648
  addName = a.name;
@@ -35601,7 +35668,7 @@ ${f2.tail.trimEnd()}
35601
35668
  const resolvedFile = resolvedPathFor(cfg.ship.stateDir, routeName);
35602
35669
  if (sub === "list" || sub === "add") {
35603
35670
  const liveRoute = cfg.routes.find((r) => r.route === routeName);
35604
- if (liveRoute?.resolved?.reposModelId && existsSync60(resolvedFile) && !dryRun) {
35671
+ if (liveRoute?.resolved?.reposModelId && existsSync61(resolvedFile) && !dryRun) {
35605
35672
  try {
35606
35673
  await hydrateApiKeys([liveRoute]);
35607
35674
  persistRepoRows(cfg.ship.stateDir, liveRoute.route, await new Tracker(liveRoute, cfg.ship).repoRowsForMap());
@@ -35610,16 +35677,16 @@ ${f2.tail.trimEnd()}
35610
35677
  }
35611
35678
  }
35612
35679
  let resolvedRemotes;
35613
- if (existsSync60(resolvedFile)) {
35680
+ if (existsSync61(resolvedFile)) {
35614
35681
  try {
35615
- resolvedRemotes = JSON.parse(readFileSync58(resolvedFile, "utf8"));
35682
+ resolvedRemotes = JSON.parse(readFileSync59(resolvedFile, "utf8"));
35616
35683
  } catch {
35617
35684
  }
35618
35685
  }
35619
35686
  const originOf = (dir) => gitOk(dir, ["remote", "get-url", "origin"]) ?? void 0;
35620
35687
  const text2 = configText;
35621
- const base = dirname38(cfg.configFile);
35622
- const isCheckout = (d) => existsSync60(`${d}/.git`);
35688
+ const base = dirname39(cfg.configFile);
35689
+ const isCheckout = (d) => existsSync61(`${d}/.git`);
35623
35690
  try {
35624
35691
  if (sub === "list") {
35625
35692
  if (flag("json")) {
@@ -35629,12 +35696,12 @@ ${f2.tail.trimEnd()}
35629
35696
  base,
35630
35697
  resolved: resolvedRemotes,
35631
35698
  originOf,
35632
- exists: (d) => existsSync60(d),
35699
+ exists: (d) => existsSync61(d),
35633
35700
  isCheckout,
35634
35701
  repoHasHooks: (d) => REPO_CONFIG_FILENAMES.some((f2) => {
35635
35702
  try {
35636
35703
  const path = resolvePath(d, f2);
35637
- return Object.keys(parseRepoConfig(readFileSync58(path, "utf8"), path).hooks).length > 0;
35704
+ return Object.keys(parseRepoConfig(readFileSync59(path, "utf8"), path).hooks).length > 0;
35638
35705
  } catch {
35639
35706
  return false;
35640
35707
  }
@@ -35651,7 +35718,7 @@ ${f2.tail.trimEnd()}
35651
35718
  for (const r of repos) {
35652
35719
  const origin2 = originOf(r.dir);
35653
35720
  const row = matchRepoName(origin2, resolvedRemotes);
35654
- const note = !existsSync60(r.dir) ? "missing on disk" : row ? `Repos row: ${row}` : `no Repos row matches ${normalizeRemote2(origin2) ?? "this checkout (no origin remote)"}`;
35721
+ const note = !existsSync61(r.dir) ? "missing on disk" : row ? `Repos row: ${row}` : `no Repos row matches ${normalizeRemote2(origin2) ?? "this checkout (no origin remote)"}`;
35655
35722
  process.stdout.write(`${r.name} ${r.dir} ${note}
35656
35723
  `);
35657
35724
  }
@@ -35663,9 +35730,9 @@ ${f2.tail.trimEnd()}
35663
35730
  ` : `${human}
35664
35731
  `);
35665
35732
  const plan2 = planRepoClone({ text: text2, base, route: routeName, name: addName, resolved: resolvedRemotes, dir: value("dir"), isCheckout });
35666
- if (existsSync60(plan2.target) && (existsSync60(`${plan2.target}/.git`) || readdirSync22(plan2.target).length > 0)) {
35733
+ if (existsSync61(plan2.target) && (existsSync61(`${plan2.target}/.git`) || readdirSync22(plan2.target).length > 0)) {
35667
35734
  throw new ReposError(
35668
- existsSync60(`${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`
35735
+ existsSync61(`${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`
35669
35736
  );
35670
35737
  }
35671
35738
  if (dryRun) {
@@ -35683,13 +35750,13 @@ ${f2.tail.trimEnd()}
35683
35750
  throw new ReposError(`${e.message}${authHint}
35684
35751
  crew.yaml was not changed`);
35685
35752
  }
35686
- writeFileSync45(cfg.configFile, plan2.text);
35753
+ writeFileSync46(cfg.configFile, plan2.text);
35687
35754
  if (plan2.droppedDir) emit.warn(`crew repos: dropped dir: ${plan2.droppedDir} from route ${routeName} \u2014 it is not a checkout (the clone base); checkouts now live under repos:`);
35688
35755
  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}`);
35689
35756
  break;
35690
35757
  }
35691
35758
  const target = resolvePath(addPath.replace(/^~(?=\/|$)/, homedir11()));
35692
- if (!existsSync60(target)) throw new ReposError(`${target} does not exist`);
35759
+ if (!existsSync61(target)) throw new ReposError(`${target} does not exist`);
35693
35760
  let top;
35694
35761
  try {
35695
35762
  top = git(target, ["rev-parse", "--show-toplevel"]);
@@ -35773,15 +35840,15 @@ would need a project first: the tracker has none (\`crew projects add NAME --pre
35773
35840
  const created = await rowTracker.createRepoRow(rowPayload);
35774
35841
  process.stdout.write(`created Repos row ${String(rowPayload.name)} (${String(rowPayload.remote)}) ${created.id}
35775
35842
  `);
35776
- if (existsSync60(resolvedFile)) {
35777
- const raw = JSON.parse(readFileSync58(resolvedFile, "utf8"));
35843
+ if (existsSync61(resolvedFile)) {
35844
+ const raw = JSON.parse(readFileSync59(resolvedFile, "utf8"));
35778
35845
  raw.repoNames = { ...raw.repoNames, [created.id]: String(rowPayload.name) };
35779
35846
  raw.repoRemotes = { ...raw.repoRemotes, [created.id]: String(rowPayload.remote) };
35780
- writeFileSync45(resolvedFile, `${JSON.stringify(raw, null, 2)}
35847
+ writeFileSync46(resolvedFile, `${JSON.stringify(raw, null, 2)}
35781
35848
  `);
35782
35849
  }
35783
35850
  }
35784
- writeFileSync45(cfg.configFile, plan.text);
35851
+ writeFileSync46(cfg.configFile, plan.text);
35785
35852
  process.stdout.write(`added ${top} to ${routeName} as ${plan.mode === "dir" ? "dir" : `repos.${plan.name}`} in ${cfg.configFile}
35786
35853
  `);
35787
35854
  } catch (e) {
@@ -36147,7 +36214,7 @@ Waiting for approval`
36147
36214
  ${found.problems.map((p) => ` - ${p}`).join("\n")}`, "fix the problems above, then run `crew connect` again");
36148
36215
  }
36149
36216
  if (found.shipNameAdopted && !dryRun) {
36150
- writeFileSync45(cfg.configFile, setShipNameInYaml(readFileSync58(cfg.configFile, "utf8"), found.shipNameAdopted));
36217
+ writeFileSync46(cfg.configFile, setShipNameInYaml(readFileSync59(cfg.configFile, "utf8"), found.shipNameAdopted));
36151
36218
  cfg.ship.name = found.shipNameAdopted;
36152
36219
  }
36153
36220
  if (found.shipRow) {
@@ -36188,10 +36255,10 @@ ${found.problems.map((p) => ` - ${p}`).join("\n")}`, "fix the problems above, t
36188
36255
  }
36189
36256
  }
36190
36257
  let previous;
36191
- const hadPreviousFile = existsSync60(resolvedPath);
36258
+ const hadPreviousFile = existsSync61(resolvedPath);
36192
36259
  if (hadPreviousFile) {
36193
36260
  try {
36194
- previous = JSON.parse(readFileSync58(resolvedPath, "utf8"));
36261
+ previous = JSON.parse(readFileSync59(resolvedPath, "utf8"));
36195
36262
  } catch {
36196
36263
  }
36197
36264
  }
@@ -36337,12 +36404,12 @@ ${found.problems.map((p) => ` - ${p}`).join("\n")}`, "fix the problems above, t
36337
36404
  process.stderr.write(`(dry run) would write resolved ids to ${resolvedPath}
36338
36405
  `);
36339
36406
  } else {
36340
- mkdirSync44(dirname38(resolvedPath), { recursive: true });
36407
+ mkdirSync44(dirname39(resolvedPath), { recursive: true });
36341
36408
  if (hadPreviousFile) copyFileSync2(resolvedPath, `${resolvedPath}.bak`);
36342
36409
  const tmpPath = `${resolvedPath}.tmp${process.pid}`;
36343
- writeFileSync45(tmpPath, `${JSON.stringify(resolved, null, 2)}
36410
+ writeFileSync46(tmpPath, `${JSON.stringify(resolved, null, 2)}
36344
36411
  `);
36345
- renameSync10(tmpPath, resolvedPath);
36412
+ renameSync11(tmpPath, resolvedPath);
36346
36413
  emit.note(`Resolved ids written to ${resolvedPath}`);
36347
36414
  }
36348
36415
  let mintOutcomes = [];
@@ -36409,8 +36476,8 @@ ${found.problems.map((p) => ` - ${p}`).join("\n")}`, "fix the problems above, t
36409
36476
  process.stderr.write(`(dry run) would write the API key to ${apiKeyFile}
36410
36477
  `);
36411
36478
  } else {
36412
- mkdirSync44(dirname38(apiKeyFile), { recursive: true });
36413
- writeFileSync45(apiKeyFile, `${apiKeyVar}=${apiKey}
36479
+ mkdirSync44(dirname39(apiKeyFile), { recursive: true });
36480
+ writeFileSync46(apiKeyFile, `${apiKeyVar}=${apiKey}
36414
36481
  `, { mode: 384 });
36415
36482
  routineLine(`API key written to ${apiKeyFile}`);
36416
36483
  }
@@ -36434,6 +36501,17 @@ ${found.problems.map((p) => ` - ${p}`).join("\n")}`, "fix the problems above, t
36434
36501
  }
36435
36502
  );
36436
36503
  let wroteConfig = false;
36504
+ const routeAlreadyInConfig = cfg.routes.some((r) => r.route === route3);
36505
+ let appendReason;
36506
+ let appendedToExisting = false;
36507
+ if (!wizard && !routeAlreadyInConfig) {
36508
+ const appended = planAppendToConfig(CREW_HOME, cfg.configFile, route3, routeBlock, keyPersisted);
36509
+ if (!appended.ok) appendReason = appended.reason;
36510
+ else if (!dryRun) {
36511
+ replaceFileKeepingMode(cfg.configFile, appended.text);
36512
+ appendedToExisting = true;
36513
+ } else appendReason = "dry-run";
36514
+ }
36437
36515
  if (writeFirstRun) {
36438
36516
  wroteConfig = writeNewConfig(wizard.configPath, renderFullConfig(wizard.answers, routeBlock));
36439
36517
  if (!wroteConfig) emit.warn(`${wizard.configPath} appeared while connecting \u2014 leaving it alone`);
@@ -36445,8 +36523,10 @@ ${found.problems.map((p) => ` - ${p}`).join("\n")}`, "fix the problems above, t
36445
36523
  connectEvents.emit("config", `${wizard.configPath} appeared while connecting; left alone`, { written: false, path: wizard.configPath, reason: "appeared while connecting" });
36446
36524
  } else if (wizard) {
36447
36525
  connectEvents.emit("config", `no key file or keychain entry to name; ${wizard.configPath} not written`, { written: false, path: wizard.configPath, reason: "no-key" });
36526
+ } else if (appendedToExisting) {
36527
+ connectEvents.emit("config", `added the route ${route3} to ${cfg.configFile}, disabled`, { written: true, path: cfg.configFile, appended: true });
36448
36528
  } else {
36449
- connectEvents.emit("config", `${cfg.configFile} already exists; left alone`, { written: false, path: cfg.configFile, reason: "exists" });
36529
+ connectEvents.emit("config", `${cfg.configFile} already exists; left alone`, { written: false, path: cfg.configFile, reason: appendReason ? `exists: ${appendReason}` : "exists" });
36450
36530
  }
36451
36531
  }
36452
36532
  const routeInConfig = cfg.routes.some((r) => r.route === route3);
@@ -36459,7 +36539,13 @@ ${found.problems.map((p) => ` - ${p}`).join("\n")}`, "fix the problems above, t
36459
36539
  keys: mintOutcomes.map((m) => ({ role: m.role, action: m.action }))
36460
36540
  }) : "";
36461
36541
  if (routeInConfig) (connectEvents.json ? process.stderr : process.stdout).write(existingReport);
36462
- else if (!wroteConfig) (connectEvents.json ? process.stderr : process.stdout).write(routeBlock);
36542
+ else if (appendedToExisting) {
36543
+ (connectEvents.json ? process.stderr : process.stdout).write(`Added the route ${route3} to ${cfg.configFile}, disabled. Set \`enabled: true\` on it once \`crew doctor ${route3}\` is green.
36544
+ `);
36545
+ } else if (dryRun && appendReason === "dry-run") {
36546
+ (connectEvents.json ? process.stderr : process.stdout).write(`(dry run) would add the route ${route3} to ${cfg.configFile}, disabled.
36547
+ `);
36548
+ } else if (!wroteConfig) (connectEvents.json ? process.stderr : process.stdout).write(routeBlock);
36463
36549
  if (!flag("no-mcp") && apiKey) {
36464
36550
  const replace = value("mcp") === "replace";
36465
36551
  const seen = /* @__PURE__ */ new Set();
@@ -36509,6 +36595,8 @@ ${found.problems.map((p) => ` - ${p}`).join("\n")}`);
36509
36595
  }));
36510
36596
  if (!operator) process.stderr.write(` Also set operator in ${resolvedPath} before arming it.
36511
36597
  `);
36598
+ } else if (appendedToExisting) {
36599
+ if (!operator) emit.warn(`no operator resolved: set it in ${resolvedPath} before arming this route`);
36512
36600
  } else if (routeInConfig) {
36513
36601
  if (!operator) emit.warn(`no operator resolved: set it in ${resolvedPath} before arming this route`);
36514
36602
  } else if (operator) {
@@ -37062,10 +37150,10 @@ ${found.problems.map((p) => ` - ${p}`).join("\n")}`);
37062
37150
  startupSeconds: cfg.ship.intelStartupSeconds,
37063
37151
  prepare: async (path) => {
37064
37152
  for (const f2 of repoWt.config.worktrees.copy) {
37065
- const src = join67(repoWt.dir, f2);
37066
- if (!existsSync60(src) || existsSync60(join67(path, f2))) continue;
37067
- mkdirSync44(dirOf2(join67(path, f2)), { recursive: true });
37068
- copyFileSync2(src, join67(path, f2));
37153
+ const src = join68(repoWt.dir, f2);
37154
+ if (!existsSync61(src) || existsSync61(join68(path, f2))) continue;
37155
+ mkdirSync44(dirOf2(join68(path, f2)), { recursive: true });
37156
+ copyFileSync2(src, join68(path, f2));
37069
37157
  }
37070
37158
  const setup = repoWt.config.hooks.setup;
37071
37159
  return setup ? runScript(setup, { cwd: path, shell: shellWt }) : null;
@@ -37289,7 +37377,7 @@ ${found.problems.map((p) => ` - ${p}`).join("\n")}`);
37289
37377
  const shellR = hit && resolveShell(hit.repo.config.shell ?? cfg.ship.shell);
37290
37378
  const resumed = await runPeriscopeResume({
37291
37379
  find: async () => hit && { row: hit.row, tag: hit.tag },
37292
- worktreeExists: (p) => existsSync60(p),
37380
+ worktreeExists: (p) => existsSync61(p),
37293
37381
  prepareDropFile,
37294
37382
  startProxy: (wt, url, n) => launchProxy(crewInvocation(CREW_HOME), wt, url, Number(n), { host: hit.row.host || "localhost", inject: hit.repo.config.periscope?.inspector !== "repo" }),
37295
37383
  relay: hit && previewRelayFor(hit.route) && {
@@ -37392,10 +37480,10 @@ ${where.join("\n")}`);
37392
37480
  },
37393
37481
  prepare: async (path) => {
37394
37482
  for (const f2 of repoP.config.worktrees.copy) {
37395
- const src = join67(repoP.dir, f2);
37396
- if (!existsSync60(src)) continue;
37397
- mkdirSync44(dirOf2(join67(path, f2)), { recursive: true });
37398
- copyFileSync2(src, join67(path, f2));
37483
+ const src = join68(repoP.dir, f2);
37484
+ if (!existsSync61(src)) continue;
37485
+ mkdirSync44(dirOf2(join68(path, f2)), { recursive: true });
37486
+ copyFileSync2(src, join68(path, f2));
37399
37487
  }
37400
37488
  const setup = repoP.config.hooks.setup;
37401
37489
  return setup ? runScript(setup, { cwd: path, shell: shellP, onLine: (l) => {
@@ -37800,7 +37888,7 @@ ${where.join("\n")}`);
37800
37888
  };
37801
37889
  const droppedRoutes = [];
37802
37890
  try {
37803
- const rawCfg = parseYaml3(readFileSync58(cfg.configFile, "utf8"));
37891
+ const rawCfg = parseYaml3(readFileSync59(cfg.configFile, "utf8"));
37804
37892
  for (const r of rawCfg?.routes ?? []) {
37805
37893
  if (typeof r?.route !== "string" || cfg.routes.some((x) => x.route === r.route)) continue;
37806
37894
  try {
@@ -37864,7 +37952,7 @@ ${where.join("\n")}`);
37864
37952
  break;
37865
37953
  }
37866
37954
  mkdirSync44(cfg.ship.stateDir, { recursive: true });
37867
- writeFileSync45(sentinel, `${(/* @__PURE__ */ new Date()).toISOString()}
37955
+ writeFileSync46(sentinel, `${(/* @__PURE__ */ new Date()).toISOString()}
37868
37956
  `);
37869
37957
  process.stdout.write(
37870
37958
  "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"
@@ -37926,7 +38014,7 @@ ${where.join("\n")}`);
37926
38014
  }
37927
38015
  case "log": {
37928
38016
  try {
37929
- const text2 = readFileSync58(cfg.ship.logFile, "utf8").split("\n");
38017
+ const text2 = readFileSync59(cfg.ship.logFile, "utf8").split("\n");
37930
38018
  process.stdout.write(`${text2.slice(-(Number(value("tail")) || 40)).join("\n")}
37931
38019
  `);
37932
38020
  } catch {
@@ -37950,8 +38038,8 @@ ${where.join("\n")}`);
37950
38038
  };
37951
38039
  if (!route2.resolved) fail2(`route ${route2.route} is not connected \u2014 run \`crew connect\` first`);
37952
38040
  const tracker = new Tracker(route2, cfg.ship);
37953
- const configText = readFileSync58(cfg.configFile, "utf8");
37954
- const cfgBase = dirname38(cfg.configFile);
38041
+ const configText = readFileSync59(cfg.configFile, "utf8");
38042
+ const cfgBase = dirname39(cfg.configFile);
37955
38043
  const configured2 = configuredRepos(configText, route2.route, cfgBase);
37956
38044
  const dir = configured2.find((r) => r.name === SAMPLE_REPO)?.dir ?? sampleDir(configured2.map((r) => r.dir), route2.reposBasePath, route2.route.split("/")[0]);
37957
38045
  const resolvedFile = resolvedPathFor(cfg.ship.stateDir, route2.route);
@@ -37979,7 +38067,7 @@ ${where.join("\n")}`);
37979
38067
  }
37980
38068
  if (configured2.some((r) => r.dir === dir)) {
37981
38069
  try {
37982
- writeFileSync45(cfg.configFile, planRepoRemove(configText, cfgBase, route2.route, dir).text);
38070
+ writeFileSync46(cfg.configFile, planRepoRemove(configText, cfgBase, route2.route, dir).text);
37983
38071
  } catch (e) {
37984
38072
  if (e instanceof ReposError) fail2(e.message);
37985
38073
  throw e;
@@ -37987,29 +38075,29 @@ ${where.join("\n")}`);
37987
38075
  }
37988
38076
  if (row) {
37989
38077
  await tracker.deleteRepoRow(row.id);
37990
- if (existsSync60(resolvedFile)) {
37991
- const raw = JSON.parse(readFileSync58(resolvedFile, "utf8"));
38078
+ if (existsSync61(resolvedFile)) {
38079
+ const raw = JSON.parse(readFileSync59(resolvedFile, "utf8"));
37992
38080
  if (raw.repoNames) delete raw.repoNames[row.id];
37993
38081
  if (raw.repoRemotes) delete raw.repoRemotes[row.id];
37994
- writeFileSync45(resolvedFile, `${JSON.stringify(raw, null, 2)}
38082
+ writeFileSync46(resolvedFile, `${JSON.stringify(raw, null, 2)}
37995
38083
  `);
37996
38084
  }
37997
38085
  }
37998
- if (existsSync60(join67(dir, ".git")) && basename17(dir) === SAMPLE_REPO) rmSync27(dir, { recursive: true, force: true });
38086
+ if (existsSync61(join68(dir, ".git")) && basename18(dir) === SAMPLE_REPO) rmSync27(dir, { recursive: true, force: true });
37999
38087
  say("removed", { dir, closed }, `removed the sample repo${closed.length ? `, closed ${closed.join(", ")}` : ""}`);
38000
38088
  break;
38001
38089
  }
38002
38090
  const projectId = route2.resolved.areaId ?? resolveRepoProject(await tracker.projectRows(), value("project"));
38003
- const fresh = !existsSync60(join67(dir, ".git"));
38004
- if (existsSync60(dir) && fresh && readdirSync22(dir).length > 0) fail2(`${dir} exists and is not a git checkout \u2014 move it aside`);
38091
+ const fresh = !existsSync61(join68(dir, ".git"));
38092
+ if (existsSync61(dir) && fresh && readdirSync22(dir).length > 0) fail2(`${dir} exists and is not a git checkout \u2014 move it aside`);
38005
38093
  if (dryRun) {
38006
38094
  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`);
38007
38095
  break;
38008
38096
  }
38009
38097
  if (fresh) {
38010
38098
  mkdirSync44(dir, { recursive: true });
38011
- writeFileSync45(join67(dir, "README.md"), SAMPLE_README);
38012
- writeFileSync45(join67(dir, ".crew.yaml"), SAMPLE_CREW_YAML);
38099
+ writeFileSync46(join68(dir, "README.md"), SAMPLE_README);
38100
+ writeFileSync46(join68(dir, ".crew.yaml"), SAMPLE_CREW_YAML);
38013
38101
  const g = (...a) => {
38014
38102
  const r = spawnSync15("git", a, { cwd: dir, encoding: "utf8" });
38015
38103
  if (r.status !== 0) fail2(`git ${a[0]} failed in ${dir}: ${(r.stderr || r.stdout).trim()}`);
@@ -38027,17 +38115,17 @@ ${where.join("\n")}`);
38027
38115
  spec: { platform: "unix", releaseMode: "integrate", ciProvider: "none" }
38028
38116
  });
38029
38117
  repoId = (await tracker.createRepoRow(payload)).id;
38030
- if (existsSync60(resolvedFile)) {
38031
- const raw = JSON.parse(readFileSync58(resolvedFile, "utf8"));
38118
+ if (existsSync61(resolvedFile)) {
38119
+ const raw = JSON.parse(readFileSync59(resolvedFile, "utf8"));
38032
38120
  raw.repoNames = { ...raw.repoNames, [repoId]: SAMPLE_REPO };
38033
38121
  raw.repoRemotes = { ...raw.repoRemotes, [repoId]: SAMPLE_REMOTE };
38034
- writeFileSync45(resolvedFile, `${JSON.stringify(raw, null, 2)}
38122
+ writeFileSync46(resolvedFile, `${JSON.stringify(raw, null, 2)}
38035
38123
  `);
38036
38124
  }
38037
38125
  }
38038
38126
  if (!configured2.some((r) => r.dir === dir)) {
38039
38127
  try {
38040
- writeFileSync45(cfg.configFile, planRepoAdd({ text: configText, base: cfgBase, route: route2.route, path: dir, name: SAMPLE_REPO }).text);
38128
+ writeFileSync46(cfg.configFile, planRepoAdd({ text: configText, base: cfgBase, route: route2.route, path: dir, name: SAMPLE_REPO }).text);
38041
38129
  } catch (e) {
38042
38130
  if (e instanceof ReposError) fail2(e.message);
38043
38131
  throw e;
@@ -38369,7 +38457,7 @@ ${where.join("\n")}`);
38369
38457
  // `synthesis-tabl-123`. `worktreePrefix` above is kept for
38370
38458
  // config-provenance display; this is the field that actually
38371
38459
  // describes where a worktree lands by default.
38372
- worktreeDirPattern: r.config.worktrees.name ?? (r.config.provenance["worktrees.prefix"] !== "default" ? `${r.config.worktrees.prefix}<number>` : `${basename17(r.dir.replace(/[/\\]+$/, ""))}-<branch>`),
38460
+ worktreeDirPattern: r.config.worktrees.name ?? (r.config.provenance["worktrees.prefix"] !== "default" ? `${r.config.worktrees.prefix}<number>` : `${basename18(r.dir.replace(/[/\\]+$/, ""))}-<branch>`),
38373
38461
  worktreeParent: resolvePath(r.dir, "..")
38374
38462
  })),
38375
38463
  waiting: waiting ? { ticket: waiting.ticket, since: waiting.since, streak: fairness.streak() } : null
@@ -38472,7 +38560,7 @@ ${where.join("\n")}`);
38472
38560
  plan,
38473
38561
  label,
38474
38562
  uid: process.getuid?.() ?? 0,
38475
- system: plan.mechanism === "systemd" && existsSync60(systemUnitPathFor(label)),
38563
+ system: plan.mechanism === "systemd" && existsSync61(systemUnitPathFor(label)),
38476
38564
  stamp: readDaemonStamp(cfg.ship.stateDir)
38477
38565
  });
38478
38566
  })();
@@ -38488,7 +38576,7 @@ ${where.join("\n")}`);
38488
38576
  }
38489
38577
  for (const r of repos) {
38490
38578
  const remote = r.config.branch.remote;
38491
- if (existsSync60(r.dir)) {
38579
+ if (existsSync61(r.dir)) {
38492
38580
  pushAuth.push({
38493
38581
  route: c.route,
38494
38582
  repo: r.name,
@@ -38577,7 +38665,7 @@ ${where.join("\n")}`);
38577
38665
  else passed++;
38578
38666
  }
38579
38667
  if (staleBundle) problems.push({ severity: "blocker", kind: "stale_bundle", message: staleBundle.message, remedy: "npm run build" });
38580
- const runtimeDir = runtimeDirWarning(process.platform, process.getuid?.() ?? null, existsSync60, userInfo2().username);
38668
+ const runtimeDir = runtimeDirWarning(process.platform, process.getuid?.() ?? null, existsSync61, userInfo2().username);
38581
38669
  if (runtimeDir) problems.push({ severity: "attention", kind: "runtime_dir_missing", message: runtimeDir });
38582
38670
  if (!flag("offline")) {
38583
38671
  const shipKind = await doctorShipKind(route2, cfg.ship);
@@ -38674,7 +38762,7 @@ routes: ${cfg.routes.map((c) => c.route).join(", ")}
38674
38762
  }
38675
38763
  try {
38676
38764
  const evFile = eventFileFor(cfg.ship.stateDir);
38677
- const evSize = existsSync60(evFile) ? statSync19(evFile).size : 0;
38765
+ const evSize = existsSync61(evFile) ? statSync20(evFile).size : 0;
38678
38766
  R.line(
38679
38767
  evSize > cfg.ship.eventsRotateBytes * 4 ? `events log: WARN ${evFile} is ${Math.round(evSize / 1048576)} MB (> 4x eventsRotateBytes); run \`crew reap\` to rotate it
38680
38768
  ` : "events log: ok\n"
@@ -38685,7 +38773,7 @@ routes: ${cfg.routes.map((c) => c.route).join(", ")}
38685
38773
  const unitPlan = planInstall(cfg.ship, CREW_HOME, host, detectSystemd(), "run", installContext());
38686
38774
  const abandons = unitAbandonsAgents(unitPlan, (p) => {
38687
38775
  try {
38688
- return readFileSync58(p, "utf8");
38776
+ return readFileSync59(p, "utf8");
38689
38777
  } catch {
38690
38778
  return null;
38691
38779
  }
@@ -38700,7 +38788,7 @@ routes: ${cfg.routes.map((c) => c.route).join(", ")}
38700
38788
  const pPlan = planInstall(cfg.ship, CREW_HOME, host, true, "passengers", installContext());
38701
38789
  const keeps = unitAbandonsAgents(pPlan, (p) => {
38702
38790
  try {
38703
- return readFileSync58(p, "utf8");
38791
+ return readFileSync59(p, "utf8");
38704
38792
  } catch {
38705
38793
  return null;
38706
38794
  }
@@ -38714,7 +38802,7 @@ routes: ${cfg.routes.map((c) => c.route).join(", ")}
38714
38802
  if (host === "linux" && detectSystemd()) {
38715
38803
  const ctl = planDaemonControl(CREW_HOME, host, true);
38716
38804
  const unitPlan = planInstall(cfg.ship, CREW_HOME, host, true, "run", installContext());
38717
- if (ctl.statusCommand && unitPlan.unitPaths.some((p) => existsSync60(p))) {
38805
+ if (ctl.statusCommand && unitPlan.unitPaths.some((p) => existsSync61(p))) {
38718
38806
  const st = spawnSync15(ctl.statusCommand[0], ctl.statusCommand.slice(1), { cwd: CREW_HOME, encoding: "utf8" });
38719
38807
  if (!st.error && st.status !== 0) {
38720
38808
  R.line("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");
@@ -38739,8 +38827,8 @@ routes: ${cfg.routes.map((c) => c.route).join(", ")}
38739
38827
  const changed2 = configChangedAfter(daemonConfigPaths(cfg), daemonStartedAt);
38740
38828
  if (changed2) {
38741
38829
  R.line(
38742
- daemonDead ? `daemon config: WARN ${changed2} changed at ${new Date(statSync19(changed2).mtimeMs).toISOString()} \u2014 no daemon is running; the new config applies when it starts
38743
- ` : `daemon config: WARN ${changed2} changed at ${new Date(statSync19(changed2).mtimeMs).toISOString()} but the daemon started at ${new Date(daemonStartedAt).toISOString()} \u2014 run \`crew reload\`
38830
+ daemonDead ? `daemon config: WARN ${changed2} changed at ${new Date(statSync20(changed2).mtimeMs).toISOString()} \u2014 no daemon is running; the new config applies when it starts
38831
+ ` : `daemon config: WARN ${changed2} changed at ${new Date(statSync20(changed2).mtimeMs).toISOString()} but the daemon started at ${new Date(daemonStartedAt).toISOString()} \u2014 run \`crew reload\`
38744
38832
  `
38745
38833
  );
38746
38834
  }
@@ -38773,7 +38861,7 @@ routes: ${cfg.routes.map((c) => c.route).join(", ")}
38773
38861
  for (const r of await resolvedRepos(route2)) {
38774
38862
  const { config } = r;
38775
38863
  R.repo = r.name;
38776
- const worktreePattern = config.worktrees.name ?? (config.provenance["worktrees.prefix"] !== "default" ? `${config.worktrees.prefix}<number>` : `${basename17(r.dir.replace(/[/\\]+$/, ""))}-${effectiveBranchTemplate(config, void 0)}`);
38864
+ const worktreePattern = config.worktrees.name ?? (config.provenance["worktrees.prefix"] !== "default" ? `${config.worktrees.prefix}<number>` : `${basename18(r.dir.replace(/[/\\]+$/, ""))}-${effectiveBranchTemplate(config, void 0)}`);
38777
38865
  R.line(
38778
38866
  `${`repo ${r.name}:`.padEnd(19)}${r.dir}
38779
38867
  worktrees at ../${worktreePattern} (${config.provenance["worktrees.name"] ?? config.provenance["worktrees.prefix"] ?? "default"}), branch ${config.branch.name}