@tablation/crew 0.170.0 → 0.171.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/cli.js +484 -270
  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";
@@ -20576,18 +20576,20 @@ async function checkTrackerInterface(o, deps = {}) {
20576
20576
  clearShipAttention(o.state, mismatchKey);
20577
20577
  return null;
20578
20578
  }
20579
- async function readForRoute(route2, ship) {
20580
- const r = route2.resolved;
20581
- if (!r?.projectId) return { kind: "unreadable" };
20582
- const get2 = async (path) => {
20579
+ function getterFor(route2, ship) {
20580
+ return async (path) => {
20583
20581
  const res = await fetch(`${route2.baseUrl.replace(/\/+$/, "")}/api${path}`, {
20584
20582
  headers: { Authorization: `Bearer ${resolveApiKey(route2)}`, "User-Agent": ship.userAgent }
20585
20583
  });
20586
20584
  if (!res.ok) throw Object.assign(new Error(`HTTP ${res.status}`), { status: res.status });
20587
20585
  return await res.json();
20588
20586
  };
20587
+ }
20588
+ async function readForRoute(route2, ship) {
20589
+ const r = route2.resolved;
20590
+ if (!r?.projectId) return { kind: "unreadable" };
20589
20591
  try {
20590
- return await readInterfaceState(get2, r.workspaceId, r.projectId);
20592
+ return await readInterfaceState(getterFor(route2, ship), r.workspaceId, r.projectId);
20591
20593
  } catch {
20592
20594
  return { kind: "unreadable" };
20593
20595
  }
@@ -20602,19 +20604,137 @@ function interfaceReport(state, o) {
20602
20604
  }
20603
20605
  const lines2 = [];
20604
20606
  const blocking = blockingMessage(state, o.storedMappingKey);
20607
+ const unresolved = state.accepted && state.conforms !== false && !blocking && o.stored && !o.stored.trackerInterface ? "this route was connected before the app declared the interface, so it is still read by default names" : state.accepted && state.conforms !== false && !blocking && o.stored && questionsPartMapped(state.mapping) && !(o.stored.questionsModelId && o.stored.answersModelId) ? "the questions part is declared by the app but not resolved on this ship, so `crew ask` would write nothing" : null;
20608
+ const refreshed = o.stored?.trackerInterface?.mappingKey === mappingKey(state.mapping);
20605
20609
  if (!state.accepted) lines2.push({ line: `work tracker interface: ${versionMismatchMessage(state.version)}`, problem: true });
20606
20610
  else if (state.conforms === false) {
20607
20611
  lines2.push({ line: `work tracker interface ${versionLabel(state.version)}: does not conform`, problem: true });
20608
20612
  for (const d of describeDifferences(state.unmet)) lines2.push({ line: ` - ${d}`, problem: true });
20609
20613
  } else if (blocking) lines2.push({ line: `work tracker interface: ${blocking}`, problem: true });
20614
+ else if (unresolved) lines2.push({
20615
+ line: refreshed ? `work tracker interface: ${unresolved} \u2014 the Questions and Answers tables the app maps were not found in this project, so a refresh cannot resolve them; fix the app's mapping` : `work tracker interface: ${unresolved} \u2014 the daemon refreshes it on its next poll, or run \`crew connect\``,
20616
+ problem: true
20617
+ });
20610
20618
  else lines2.push({ line: `work tracker interface ${versionLabel(state.version)}: ${state.conforms ? "conforms" : "declared (conformance not visible to this key)"}`, problem: false });
20611
20619
  if (o.contractAuthored) lines2.push({ line: `work tracker interface: ${OVERRIDE_IGNORED_MESSAGE}`, problem: false });
20612
20620
  return lines2;
20613
20621
  }
20614
20622
 
20623
+ // src/interface-refresh.ts
20624
+ import { copyFileSync, existsSync as existsSync39, readFileSync as readFileSync41, renameSync as renameSync8, writeFileSync as writeFileSync32 } from "fs";
20625
+ var OPTIONAL_TABLES = [
20626
+ ["ships", "shipsModelId"],
20627
+ ["epics", "epicsModelId"],
20628
+ ["maps", "mapsModelId"],
20629
+ ["periscopes", "periscopesModelId"],
20630
+ ["locks", "locksModelId"]
20631
+ ];
20632
+ function refreshable(state) {
20633
+ return state.kind === "declared" && state.accepted && state.conforms !== false;
20634
+ }
20635
+ function snapshotCurrent(resolved, state) {
20636
+ if (!resolved?.trackerInterface || resolved.trackerInterface.mappingKey !== mappingKey(state.mapping)) return false;
20637
+ return !questionsPartMapped(state.mapping) || !!resolved.questionsModelId && !!resolved.answersModelId;
20638
+ }
20639
+ function planRefresh(resolved, state, models) {
20640
+ const eq2 = (a, b) => a.trim().toLowerCase() === b.trim().toLowerCase();
20641
+ const idOf = (role) => {
20642
+ const name = mappedTableName(state.mapping, role);
20643
+ return name ? models.find((m) => eq2(m.name, name))?.id : void 0;
20644
+ };
20645
+ const declaredContract = contractFromMapping(DEFAULT_CONTRACT, state.mapping);
20646
+ const resolvedStatuses = [.../* @__PURE__ */ new Set([...declaredContract.statuses.resolved, ...resolved.contract?.statuses?.resolved ?? []])];
20647
+ const patch2 = {
20648
+ trackerInterface: { declared: true, version: versionLabel(state.version), mappingKey: mappingKey(state.mapping) },
20649
+ contract: { ...declaredContract, statuses: { ...declaredContract.statuses, resolved: resolvedStatuses } }
20650
+ };
20651
+ const required = {};
20652
+ for (const role of ["issues", "comments", "crew"]) {
20653
+ const id = idOf(role);
20654
+ if (id) required[role] = id;
20655
+ }
20656
+ if (Object.keys(required).length > 0) patch2.models = required;
20657
+ for (const [role, key] of OPTIONAL_TABLES) {
20658
+ const id = idOf(role);
20659
+ if (id) patch2[key] = id;
20660
+ }
20661
+ if (questionsPartMapped(state.mapping)) {
20662
+ const q2 = idOf("questions");
20663
+ const a = idOf("answers");
20664
+ if (q2 && a) {
20665
+ patch2.questionsModelId = q2;
20666
+ patch2.answersModelId = a;
20667
+ }
20668
+ }
20669
+ return patch2;
20670
+ }
20671
+ function mergePatch(raw, patch2) {
20672
+ const { models, ...rest } = patch2;
20673
+ const out = { ...raw, ...rest };
20674
+ if (models) out["models"] = { ...raw["models"], ...models };
20675
+ return out;
20676
+ }
20677
+ function applyToRoute(route2, patch2) {
20678
+ const { models, contract, trackerInterface, ...ids } = patch2;
20679
+ route2.resolved = {
20680
+ ...route2.resolved,
20681
+ ...ids,
20682
+ trackerInterface,
20683
+ contract,
20684
+ ...models ? { models: { ...route2.resolved.models, ...models } } : {}
20685
+ };
20686
+ route2.contract = contract;
20687
+ }
20688
+ var attempted = /* @__PURE__ */ new Set();
20689
+ async function refreshInterfaceSnapshot(o, state, listModels) {
20690
+ const r = o.route.resolved;
20691
+ if (!r || !refreshable(state) || snapshotCurrent(r, state)) return null;
20692
+ const attemptKey = `${o.stateDir}|${o.route.route}|${mappingKey(state.mapping)}`;
20693
+ if (attempted.has(attemptKey)) return null;
20694
+ let models;
20695
+ try {
20696
+ models = await listModels();
20697
+ } catch {
20698
+ return null;
20699
+ }
20700
+ attempted.add(attemptKey);
20701
+ const patch2 = planRefresh(r, state, models);
20702
+ if (o.write !== false) {
20703
+ const path = resolvedPathFor(o.stateDir, o.route.route);
20704
+ if (!existsSync39(path)) return null;
20705
+ let raw;
20706
+ try {
20707
+ raw = JSON.parse(readFileSync41(path, "utf8"));
20708
+ } catch {
20709
+ return null;
20710
+ }
20711
+ const next = `${JSON.stringify(mergePatch(raw, patch2), null, 2)}
20712
+ `;
20713
+ if (next === readFileSync41(path, "utf8")) return null;
20714
+ copyFileSync(path, `${path}.bak`);
20715
+ const tmp = `${path}.tmp${process.pid}`;
20716
+ writeFileSync32(tmp, next);
20717
+ renameSync8(tmp, path);
20718
+ }
20719
+ applyToRoute(o.route, patch2);
20720
+ return patch2;
20721
+ }
20722
+ async function refreshForRoute(route2, ship, write, state) {
20723
+ const live2 = state ?? await readForRoute(route2, ship);
20724
+ const projectId = route2.resolved?.projectId;
20725
+ if (!projectId) return false;
20726
+ const get2 = getterFor(route2, ship);
20727
+ const patch2 = await refreshInterfaceSnapshot(
20728
+ { route: route2, stateDir: ship.stateDir, write },
20729
+ live2,
20730
+ () => get2(`/data-models?projectId=${projectId}`)
20731
+ );
20732
+ return patch2 !== null;
20733
+ }
20734
+
20615
20735
  // src/sandbox-hygiene.ts
20616
20736
  import { execFile as execFile3 } from "child_process";
20617
- import { existsSync as existsSync39, statfsSync as statfsSync2 } from "fs";
20737
+ import { existsSync as existsSync40, statfsSync as statfsSync2 } from "fs";
20618
20738
  import { promisify as promisify3 } from "util";
20619
20739
  var execFileP3 = promisify3(execFile3);
20620
20740
  var REAP_MIN_AGE_MS = 5 * 6e4;
@@ -20757,7 +20877,7 @@ async function realDiskReadings(ship) {
20757
20877
  const paths = ["/"];
20758
20878
  try {
20759
20879
  const root = (await run3(ship.sandbox?.engine ?? DEFAULT_CACHE_SETTINGS.engine, ["info", "--format", "{{.DockerRootDir}}"])).trim();
20760
- if (root && existsSync39(root)) paths.push(root);
20880
+ if (root && existsSync40(root)) paths.push(root);
20761
20881
  } catch {
20762
20882
  }
20763
20883
  return paths.flatMap((path) => {
@@ -20798,7 +20918,7 @@ function diskFullStop(state) {
20798
20918
  }
20799
20919
 
20800
20920
  // src/poll.ts
20801
- import { writeFileSync as writeFileSync32 } from "fs";
20921
+ import { writeFileSync as writeFileSync33 } from "fs";
20802
20922
  import { join as join45 } from "path";
20803
20923
 
20804
20924
  // src/stalled.ts
@@ -20903,6 +21023,11 @@ async function runStalledSweep(o, stalled) {
20903
21023
  }
20904
21024
 
20905
21025
  // src/poll.ts
21026
+ async function readAndRefresh(route2, ship) {
21027
+ const s = await readForRoute(route2, ship);
21028
+ await refreshForRoute(route2, ship, true, s);
21029
+ return s;
21030
+ }
20906
21031
  async function decideCycle(o) {
20907
21032
  const { route: route2, ship, state, emit } = o;
20908
21033
  const tracker = new Tracker(route2, ship);
@@ -21072,7 +21197,7 @@ async function decideCycle(o) {
21072
21197
  emit.emit(`${what}: no longer missing from the scheduler PATH \u2014 stop cleared`, { step: "select" });
21073
21198
  }
21074
21199
  await checkRepoDisks({ state, emit, route: route2, ship });
21075
- const floorStop = await checkCrewFloor({ state, emit, route: route2, ship }) ?? await checkTrackerInterface({ state, emit, route: route2, ship });
21200
+ const floorStop = await checkCrewFloor({ state, emit, route: route2, ship }) ?? await checkTrackerInterface({ state, emit, route: route2, ship }, { read: (r) => readAndRefresh(r, ship) });
21076
21201
  const itemStop = repoStopFor(openShipAttention(state), route2);
21077
21202
  const diskStop = diskFullStop(state);
21078
21203
  const selectionInput = {
@@ -21225,7 +21350,7 @@ ${footprintDigestSection(recorded)}`;
21225
21350
 
21226
21351
  ${body}` : body;
21227
21352
  const path = digestPath(stateDir, routeSlug(o.route.route), role, runId);
21228
- writeFileSync32(path, text2);
21353
+ writeFileSync33(path, text2);
21229
21354
  o.emit.note(`queue digest written for ${role} (${Buffer.byteLength(text2)} bytes)`, {
21230
21355
  data: { role, bytes: Buffer.byteLength(text2) }
21231
21356
  });
@@ -21400,7 +21525,7 @@ async function markCrewAssistedAtLaunch(tracker, route2, role, ticketId, ticket,
21400
21525
  }
21401
21526
 
21402
21527
  // src/repo-refresh.ts
21403
- import { existsSync as existsSync40, mkdirSync as mkdirSync29, readFileSync as readFileSync41, writeFileSync as writeFileSync33 } from "fs";
21528
+ import { existsSync as existsSync41, mkdirSync as mkdirSync29, readFileSync as readFileSync42, writeFileSync as writeFileSync34 } from "fs";
21404
21529
  import { dirname as dirname23 } from "path";
21405
21530
  var REFRESH_COOLDOWN_MS = 2 * 6e4;
21406
21531
  var UNSERVABLE_PASSES_BEFORE_ATTENTION = 3;
@@ -21430,11 +21555,11 @@ function applyRepoRows(resolved, rows) {
21430
21555
  }
21431
21556
  function persistRepoRows(stateDir, routeName, rows) {
21432
21557
  const path = resolvedPathFor(stateDir, routeName);
21433
- if (!existsSync40(path)) return;
21434
- const raw = JSON.parse(readFileSync41(path, "utf8"));
21558
+ if (!existsSync41(path)) return;
21559
+ const raw = JSON.parse(readFileSync42(path, "utf8"));
21435
21560
  applyRepoRows(raw, rows);
21436
21561
  mkdirSync29(dirname23(path), { recursive: true });
21437
- writeFileSync33(path, `${JSON.stringify(raw, null, 2)}
21562
+ writeFileSync34(path, `${JSON.stringify(raw, null, 2)}
21438
21563
  `);
21439
21564
  }
21440
21565
  async function refreshUnknownRepos(o) {
@@ -21725,12 +21850,12 @@ function platformStuckNote(repo, required, ship, issueIds) {
21725
21850
 
21726
21851
  // src/connect-wizard.ts
21727
21852
  import { delimiter, dirname as dirname24, join as join47 } from "path";
21728
- import { accessSync as accessSync3, constants as constants3, existsSync as existsSync41, mkdirSync as mkdirSync30, writeFileSync as writeFileSync34 } from "fs";
21853
+ import { accessSync as accessSync3, constants as constants3, existsSync as existsSync42, mkdirSync as mkdirSync30, writeFileSync as writeFileSync35 } from "fs";
21729
21854
  import { stringify as stringify3 } from "yaml";
21730
21855
  var HOST_PASSENGERS_DOCS_URL = "https://crew.tablation.dev/host-passengers";
21731
21856
  function shouldRunWizard(opts) {
21732
21857
  if (!opts.isTTY) return false;
21733
- const exists = opts.configExists ?? existsSync41;
21858
+ const exists = opts.configExists ?? existsSync42;
21734
21859
  return !configSearchPath(opts.crewHome).some((p) => exists(p));
21735
21860
  }
21736
21861
  function firstRunConfigPath() {
@@ -21810,7 +21935,7 @@ ${routeBlock}`;
21810
21935
  function writeNewConfig(path, text2) {
21811
21936
  mkdirSync30(dirname24(path), { recursive: true });
21812
21937
  try {
21813
- writeFileSync34(path, text2, { mode: 384, flag: "wx" });
21938
+ writeFileSync35(path, text2, { mode: 384, flag: "wx" });
21814
21939
  return true;
21815
21940
  } catch (e) {
21816
21941
  if (e.code === "EEXIST") return false;
@@ -22009,7 +22134,7 @@ async function collectDiagnostics(d) {
22009
22134
  }
22010
22135
 
22011
22136
  // src/release-run.ts
22012
- import { readFileSync as readFileSync42, writeFileSync as writeFileSync35, existsSync as existsSync42, copyFileSync, mkdirSync as mkdirSync31, mkdtempSync as mkdtempSync3, rmSync as rmSync21 } from "fs";
22137
+ import { readFileSync as readFileSync43, writeFileSync as writeFileSync36, existsSync as existsSync43, copyFileSync as copyFileSync2, mkdirSync as mkdirSync31, mkdtempSync as mkdtempSync3, rmSync as rmSync21 } from "fs";
22013
22138
  import { dirname as dirname26, join as join49 } from "path";
22014
22139
  import { tmpdir as tmpdir7, hostname as hostname4 } from "os";
22015
22140
 
@@ -22990,11 +23115,11 @@ async function bump(o, size) {
22990
23115
  }
22991
23116
  const files = o.repo.release.versionFiles.map((f2) => join49(o.cwd, f2));
22992
23117
  const first = files[0];
22993
- if (!existsAt(first, existsSync42)) {
23118
+ if (!existsAt(first, existsSync43)) {
22994
23119
  o.emit.error(`no ${o.repo.release.versionFiles[0]} to read a version from`);
22995
23120
  return null;
22996
23121
  }
22997
- const firstText = readTextAt(first, (p) => readFileSync42(p, "utf8"));
23122
+ const firstText = readTextAt(first, (p) => readFileSync43(p, "utf8"));
22998
23123
  const problem = versionFileProblem(o.repo.release.versionFiles[0], firstText);
22999
23124
  if (problem) {
23000
23125
  o.emit.error(problem);
@@ -23013,13 +23138,13 @@ async function bump(o, size) {
23013
23138
  return version;
23014
23139
  }
23015
23140
  for (const f2 of files) {
23016
- const src = readTextAt(f2, (p) => readFileSync42(p, "utf8"));
23141
+ const src = readTextAt(f2, (p) => readFileSync43(p, "utf8"));
23017
23142
  const out = src.replace(/("version"\s*:\s*")[^"]*(")/, `$1${version}$2`);
23018
23143
  if (out === src) {
23019
23144
  o.emit.error(`no version field in ${f2}`);
23020
23145
  return null;
23021
23146
  }
23022
- writeTextAt(f2, out, writeFileSync35);
23147
+ writeTextAt(f2, out, writeFileSync36);
23023
23148
  }
23024
23149
  return version;
23025
23150
  }
@@ -23032,8 +23157,8 @@ function writeChangelog(o, version, entries) {
23032
23157
  o.emit.emit(`would prepend ${entries.length} entr(ies) to ${file}`);
23033
23158
  return;
23034
23159
  }
23035
- const existing = existsAt(path, existsSync42) ? readTextAt(path, (p) => readFileSync42(p, "utf8")) : "# Changelog\n";
23036
- writeTextAt(path, insertChangelogSection(existing, section), writeFileSync35);
23160
+ const existing = existsAt(path, existsSync43) ? readTextAt(path, (p) => readFileSync43(p, "utf8")) : "# Changelog\n";
23161
+ writeTextAt(path, insertChangelogSection(existing, section), writeFileSync36);
23037
23162
  }
23038
23163
  async function confirm(o, expected, ci) {
23039
23164
  if (!o.repo.hooks.released) return void 0;
@@ -23198,9 +23323,9 @@ function openReleaseCheckout(o) {
23198
23323
  }
23199
23324
  for (const f2 of o.repo.worktrees.copy) {
23200
23325
  const src = join49(o.cwd, f2);
23201
- if (!existsSync42(src)) continue;
23326
+ if (!existsSync43(src)) continue;
23202
23327
  mkdirSync31(dirname26(join49(dir, f2)), { recursive: true });
23203
- copyFileSync(src, join49(dir, f2));
23328
+ copyFileSync2(src, join49(dir, f2));
23204
23329
  }
23205
23330
  return { dir, branch, close };
23206
23331
  }
@@ -24259,14 +24384,14 @@ async function runCommentDeliveryPass(deps) {
24259
24384
  }
24260
24385
 
24261
24386
  // src/launchd-start.ts
24262
- import { readFileSync as readFileSync49 } from "fs";
24387
+ import { readFileSync as readFileSync50 } from "fs";
24263
24388
  import { spawnSync as spawnSync13 } from "child_process";
24264
24389
 
24265
24390
  // src/daemon-liveness.ts
24266
- import { existsSync as existsSync49, readFileSync as readFileSync48 } from "fs";
24391
+ import { existsSync as existsSync50, readFileSync as readFileSync49 } from "fs";
24267
24392
 
24268
24393
  // src/daemon.ts
24269
- import { existsSync as existsSync48, mkdirSync as mkdirSync37, readFileSync as readFileSync47, readdirSync as readdirSync15, rmSync as rmSync23, statSync as statSync14, writeFileSync as writeFileSync39 } from "fs";
24394
+ import { existsSync as existsSync49, mkdirSync as mkdirSync37, readFileSync as readFileSync48, readdirSync as readdirSync15, rmSync as rmSync23, statSync as statSync14, writeFileSync as writeFileSync40 } from "fs";
24270
24395
  import { join as join54 } from "path";
24271
24396
  import { randomBytes } from "crypto";
24272
24397
 
@@ -24553,7 +24678,7 @@ function nextRoles(decision, ran) {
24553
24678
  }
24554
24679
 
24555
24680
  // src/noop-runs.ts
24556
- import { existsSync as existsSync43, mkdirSync as mkdirSync32, readFileSync as readFileSync43, renameSync as renameSync8, writeFileSync as writeFileSync36 } from "fs";
24681
+ import { existsSync as existsSync44, mkdirSync as mkdirSync32, readFileSync as readFileSync44, renameSync as renameSync9, writeFileSync as writeFileSync37 } from "fs";
24557
24682
  import { join as join50 } from "path";
24558
24683
  var NOOP_DELAYS_MS = [5, 15, 60].map((m) => m * 6e4);
24559
24684
  var DEFAULT_NOOP_REPEATS = 3;
@@ -24562,7 +24687,7 @@ var noopRunsPath = (stateDir) => join50(stateDir, "noop-runs.json");
24562
24687
  var noopRunsKey = (issueId) => `noop_runs:${issueId}`;
24563
24688
  function readNoopRuns(stateDir) {
24564
24689
  try {
24565
- const v = JSON.parse(readFileSync43(noopRunsPath(stateDir), "utf8"));
24690
+ const v = JSON.parse(readFileSync44(noopRunsPath(stateDir), "utf8"));
24566
24691
  return v && typeof v === "object" && !Array.isArray(v) ? v : {};
24567
24692
  } catch {
24568
24693
  return {};
@@ -24571,9 +24696,9 @@ function readNoopRuns(stateDir) {
24571
24696
  function writeNoopRuns(stateDir, state) {
24572
24697
  mkdirSync32(stateDir, { recursive: true });
24573
24698
  const file = noopRunsPath(stateDir);
24574
- writeFileSync36(`${file}.tmp`, `${JSON.stringify(state, null, 2)}
24699
+ writeFileSync37(`${file}.tmp`, `${JSON.stringify(state, null, 2)}
24575
24700
  `);
24576
- renameSync8(`${file}.tmp`, file);
24701
+ renameSync9(`${file}.tmp`, file);
24577
24702
  }
24578
24703
  function noopBackedOff(stateDir, recordId, now = Date.now()) {
24579
24704
  const e = readNoopRuns(stateDir)[recordId];
@@ -24588,7 +24713,7 @@ function recordNoopRun(stateDir, recordId, repeats, now = Date.now()) {
24588
24713
  return { count, nextAt, bounce: count >= repeats };
24589
24714
  }
24590
24715
  function clearNoopRuns(stateDir, recordId) {
24591
- if (!existsSync43(noopRunsPath(stateDir))) return;
24716
+ if (!existsSync44(noopRunsPath(stateDir))) return;
24592
24717
  const state = readNoopRuns(stateDir);
24593
24718
  if (!(recordId in state)) return;
24594
24719
  delete state[recordId];
@@ -24653,7 +24778,7 @@ async function settleNoopRun(o) {
24653
24778
  }
24654
24779
 
24655
24780
  // src/ship-name.ts
24656
- import { existsSync as existsSync44, mkdirSync as mkdirSync33, readFileSync as readFileSync44, renameSync as renameSync9, writeFileSync as writeFileSync37 } from "fs";
24781
+ import { existsSync as existsSync45, mkdirSync as mkdirSync33, readFileSync as readFileSync45, renameSync as renameSync10, writeFileSync as writeFileSync38 } from "fs";
24657
24782
  import { dirname as dirname27 } from "path";
24658
24783
  import { parseDocument as parseDocument4 } from "yaml";
24659
24784
  var ShipNameError = class extends Error {
@@ -24715,19 +24840,19 @@ async function syncRouteName(i) {
24715
24840
  return { status: "ok", ...base, action, name: i.local };
24716
24841
  }
24717
24842
  function readSyncedName(resolvedFile) {
24718
- if (!existsSync44(resolvedFile)) return void 0;
24843
+ if (!existsSync45(resolvedFile)) return void 0;
24719
24844
  try {
24720
- const v = JSON.parse(readFileSync44(resolvedFile, "utf8")).shipName;
24845
+ const v = JSON.parse(readFileSync45(resolvedFile, "utf8")).shipName;
24721
24846
  return typeof v === "string" ? v : void 0;
24722
24847
  } catch {
24723
24848
  return void 0;
24724
24849
  }
24725
24850
  }
24726
24851
  function writeSyncedName(resolvedFile, name) {
24727
- if (!existsSync44(resolvedFile)) return;
24852
+ if (!existsSync45(resolvedFile)) return;
24728
24853
  let raw;
24729
24854
  try {
24730
- raw = JSON.parse(readFileSync44(resolvedFile, "utf8"));
24855
+ raw = JSON.parse(readFileSync45(resolvedFile, "utf8"));
24731
24856
  } catch {
24732
24857
  return;
24733
24858
  }
@@ -24735,14 +24860,14 @@ function writeSyncedName(resolvedFile, name) {
24735
24860
  raw.shipName = name;
24736
24861
  mkdirSync33(dirname27(resolvedFile), { recursive: true });
24737
24862
  const tmp = `${resolvedFile}.tmp${process.pid}`;
24738
- writeFileSync37(tmp, `${JSON.stringify(raw, null, 2)}
24863
+ writeFileSync38(tmp, `${JSON.stringify(raw, null, 2)}
24739
24864
  `);
24740
- renameSync9(tmp, resolvedFile);
24865
+ renameSync10(tmp, resolvedFile);
24741
24866
  }
24742
24867
  async function reconcileShipName(i) {
24743
24868
  let local = i.ship.name;
24744
24869
  try {
24745
- local = shipNameOfYaml(readFileSync44(i.configFile, "utf8")) ?? local;
24870
+ local = shipNameOfYaml(readFileSync45(i.configFile, "utf8")) ?? local;
24746
24871
  } catch {
24747
24872
  }
24748
24873
  const resolvedFile = resolvedPathFor(i.stateDir, i.route);
@@ -24766,8 +24891,8 @@ async function reconcileShipName(i) {
24766
24891
  }
24767
24892
  if (result.status !== "ok") return result;
24768
24893
  if (result.action === "adopt" || result.action === "row-wins") {
24769
- const text2 = readFileSync44(i.configFile, "utf8");
24770
- writeFileSync37(i.configFile, setShipNameInYaml(text2, result.name));
24894
+ const text2 = readFileSync45(i.configFile, "utf8");
24895
+ writeFileSync38(i.configFile, setShipNameInYaml(text2, result.name));
24771
24896
  i.ship.name = result.name;
24772
24897
  if (result.action === "row-wins") {
24773
24898
  i.emit?.warn(
@@ -24812,7 +24937,7 @@ async function reconcileRouteShipName(o) {
24812
24937
  }
24813
24938
 
24814
24939
  // src/mirror-contract.ts
24815
- import { existsSync as existsSync45 } from "fs";
24940
+ import { existsSync as existsSync46 } from "fs";
24816
24941
 
24817
24942
  // src/passenger-mirror.ts
24818
24943
  import { mkdirSync as mkdirSync34 } from "fs";
@@ -24853,7 +24978,7 @@ function mirrorOutcome(m) {
24853
24978
 
24854
24979
  // src/mirror-contract.ts
24855
24980
  function lacksCheckout(ship, dir) {
24856
- return ship.runner === "sandbox" && !existsSync45(dir) && !remoteOf(dir);
24981
+ return ship.runner === "sandbox" && !existsSync46(dir) && !remoteOf(dir);
24857
24982
  }
24858
24983
  function skipsHostCheckout(ship) {
24859
24984
  return ship.runner === "sandbox";
@@ -24988,7 +25113,7 @@ function seatMissingProblems(route2, probes) {
24988
25113
 
24989
25114
  // src/ssh-keys.ts
24990
25115
  import { execFileSync as execFileSync13 } from "child_process";
24991
- import { existsSync as existsSync46, mkdirSync as mkdirSync35, readFileSync as readFileSync45, chmodSync as chmodSync3 } from "fs";
25116
+ import { existsSync as existsSync47, mkdirSync as mkdirSync35, readFileSync as readFileSync46, chmodSync as chmodSync3 } from "fs";
24992
25117
  import { dirname as dirname29, join as join51 } from "path";
24993
25118
  var SshKeyError = class extends Error {
24994
25119
  };
@@ -24998,7 +25123,7 @@ function shipSshKeyPathFor(stateDir) {
24998
25123
  function ensureShipSshKeypair(stateDir) {
24999
25124
  const privateKeyPath = shipSshKeyPathFor(stateDir);
25000
25125
  const publicKeyPath = `${privateKeyPath}.pub`;
25001
- if (!existsSync46(privateKeyPath)) {
25126
+ if (!existsSync47(privateKeyPath)) {
25002
25127
  mkdirSync35(dirname29(privateKeyPath), { recursive: true });
25003
25128
  try {
25004
25129
  execFileSync13("ssh-keygen", [
@@ -25019,10 +25144,10 @@ function ensureShipSshKeypair(stateDir) {
25019
25144
  }
25020
25145
  chmodSync3(privateKeyPath, 384);
25021
25146
  }
25022
- if (!existsSync46(publicKeyPath)) {
25147
+ if (!existsSync47(publicKeyPath)) {
25023
25148
  throw new SshKeyError(`${privateKeyPath} exists but ${publicKeyPath} does not \u2014 regenerate or restore it`);
25024
25149
  }
25025
- const publicKey = readFileSync45(publicKeyPath, "utf8").trim();
25150
+ const publicKey = readFileSync46(publicKeyPath, "utf8").trim();
25026
25151
  return { privateKeyPath, publicKeyPath, publicKey };
25027
25152
  }
25028
25153
  function sshKeygenAvailable() {
@@ -25136,7 +25261,7 @@ async function runPeriscopeIdlePass(d) {
25136
25261
  }
25137
25262
 
25138
25263
  // src/periscope-cmd.ts
25139
- import { existsSync as existsSync47, mkdirSync as mkdirSync36, readFileSync as readFileSync46, rmSync as rmSync22, writeFileSync as writeFileSync38 } from "fs";
25264
+ import { existsSync as existsSync48, mkdirSync as mkdirSync36, readFileSync as readFileSync47, rmSync as rmSync22, writeFileSync as writeFileSync39 } from "fs";
25140
25265
  import { join as join53 } from "path";
25141
25266
  var PeriscopeError = class extends Error {
25142
25267
  };
@@ -25155,14 +25280,14 @@ function removePeriscopePrior(stateDir, ticketRecordId) {
25155
25280
  function writePeriscopePrior(stateDir, ticketRecordId, prior) {
25156
25281
  try {
25157
25282
  mkdirSync36(priorDir(stateDir), { recursive: true });
25158
- writeFileSync38(priorPath(stateDir, ticketRecordId), JSON.stringify(prior));
25283
+ writeFileSync39(priorPath(stateDir, ticketRecordId), JSON.stringify(prior));
25159
25284
  } catch {
25160
25285
  }
25161
25286
  }
25162
25287
  function readPeriscopePrior(stateDir, ticketRecordId) {
25163
25288
  try {
25164
25289
  const p = priorPath(stateDir, ticketRecordId);
25165
- return existsSync47(p) ? JSON.parse(readFileSync46(p, "utf8")) : void 0;
25290
+ return existsSync48(p) ? JSON.parse(readFileSync47(p, "utf8")) : void 0;
25166
25291
  } catch {
25167
25292
  return void 0;
25168
25293
  }
@@ -25710,7 +25835,7 @@ function computeTreeSignature(paths) {
25710
25835
  }
25711
25836
  function makeStaleChecker(paths, opts = {}) {
25712
25837
  const initial = computeTreeSignature(paths);
25713
- return () => computeTreeSignature(paths) !== initial || opts.reloadSentinel !== void 0 && existsSync48(opts.reloadSentinel);
25838
+ return () => computeTreeSignature(paths) !== initial || opts.reloadSentinel !== void 0 && existsSync49(opts.reloadSentinel);
25714
25839
  }
25715
25840
  function reloadSentinelFor(stateDir) {
25716
25841
  return join54(stateDir, "reload-requested");
@@ -25728,12 +25853,12 @@ function daemonStampFor(stateDir) {
25728
25853
  function noteDaemonStarted(stateDir, now = Date.now()) {
25729
25854
  mkdirSync37(stateDir, { recursive: true });
25730
25855
  rmSync23(reloadSentinelFor(stateDir), { force: true });
25731
- writeFileSync39(daemonStampFor(stateDir), `${JSON.stringify({ pid: process.pid, startedAt: now })}
25856
+ writeFileSync40(daemonStampFor(stateDir), `${JSON.stringify({ pid: process.pid, startedAt: now })}
25732
25857
  `);
25733
25858
  }
25734
25859
  function readDaemonStarted(stateDir) {
25735
25860
  try {
25736
- const v = JSON.parse(readFileSync47(daemonStampFor(stateDir), "utf8")).startedAt;
25861
+ const v = JSON.parse(readFileSync48(daemonStampFor(stateDir), "utf8")).startedAt;
25737
25862
  return typeof v === "number" ? v : null;
25738
25863
  } catch {
25739
25864
  return null;
@@ -26622,7 +26747,7 @@ function parseSystemctlShow(text2) {
26622
26747
  }
26623
26748
  function lastLogLine(path, read = (p) => {
26624
26749
  try {
26625
- return readFileSync48(p, "utf8");
26750
+ return readFileSync49(p, "utf8");
26626
26751
  } catch {
26627
26752
  return null;
26628
26753
  }
@@ -26649,7 +26774,7 @@ function probeDaemonUnit(o) {
26649
26774
  const r = spawnSync12(cmd[0], cmd.slice(1), { encoding: "utf8" });
26650
26775
  return r.error ? null : { status: r.status, stdout: r.stdout ?? "" };
26651
26776
  });
26652
- const installed = o.plan.unitPaths.some((p) => existsSync49(p));
26777
+ const installed = o.plan.unitPaths.some((p) => existsSync50(p));
26653
26778
  let reading = null;
26654
26779
  if (installed && o.plan.mechanism === "launchd") {
26655
26780
  const r = run4(["launchctl", "print", `gui/${o.uid}/${o.label}`]);
@@ -26699,7 +26824,7 @@ function daemonProblem(d, route2) {
26699
26824
  }
26700
26825
  function readDaemonStamp(stateDir) {
26701
26826
  try {
26702
- const v = JSON.parse(readFileSync48(daemonStampFor(stateDir), "utf8"));
26827
+ const v = JSON.parse(readFileSync49(daemonStampFor(stateDir), "utf8"));
26703
26828
  if (typeof v.startedAt !== "number") return null;
26704
26829
  return typeof v.pid === "number" ? { pid: v.pid, startedAt: v.startedAt } : { startedAt: v.startedAt };
26705
26830
  } catch {
@@ -26725,7 +26850,7 @@ function defaultRun(cmd) {
26725
26850
  }
26726
26851
  function defaultReadLog(path) {
26727
26852
  try {
26728
- return readFileSync49(path, "utf8");
26853
+ return readFileSync50(path, "utf8");
26729
26854
  } catch {
26730
26855
  return null;
26731
26856
  }
@@ -26792,7 +26917,7 @@ function startLaunchdDaemon(o) {
26792
26917
  }
26793
26918
 
26794
26919
  // src/daemon-start-failure.ts
26795
- import { existsSync as existsSync50, mkdirSync as mkdirSync38, readFileSync as readFileSync50, unlinkSync as unlinkSync4, writeFileSync as writeFileSync40 } from "fs";
26920
+ import { existsSync as existsSync51, mkdirSync as mkdirSync38, readFileSync as readFileSync51, unlinkSync as unlinkSync4, writeFileSync as writeFileSync41 } from "fs";
26796
26921
  import { dirname as dirname30, join as join55 } from "path";
26797
26922
  var DAEMON_START_FAILED_KEY = "daemon_start_failed";
26798
26923
  var START_FAILURE_BACKOFF_MS = 6e4;
@@ -26800,7 +26925,7 @@ var BACKOFF_AFTER_FAILURES = 2;
26800
26925
  var fileFor4 = (stateDir) => join55(stateDir, ".daemon-start-failure.json");
26801
26926
  function readStartFailure(stateDir) {
26802
26927
  try {
26803
- const parsed = JSON.parse(readFileSync50(fileFor4(stateDir), "utf8"));
26928
+ const parsed = JSON.parse(readFileSync51(fileFor4(stateDir), "utf8"));
26804
26929
  return typeof parsed.reason === "string" && typeof parsed.count === "number" ? { reason: parsed.reason, count: parsed.count, firstAt: String(parsed.firstAt), lastAt: String(parsed.lastAt) } : null;
26805
26930
  } catch {
26806
26931
  return null;
@@ -26817,7 +26942,7 @@ function noteStartFailure(stateDir, reason, nowMs = Date.now()) {
26817
26942
  lastAt: nowIso
26818
26943
  };
26819
26944
  mkdirSync38(stateDir, { recursive: true });
26820
- writeFileSync40(fileFor4(stateDir), JSON.stringify(record));
26945
+ writeFileSync41(fileFor4(stateDir), JSON.stringify(record));
26821
26946
  return record;
26822
26947
  }
26823
26948
  function startFailureDelayMs(count) {
@@ -26831,7 +26956,7 @@ function startFailureItem(record, o = {}) {
26831
26956
  return { kind: "daemon_start_failed", key: DAEMON_START_FAILED_KEY, message: parts.join(". ").replace(/\.\./g, "."), since: record.firstAt };
26832
26957
  }
26833
26958
  function clearStartFailure(state, stateDir) {
26834
- if (existsSync50(fileFor4(stateDir))) {
26959
+ if (existsSync51(fileFor4(stateDir))) {
26835
26960
  try {
26836
26961
  unlinkSync4(fileFor4(stateDir));
26837
26962
  } catch {
@@ -27143,7 +27268,7 @@ function runForge(a, io) {
27143
27268
 
27144
27269
  // src/release-sandbox.ts
27145
27270
  import { execFile as execFile5 } from "child_process";
27146
- import { mkdirSync as mkdirSync39, writeFileSync as writeFileSync41 } from "fs";
27271
+ import { mkdirSync as mkdirSync39, writeFileSync as writeFileSync42 } from "fs";
27147
27272
  import { dirname as dirname31 } from "path";
27148
27273
  import { promisify as promisify4 } from "util";
27149
27274
  var execFileP4 = promisify4(execFile5);
@@ -27191,7 +27316,7 @@ async function openReleaseSandbox(o) {
27191
27316
  generated = generateSandboxPolicy({ mirrorDir: cfg.mirrorDir, workDir: cfg.workDir, ...o.policy });
27192
27317
  policyFile = o.policyFile;
27193
27318
  mkdirSync39(dirname31(policyFile), { recursive: true });
27194
- writeFileSync41(policyFile, generated.yaml, { mode: 384 });
27319
+ writeFileSync42(policyFile, generated.yaml, { mode: 384 });
27195
27320
  }
27196
27321
  const secrets = { ...process.env };
27197
27322
  const secretKeys = [];
@@ -27357,7 +27482,7 @@ function missingReleaserWarning(repo, release, ships, now = Date.now()) {
27357
27482
  }
27358
27483
 
27359
27484
  // src/watch.ts
27360
- import { watch as watchFile, existsSync as existsSync51, statSync as statSync15, openSync as openSync6, readSync as readSync3, closeSync as closeSync6 } from "fs";
27485
+ import { watch as watchFile, existsSync as existsSync52, statSync as statSync15, openSync as openSync6, readSync as readSync3, closeSync as closeSync6 } from "fs";
27361
27486
  var E = "\x1B[";
27362
27487
  var dim = (s) => `${E}2m${s}${E}0m`;
27363
27488
  var bold = (s) => `${E}1m${s}${E}0m`;
@@ -27458,7 +27583,7 @@ function renderHeaders(states, now = Date.now()) {
27458
27583
  return states.map((s) => renderHeader(s, now)).join("");
27459
27584
  }
27460
27585
  function readFrom(file, from) {
27461
- if (!existsSync51(file)) return { events: [], offset: from };
27586
+ if (!existsSync52(file)) return { events: [], offset: from };
27462
27587
  const size = statSync15(file).size;
27463
27588
  if (size < from) return readFrom(file, 0);
27464
27589
  if (size === from) return { events: [], offset: from };
@@ -28525,7 +28650,7 @@ function describeCapability(i) {
28525
28650
  }
28526
28651
 
28527
28652
  // src/persona-avatars.ts
28528
- import { existsSync as existsSync52, readFileSync as readFileSync51 } from "fs";
28653
+ import { existsSync as existsSync53, readFileSync as readFileSync52 } from "fs";
28529
28654
  import { join as join56 } from "path";
28530
28655
  var IMAGE_TYPES = { png: "image/png", svg: "image/svg+xml" };
28531
28656
  function personaAvatarFile(promptsDir, role) {
@@ -28533,7 +28658,7 @@ function personaAvatarFile(promptsDir, role) {
28533
28658
  for (const ext of ["png", "svg"]) {
28534
28659
  const name = `${stem}.${ext}`;
28535
28660
  const path = join56(promptsDir, "personas", name);
28536
- if (existsSync52(path)) return { path, mimeType: IMAGE_TYPES[ext], name };
28661
+ if (existsSync53(path)) return { path, mimeType: IMAGE_TYPES[ext], name };
28537
28662
  }
28538
28663
  return void 0;
28539
28664
  }
@@ -28550,7 +28675,7 @@ async function syncPersonaAvatars(route2, agentPersonas, opts) {
28550
28675
  if (!file || !agentId) continue;
28551
28676
  try {
28552
28677
  const form = new FormData();
28553
- form.append("file", new Blob([readFileSync51(file.path)], { type: file.mimeType }), file.name);
28678
+ form.append("file", new Blob([readFileSync52(file.path)], { type: file.mimeType }), file.name);
28554
28679
  const res = await fetch(`${base}/${agentId}/avatar`, {
28555
28680
  method: "PUT",
28556
28681
  headers: { Authorization: `Bearer ${resolveApiKey(route2)}`, "User-Agent": opts.userAgent ?? "Mozilla/5.0 TablationCrewAgent/1.0" },
@@ -28591,14 +28716,14 @@ function avatarFailures(raw) {
28591
28716
  }
28592
28717
  function routeAvatarFailures(stateDir, route2) {
28593
28718
  try {
28594
- return avatarFailures(JSON.parse(readFileSync51(resolvedPathFor(stateDir, route2), "utf8")));
28719
+ return avatarFailures(JSON.parse(readFileSync52(resolvedPathFor(stateDir, route2), "utf8")));
28595
28720
  } catch {
28596
28721
  return [];
28597
28722
  }
28598
28723
  }
28599
28724
 
28600
28725
  // src/agents-sync-run.ts
28601
- import { existsSync as existsSync53, mkdirSync as mkdirSync40, readFileSync as readFileSync52, writeFileSync as writeFileSync42 } from "fs";
28726
+ import { existsSync as existsSync54, mkdirSync as mkdirSync40, readFileSync as readFileSync53, writeFileSync as writeFileSync43 } from "fs";
28602
28727
  import { dirname as dirname32 } from "path";
28603
28728
  async function runAgentsSync(target, o) {
28604
28729
  const dryRun = o.dryRun ?? false;
@@ -28644,13 +28769,13 @@ async function runAgentsSync(target, o) {
28644
28769
  }
28645
28770
  if (!dryRun) {
28646
28771
  const resolvedPath = resolvedPathFor(o.stateDir, target.route);
28647
- const raw = existsSync53(resolvedPath) ? JSON.parse(readFileSync52(resolvedPath, "utf8")) : {};
28772
+ const raw = existsSync54(resolvedPath) ? JSON.parse(readFileSync53(resolvedPath, "utf8")) : {};
28648
28773
  raw.agentPersonas = personaResult.agentPersonas;
28649
28774
  if (skillResult) raw.agentSkills = skillResult.agentSkills;
28650
28775
  if (!readOnly2) raw.avatarSyncFailures = avatarFailures2;
28651
28776
  if (personaResult.releaseAgentId) raw.releaseAgentId = personaResult.releaseAgentId;
28652
28777
  mkdirSync40(dirname32(resolvedPath), { recursive: true });
28653
- writeFileSync42(resolvedPath, `${JSON.stringify(raw, null, 2)}
28778
+ writeFileSync43(resolvedPath, `${JSON.stringify(raw, null, 2)}
28654
28779
  `);
28655
28780
  if (target.resolved) {
28656
28781
  target.resolved.agentPersonas = personaResult.agentPersonas;
@@ -28786,16 +28911,16 @@ async function showLogEntry(route2, entryId, opts = {}) {
28786
28911
  }
28787
28912
 
28788
28913
  // src/repo-setup-prompt.ts
28789
- import { readFileSync as readFileSync53 } from "fs";
28914
+ import { readFileSync as readFileSync54 } from "fs";
28790
28915
  import { join as join57 } from "path";
28791
28916
  var REPO_SETUP_PROMPT_PATH = join57("docs", "repo-setup-prompt.md");
28792
28917
  function readRepoSetupPrompt(crewHome) {
28793
- return readFileSync53(join57(crewHome, REPO_SETUP_PROMPT_PATH), "utf8");
28918
+ return readFileSync54(join57(crewHome, REPO_SETUP_PROMPT_PATH), "utf8");
28794
28919
  }
28795
28920
 
28796
28921
  // src/repos-check.ts
28797
28922
  import { spawnSync as spawnSync14 } from "child_process";
28798
- import { readFileSync as readFileSync54 } from "fs";
28923
+ import { readFileSync as readFileSync55 } from "fs";
28799
28924
  import { basename as basename12 } from "path";
28800
28925
  var POSIX_SHELL = /^(?:ba|z|da|k|a|mk)?sh$|^fish$/;
28801
28926
  function checkHookSyntax(script, shell) {
@@ -28836,7 +28961,7 @@ function checkRepoSpec(dir, opts = {}) {
28836
28961
  }
28837
28962
  let parsed;
28838
28963
  try {
28839
- parsed = parseRepoConfig(readFileSync54(file, "utf8"), file);
28964
+ parsed = parseRepoConfig(readFileSync55(file, "utf8"), file);
28840
28965
  } catch (e) {
28841
28966
  if (!(e instanceof RepoConfigError)) throw e;
28842
28967
  return { ...empty, file, error: e.message, exitCode: 1 };
@@ -29368,6 +29493,73 @@ function planSampleTicket(i) {
29368
29493
  };
29369
29494
  }
29370
29495
 
29496
+ // src/connect-append.ts
29497
+ import { chmodSync as chmodSync4, existsSync as existsSync55, readFileSync as readFileSync56, renameSync as renameSync11, statSync as statSync16, unlinkSync as unlinkSync5, writeFileSync as writeFileSync44 } from "fs";
29498
+ import { basename as basename14, dirname as dirname34, join as join59 } from "path";
29499
+ import { isMap as isMap4, isSeq as isSeq2, parseDocument as parseDocument7 } from "yaml";
29500
+ function appendRouteBlock(config, block) {
29501
+ const doc = parseDocument7(config);
29502
+ if (doc.errors.length > 0) return { ok: false, reason: "crew.yaml is not valid YAML" };
29503
+ if (!isMap4(doc.contents)) return { ok: false, reason: "crew.yaml has no routes: list" };
29504
+ const routes = doc.contents.get("routes", true);
29505
+ if (!isSeq2(routes) || !routes.range) return { ok: false, reason: "crew.yaml has no routes: list to extend" };
29506
+ const body = block.replace(/\n+$/, "");
29507
+ if (routes.items.length === 0) {
29508
+ if (!routes.flow) return { ok: false, reason: "routes: is written in a form that cannot be extended" };
29509
+ let start = routes.range[0];
29510
+ while (start > 0 && (config[start - 1] === " " || config[start - 1] === " ")) start--;
29511
+ return { ok: true, text: `${config.slice(0, start)}
29512
+ ${body}${config.slice(routes.range[1])}` };
29513
+ }
29514
+ if (routes.flow) return { ok: false, reason: "routes: is written as an inline list that cannot be extended" };
29515
+ const first = routes.items[0];
29516
+ if (!isMap4(first) || !first.range) return { ok: false, reason: "routes: holds an entry that is not a mapping" };
29517
+ const lineStart = config.lastIndexOf("\n", first.range[0] - 1) + 1;
29518
+ const dashCol = config.slice(lineStart, first.range[0]).indexOf("-");
29519
+ if (dashCol < 0) return { ok: false, reason: "routes: is written in a form that cannot be extended" };
29520
+ const shift = dashCol - 2;
29521
+ const lines2 = body.split("\n").map((l) => shift >= 0 ? " ".repeat(shift) + l : l.slice(Math.min(-shift, l.length - l.trimStart().length)));
29522
+ const indented = lines2.join("\n");
29523
+ const lastEnd = routes.range[1];
29524
+ let eol = config.indexOf("\n", Math.max(0, lastEnd - 1));
29525
+ if (eol < 0) return { ok: true, text: `${config}
29526
+ ${indented}
29527
+ ` };
29528
+ eol += 1;
29529
+ return { ok: true, text: `${config.slice(0, eol)}${indented}
29530
+ ${config.slice(eol)}` };
29531
+ }
29532
+ function replaceFileKeepingMode(path, text2) {
29533
+ const mode = statSync16(path).mode & 4095;
29534
+ const tmp = join59(dirname34(path), `.${basename14(path)}.${process.pid}.tmp`);
29535
+ try {
29536
+ writeFileSync44(tmp, text2, { mode });
29537
+ chmodSync4(tmp, mode);
29538
+ renameSync11(tmp, path);
29539
+ } catch (e) {
29540
+ if (existsSync55(tmp)) unlinkSync5(tmp);
29541
+ throw e;
29542
+ }
29543
+ }
29544
+ function planAppendToConfig(crewHome, configFile, route2, block, keyPersisted) {
29545
+ if (!keyPersisted) return { ok: false, reason: "no stored key to name" };
29546
+ let current;
29547
+ try {
29548
+ current = readFileSync56(configFile, "utf8");
29549
+ } catch (e) {
29550
+ return { ok: false, reason: `could not read the file: ${e.message}` };
29551
+ }
29552
+ const r = appendRouteBlock(current, block);
29553
+ if (!r.ok) return r;
29554
+ try {
29555
+ const loaded = loadConfig(crewHome, configFile, { text: r.text });
29556
+ if (!loaded.routes.some((x) => x.route === route2)) return { ok: false, reason: "the config loader dropped the new route" };
29557
+ } catch (e) {
29558
+ return { ok: false, reason: `the config loader rejected the result: ${e.message.split("\n")[0]}` };
29559
+ }
29560
+ return r;
29561
+ }
29562
+
29371
29563
  // src/snapshot-staleness.ts
29372
29564
  var SNAPSHOT_TABLES = [
29373
29565
  { key: "periscopesModelId", name: "Periscopes" },
@@ -29593,8 +29785,8 @@ function fixPhaseNothingToOffer(o) {
29593
29785
  }
29594
29786
 
29595
29787
  // 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";
29788
+ import { existsSync as existsSync56, readFileSync as readFileSync57, readdirSync as readdirSync16 } from "fs";
29789
+ import { basename as basename15, dirname as dirname35, join as join60, resolve as resolve6 } from "path";
29598
29790
  function planWorktreeSweep(target, tickets, contract) {
29599
29791
  const terminal = new Set(contract.statuses.resolved.filter((s) => s !== contract.statuses.verified));
29600
29792
  const verified = contract.statuses.verified;
@@ -29635,7 +29827,7 @@ function ticketForWorktree(w, byNumber, contract) {
29635
29827
  const t = num2 ? byNumber.get(num2) : void 0;
29636
29828
  if (t && ticketStems(t).has(stem)) return t;
29637
29829
  }
29638
- const dir = basename14(w.path);
29830
+ const dir = basename15(w.path);
29639
29831
  const m = DIR_NUMBER.exec(dir);
29640
29832
  if (m && byNumber.has(m[1])) return byNumber.get(m[1]);
29641
29833
  if (!w.branch) {
@@ -29651,15 +29843,15 @@ function worktreeTicketNumbers(target) {
29651
29843
  const n = /-(\d+)$/.exec(BRANCH_STEM.exec(w.branch)?.[1] ?? "")?.[1];
29652
29844
  if (n) nums.add(n);
29653
29845
  }
29654
- const m = DIR_NUMBER_SUFFIXED.exec(basename14(w.path));
29846
+ const m = DIR_NUMBER_SUFFIXED.exec(basename15(w.path));
29655
29847
  if (m) nums.add(m[1]);
29656
29848
  }
29657
29849
  for (const d of siblingWorktreeDirs(target)) nums.add(d.number);
29658
29850
  return [...nums];
29659
29851
  }
29660
29852
  function siblingWorktreeDirs(target) {
29661
- const parent = dirname34(target.dir.replace(/[/\\]+$/, ""));
29662
- const stem = `${basename14(target.dir.replace(/[/\\]+$/, ""))}-`;
29853
+ const parent = dirname35(target.dir.replace(/[/\\]+$/, ""));
29854
+ const stem = `${basename15(target.dir.replace(/[/\\]+$/, ""))}-`;
29663
29855
  const registered = new Set(worktrees(target.dir).map((w) => resolve6(w.path)));
29664
29856
  let names;
29665
29857
  try {
@@ -29671,7 +29863,7 @@ function siblingWorktreeDirs(target) {
29671
29863
  for (const name of names) {
29672
29864
  if (!name.startsWith(stem)) continue;
29673
29865
  const m = DIR_NUMBER_SUFFIXED.exec(name);
29674
- const path = join59(parent, name);
29866
+ const path = join60(parent, name);
29675
29867
  if (m && !registered.has(resolve6(path))) out.push({ path, number: m[1] });
29676
29868
  }
29677
29869
  return out;
@@ -29684,7 +29876,7 @@ function orphanedWorktreeDirs(target, tickets, contract) {
29684
29876
  }
29685
29877
  function warnOrphanedWorktreeDirs(paths, log, held) {
29686
29878
  for (const p of paths) {
29687
- const number = DIR_NUMBER_SUFFIXED.exec(basename14(p))?.[1];
29879
+ const number = DIR_NUMBER_SUFFIXED.exec(basename15(p))?.[1];
29688
29880
  const when = held && number ? noteHeldWorktree(held.state, { repo: held.repo, path: p, ticket: number, status: "deployed", reason: "orphaned directory" }) : "first";
29689
29881
  if (when) {
29690
29882
  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 +29898,7 @@ async function applyWorktreeSweep(cwd, actions, dryRun, log, remote = "origin",
29706
29898
  let removed = 0;
29707
29899
  let keptBranches = 0;
29708
29900
  for (const a of actions) {
29709
- if (!dryRun && base && !a.keepBranch && existsSync54(a.path) && isHandBackMerge(a.path, base)) {
29901
+ if (!dryRun && base && !a.keepBranch && existsSync56(a.path) && isHandBackMerge(a.path, base)) {
29710
29902
  if (gitOk(a.path, ["merge", "--abort"]) !== null) {
29711
29903
  log.emit(
29712
29904
  `abandoned the hand-back merge of ${base} in ${a.path}: ${displayKey(a.ticket)} deployed without it`,
@@ -29723,11 +29915,11 @@ async function applyWorktreeSweep(cwd, actions, dryRun, log, remote = "origin",
29723
29915
  { ticket: a.ticket.issue_id, step: "worktree" }
29724
29916
  );
29725
29917
  };
29726
- if (!dryRun && liveRun && existsSync54(a.path)) {
29918
+ if (!dryRun && liveRun && existsSync56(a.path)) {
29727
29919
  defer();
29728
29920
  continue;
29729
29921
  }
29730
- if (!dryRun && existsSync54(a.path)) {
29922
+ if (!dryRun && existsSync56(a.path)) {
29731
29923
  let dirty = false;
29732
29924
  try {
29733
29925
  dirty = status(a.path).length > 0;
@@ -29742,7 +29934,7 @@ async function applyWorktreeSweep(cwd, actions, dryRun, log, remote = "origin",
29742
29934
  continue;
29743
29935
  }
29744
29936
  }
29745
- if (!dryRun && a.requirePushed && a.branch && existsSync54(a.path) && remoteConfigured(cwd, remote) && worktreeHoldsUnpushed(a.path, remote)) {
29937
+ if (!dryRun && a.requirePushed && a.branch && existsSync56(a.path) && remoteConfigured(cwd, remote) && worktreeHoldsUnpushed(a.path, remote)) {
29746
29938
  if (pids.length) {
29747
29939
  defer();
29748
29940
  continue;
@@ -29798,7 +29990,7 @@ function isHandBackMerge(path, base) {
29798
29990
  if (!msgPath) return false;
29799
29991
  let first;
29800
29992
  try {
29801
- first = readFileSync55(resolve6(path, msgPath), "utf8").split("\n")[0] ?? "";
29993
+ first = readFileSync57(resolve6(path, msgPath), "utf8").split("\n")[0] ?? "";
29802
29994
  } catch {
29803
29995
  return false;
29804
29996
  }
@@ -29852,7 +30044,7 @@ function isTicketBranch(name, base, stems) {
29852
30044
  }
29853
30045
  function sweepCandidatesExist(cwd, base) {
29854
30046
  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;
30047
+ if (linked.some((w) => DIR_NUMBER_SUFFIXED.test(basename15(w.path)) || w.branch && BRANCH_STEM.test(w.branch))) return true;
29856
30048
  if (siblingWorktreeDirs({ name: "", dir: cwd }).length) return true;
29857
30049
  return localBranches(cwd).some((b) => b !== base && /-\d+(?:-.*)?$/.test(b));
29858
30050
  }
@@ -29903,16 +30095,16 @@ function applyRemoteBranchCleanup(cwd, remote, branches2, dryRun, log) {
29903
30095
  }
29904
30096
 
29905
30097
  // 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";
30098
+ import { existsSync as existsSync57, readdirSync as readdirSync17, rmSync as rmSync24, statSync as statSync17 } from "fs";
30099
+ import { join as join61 } from "path";
29908
30100
  var DAY_MS2 = 24 * 60 * 60 * 1e3;
29909
30101
  function planStreamSweep(stateDir, retentionDays, now = Date.now()) {
29910
- const dir = join60(stateDir, "streams");
29911
- if (!existsSync55(dir)) return [];
30102
+ const dir = join61(stateDir, "streams");
30103
+ if (!existsSync57(dir)) return [];
29912
30104
  const cutoff = now - retentionDays * DAY_MS2;
29913
- return readdirSync17(dir).map((name) => join60(dir, name)).filter((path) => {
30105
+ return readdirSync17(dir).map((name) => join61(dir, name)).filter((path) => {
29914
30106
  try {
29915
- return statSync16(path).mtimeMs < cutoff;
30107
+ return statSync17(path).mtimeMs < cutoff;
29916
30108
  } catch {
29917
30109
  return false;
29918
30110
  }
@@ -29936,11 +30128,11 @@ function applyStreamSweep(paths, dryRun, log) {
29936
30128
  return removed;
29937
30129
  }
29938
30130
  function planEventsSweep(stateDir, retentionDays, now = Date.now()) {
29939
- if (!existsSync55(stateDir)) return [];
30131
+ if (!existsSync57(stateDir)) return [];
29940
30132
  const cutoff = now - retentionDays * DAY_MS2;
29941
- return readdirSync17(stateDir).filter((name) => ROTATED_EVENTS_RE.test(name)).map((name) => join60(stateDir, name)).filter((path) => {
30133
+ return readdirSync17(stateDir).filter((name) => ROTATED_EVENTS_RE.test(name)).map((name) => join61(stateDir, name)).filter((path) => {
29942
30134
  try {
29943
- return statSync16(path).mtimeMs < cutoff;
30135
+ return statSync17(path).mtimeMs < cutoff;
29944
30136
  } catch {
29945
30137
  return false;
29946
30138
  }
@@ -29949,18 +30141,18 @@ function planEventsSweep(stateDir, retentionDays, now = Date.now()) {
29949
30141
  function planSizeCapSweep(stateDir, maxBytes, now = Date.now()) {
29950
30142
  const files = [];
29951
30143
  const add = (dir, keep) => {
29952
- if (!existsSync55(dir)) return;
30144
+ if (!existsSync57(dir)) return;
29953
30145
  for (const name of readdirSync17(dir)) {
29954
30146
  if (!keep(name)) continue;
29955
- const path = join60(dir, name);
30147
+ const path = join61(dir, name);
29956
30148
  try {
29957
- const st = statSync16(path);
30149
+ const st = statSync17(path);
29958
30150
  if (st.isFile()) files.push({ path, mtime: st.mtimeMs, size: st.size });
29959
30151
  } catch {
29960
30152
  }
29961
30153
  }
29962
30154
  };
29963
- add(join60(stateDir, "streams"), () => true);
30155
+ add(join61(stateDir, "streams"), () => true);
29964
30156
  add(stateDir, (name) => ROTATED_EVENTS_RE.test(name));
29965
30157
  let total = files.reduce((n, f2) => n + f2.size, 0);
29966
30158
  const out = [];
@@ -29980,7 +30172,7 @@ function planStateSweep(stateDir, retentionDays, maxBytes, now = Date.now()) {
29980
30172
  }
29981
30173
 
29982
30174
  // 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";
30175
+ import { realpathSync as realpathSync4, readFileSync as readFileSync60, existsSync as existsSync62, mkdirSync as mkdirSync44, writeFileSync as writeFileSync47, rmSync as rmSync27, unlinkSync as unlinkSync7, copyFileSync as copyFileSync3, renameSync as renameSync12, statSync as statSync20, readdirSync as readdirSync22 } from "fs";
29984
30176
  import { createInterface } from "readline/promises";
29985
30177
 
29986
30178
  // src/periscope-resume.ts
@@ -30056,33 +30248,33 @@ ${tail2(preview.output)}`);
30056
30248
  import { dirname as dirOf2, resolve as resolvePath } from "path";
30057
30249
 
30058
30250
  // src/bundle-staleness.ts
30059
- import { existsSync as existsSync56, readdirSync as readdirSync18, statSync as statSync17 } from "fs";
30060
- import { join as join61 } from "path";
30251
+ import { existsSync as existsSync58, readdirSync as readdirSync18, statSync as statSync18 } from "fs";
30252
+ import { join as join62 } from "path";
30061
30253
  function builtVersion() {
30062
- return true ? "0.170.0" : null;
30254
+ return true ? "0.171.1" : null;
30063
30255
  }
30064
30256
  var REBUILD_HINT = "rebuild with npm run build";
30065
30257
  function newestMtime(path) {
30066
30258
  let stat2;
30067
30259
  try {
30068
- stat2 = statSync17(path);
30260
+ stat2 = statSync18(path);
30069
30261
  } catch {
30070
30262
  return 0;
30071
30263
  }
30072
30264
  if (stat2.isFile()) return stat2.mtimeMs;
30073
30265
  if (!stat2.isDirectory()) return 0;
30074
30266
  let latest = stat2.mtimeMs;
30075
- for (const e of readdirSync18(path, { withFileTypes: true })) latest = Math.max(latest, newestMtime(join61(path, e.name)));
30267
+ for (const e of readdirSync18(path, { withFileTypes: true })) latest = Math.max(latest, newestMtime(join62(path, e.name)));
30076
30268
  return latest;
30077
30269
  }
30078
30270
  function bundleStaleness(i) {
30079
30271
  if (i.built === null || i.compiled) return null;
30080
- const src = join61(i.home, "src");
30081
- if (!existsSync56(src)) return null;
30272
+ const src = join62(i.home, "src");
30273
+ if (!existsSync58(src)) return null;
30082
30274
  if (i.built !== i.current) {
30083
30275
  return { kind: "version", builtVersion: i.built, message: `running a bundle built from ${i.built} (package.json names ${i.current}); ${REBUILD_HINT}` };
30084
30276
  }
30085
- const bundle = statSafe(join61(i.home, "dist", "cli.js"));
30277
+ const bundle = statSafe(join62(i.home, "dist", "cli.js"));
30086
30278
  if (bundle === null) return null;
30087
30279
  if (newestMtime(src) > bundle) {
30088
30280
  return { kind: "source", builtVersion: i.built, message: `running a bundle older than the source in src/ (both ${i.current}); ${REBUILD_HINT}` };
@@ -30091,7 +30283,7 @@ function bundleStaleness(i) {
30091
30283
  }
30092
30284
  function statSafe(p) {
30093
30285
  try {
30094
- return statSync17(p).mtimeMs;
30286
+ return statSync18(p).mtimeMs;
30095
30287
  } catch {
30096
30288
  return null;
30097
30289
  }
@@ -30300,8 +30492,8 @@ async function unregisterEndpoint(workspaceId, info, d) {
30300
30492
  import { createServer as createHttpServer } from "http";
30301
30493
  import { spawn as spawn10 } from "child_process";
30302
30494
  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";
30495
+ import { existsSync as existsSync59, mkdirSync as mkdirSync41, readFileSync as readFileSync58, writeFileSync as writeFileSync45, unlinkSync as unlinkSync6, readdirSync as readdirSync19 } from "fs";
30496
+ import { join as join63 } from "path";
30305
30497
 
30306
30498
  // src/secret-compare.ts
30307
30499
  import { timingSafeEqual } from "crypto";
@@ -30394,27 +30586,27 @@ var defaultSpawn2 = (cmd, args, env) => {
30394
30586
  return child;
30395
30587
  };
30396
30588
  function syncDaemonStatePath(stateDir, workspaceId) {
30397
- return join62(stateDir, "passengers", `${workspaceId}-sync.json`);
30589
+ return join63(stateDir, "passengers", `${workspaceId}-sync.json`);
30398
30590
  }
30399
30591
  function readPersistedSyncDaemon(stateDir, workspaceId) {
30400
30592
  const path = syncDaemonStatePath(stateDir, workspaceId);
30401
- if (!existsSync57(path)) return void 0;
30593
+ if (!existsSync59(path)) return void 0;
30402
30594
  try {
30403
- return JSON.parse(readFileSync56(path, "utf8"));
30595
+ return JSON.parse(readFileSync58(path, "utf8"));
30404
30596
  } catch {
30405
30597
  return void 0;
30406
30598
  }
30407
30599
  }
30408
30600
  function writePersistedSyncDaemon(stateDir, state) {
30409
30601
  const path = syncDaemonStatePath(stateDir, state.workspaceId);
30410
- mkdirSync41(join62(stateDir, "passengers"), { recursive: true });
30411
- writeFileSync43(path, `${JSON.stringify(state, null, 2)}
30602
+ mkdirSync41(join63(stateDir, "passengers"), { recursive: true });
30603
+ writeFileSync45(path, `${JSON.stringify(state, null, 2)}
30412
30604
  `);
30413
30605
  }
30414
30606
  function removePersistedSyncDaemon(stateDir, workspaceId) {
30415
30607
  const path = syncDaemonStatePath(stateDir, workspaceId);
30416
30608
  try {
30417
- unlinkSync5(path);
30609
+ unlinkSync6(path);
30418
30610
  } catch {
30419
30611
  }
30420
30612
  }
@@ -30425,8 +30617,8 @@ function waitForExit(pid, alive, timeoutMs = 5e3) {
30425
30617
  }
30426
30618
  }
30427
30619
  function readAllPersistedSyncWorkspaceIds(stateDir) {
30428
- const dir = join62(stateDir, "passengers");
30429
- if (!existsSync57(dir)) return [];
30620
+ const dir = join63(stateDir, "passengers");
30621
+ if (!existsSync59(dir)) return [];
30430
30622
  const suffix = "-sync.json";
30431
30623
  return readdirSync19(dir).filter((f2) => f2.endsWith(suffix)).map((f2) => f2.slice(0, -suffix.length));
30432
30624
  }
@@ -30490,7 +30682,7 @@ import { createServer, request as httpRequest } from "http";
30490
30682
  import { request as httpsRequest } from "https";
30491
30683
  import { connect as netConnect } from "net";
30492
30684
  import { connect as tlsConnect } from "tls";
30493
- import { dirname as dirname35, isAbsolute as isAbsolute4 } from "path";
30685
+ import { dirname as dirname36, isAbsolute as isAbsolute4 } from "path";
30494
30686
  import { brotliDecompressSync, gunzipSync, inflateSync } from "zlib";
30495
30687
 
30496
30688
  // src/periscope-inspector.ts
@@ -30604,7 +30796,7 @@ function parsePointedBody(raw) {
30604
30796
  return entry;
30605
30797
  }
30606
30798
  function appendPointed(file, entry, now = /* @__PURE__ */ new Date()) {
30607
- mkdirSync42(dirname35(file), { recursive: true });
30799
+ mkdirSync42(dirname36(file), { recursive: true });
30608
30800
  appendFileSync4(file, `${JSON.stringify({ ...entry, at: now.toISOString() })}
30609
30801
  `);
30610
30802
  }
@@ -30893,7 +31085,7 @@ async function startWorktreeIntel(d) {
30893
31085
  }
30894
31086
 
30895
31087
  // src/contract-refusal.ts
30896
- import { join as join63 } from "path";
31088
+ import { join as join64 } from "path";
30897
31089
  function contractFixers(dir, baseRef, tickets, locate) {
30898
31090
  const out = [];
30899
31091
  for (const t of tickets) {
@@ -30905,7 +31097,7 @@ function contractFixers(dir, baseRef, tickets, locate) {
30905
31097
  const text2 = gitOk(dir, ["show", `${branch}:${file}`]);
30906
31098
  if (text2 === null) continue;
30907
31099
  try {
30908
- parseRepoConfig(text2, join63(dir, file));
31100
+ parseRepoConfig(text2, join64(dir, file));
30909
31101
  } catch (e) {
30910
31102
  if (e instanceof RepoConfigError) continue;
30911
31103
  throw e;
@@ -30918,20 +31110,20 @@ function contractFixers(dir, baseRef, tickets, locate) {
30918
31110
  // src/control-api.ts
30919
31111
  import { createHash as createHash12 } from "crypto";
30920
31112
  import {
30921
- chmodSync as chmodSync4,
31113
+ chmodSync as chmodSync5,
30922
31114
  closeSync as closeSync7,
30923
- existsSync as existsSync58,
31115
+ existsSync as existsSync60,
30924
31116
  fstatSync as fstatSync2,
30925
31117
  openSync as openSync7,
30926
31118
  readSync as readSync4,
30927
31119
  readdirSync as readdirSync20,
30928
31120
  rmSync as rmSync25,
30929
- statSync as statSync18,
31121
+ statSync as statSync19,
30930
31122
  watch
30931
31123
  } from "fs";
30932
31124
  import { createConnection } from "net";
30933
31125
  import { createServer as createServer2 } from "http";
30934
- import { basename as basename15, dirname as dirname36, join as join64 } from "path";
31126
+ import { basename as basename16, dirname as dirname37, join as join65 } from "path";
30935
31127
  import { execFile as execFile6, spawn as spawn13 } from "child_process";
30936
31128
 
30937
31129
  // src/periscope-control.ts
@@ -31169,7 +31361,7 @@ function runCrew(args, onLine, timeoutMs = 20 * 6e4) {
31169
31361
  // src/control-api.ts
31170
31362
  var PAUSABLE = ["dev", "design", "qa"];
31171
31363
  var CONTROL_SOCKET_NAME = "control.sock";
31172
- var controlSocketFor = (stateDir) => join64(stateDir, CONTROL_SOCKET_NAME);
31364
+ var controlSocketFor = (stateDir) => join65(stateDir, CONTROL_SOCKET_NAME);
31173
31365
  var MAX_SOCKET_PATH = 100;
31174
31366
  var MAX_TAIL_BYTES = 1024 * 1024;
31175
31367
  var MAX_WAIT_SECONDS = 30;
@@ -31256,7 +31448,7 @@ function candidates(live2, rotated) {
31256
31448
  const out = [live2];
31257
31449
  if (!rotated) return out;
31258
31450
  try {
31259
- for (const n of readdirSync20(dirname36(live2))) if (ROTATED_EVENTS_RE.test(n)) out.push(join64(dirname36(live2), n));
31451
+ for (const n of readdirSync20(dirname37(live2))) if (ROTATED_EVENTS_RE.test(n)) out.push(join65(dirname37(live2), n));
31260
31452
  } catch {
31261
31453
  }
31262
31454
  return out;
@@ -31279,7 +31471,7 @@ function readRange(path, from, max) {
31279
31471
  }
31280
31472
  }
31281
31473
  function lastLines2(path, n) {
31282
- const st = statSync18(path);
31474
+ const st = statSync19(path);
31283
31475
  const cursorAt = (off) => encodeCursor({ dev: st.dev, ino: st.ino, off });
31284
31476
  if (n <= 0 || st.size === 0) return { lines: [], cursor: cursorAt(st.size), reset: false };
31285
31477
  let start = st.size;
@@ -31300,7 +31492,7 @@ function lastLines2(path, n) {
31300
31492
  }
31301
31493
  function readTail(live2, opts) {
31302
31494
  const max = opts.maxBytes ?? MAX_TAIL_BYTES;
31303
- if (!existsSync58(live2)) {
31495
+ if (!existsSync60(live2)) {
31304
31496
  return { lines: [], cursor: opts.after ?? encodeCursor({ dev: 0, ino: 0, off: 0 }), reset: false };
31305
31497
  }
31306
31498
  const cur = opts.after ? decodeCursor(opts.after) : null;
@@ -31313,7 +31505,7 @@ function readTail(live2, opts) {
31313
31505
  } else {
31314
31506
  const found = candidates(live2, opts.rotated ?? false).find((p) => {
31315
31507
  try {
31316
- const s = statSync18(p);
31508
+ const s = statSync19(p);
31317
31509
  return s.ino === cur.ino && s.dev === cur.dev;
31318
31510
  } catch {
31319
31511
  return false;
@@ -31324,7 +31516,7 @@ function readTail(live2, opts) {
31324
31516
  off = cur.off;
31325
31517
  } else reset = true;
31326
31518
  }
31327
- let size = statSync18(path).size;
31519
+ let size = statSync19(path).size;
31328
31520
  if (off > size) {
31329
31521
  off = 0;
31330
31522
  reset = true;
@@ -31332,12 +31524,12 @@ function readTail(live2, opts) {
31332
31524
  if (off >= size && path !== live2) {
31333
31525
  path = live2;
31334
31526
  off = 0;
31335
- size = statSync18(path).size;
31527
+ size = statSync19(path).size;
31336
31528
  }
31337
31529
  const { text: text2 } = readRange(path, off, max);
31338
31530
  const cut = text2.lastIndexOf("\n");
31339
31531
  const whole = cut < 0 ? "" : text2.slice(0, cut + 1);
31340
- const st = statSync18(path);
31532
+ const st = statSync19(path);
31341
31533
  return {
31342
31534
  lines: whole.split("\n").filter((l) => l.length),
31343
31535
  cursor: encodeCursor({ dev: st.dev, ino: st.ino, off: off + Buffer.byteLength(whole) }),
@@ -31387,7 +31579,7 @@ function pauseDoc(state) {
31387
31579
  }
31388
31580
  function describeStream(r) {
31389
31581
  return {
31390
- run: basename15(r.streamPath).replace(/\.jsonl$/, ""),
31582
+ run: basename16(r.streamPath).replace(/\.jsonl$/, ""),
31391
31583
  pid: r.pid,
31392
31584
  ticket: r.ticket,
31393
31585
  role: r.role,
@@ -31424,7 +31616,7 @@ async function tailReply(path, q2, rotated, abort) {
31424
31616
  const deadline = Date.now() + Math.min(wait, MAX_WAIT_SECONDS) * 1e3;
31425
31617
  let r = readTail(path, { after, tail: tail3, rotated });
31426
31618
  while (after && !r.lines.length && !r.reset && Date.now() < deadline && !abort.aborted) {
31427
- await waitForChange(dirname36(path), deadline - Date.now(), abort);
31619
+ await waitForChange(dirname37(path), deadline - Date.now(), abort);
31428
31620
  r = readTail(path, { after: r.cursor, rotated });
31429
31621
  }
31430
31622
  return reply2(200, r);
@@ -31433,14 +31625,14 @@ var NOTE_MAX_CHARS = 4e3;
31433
31625
  var SEAT_ROLES = ["dev", "design", "qa", "triage", "pair"];
31434
31626
  async function postRunMessage(deps, run4, body) {
31435
31627
  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$/, ""));
31628
+ const live2 = liveRuns(deps.stateDir).find((r) => basename16(r.streamPath, ".jsonl") === run4.replace(/\.jsonl$/, ""));
31437
31629
  const carry = "A note for the work item posted from the platform is carried forward into its next run's brief.";
31438
31630
  if (!live2) return err2(404, `no live run ${run4}: it is unknown or has finished. ${carry}`);
31439
31631
  if (!body) return err2(400, "body must be a small JSON object");
31440
31632
  const text2 = typeof body.text === "string" ? body.text.trim() : "";
31441
31633
  if (!text2 || text2.length > NOTE_MAX_CHARS) return err2(400, `text must be a string of 1 to ${NOTE_MAX_CHARS} characters`);
31442
31634
  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"));
31635
+ const input = runInputFor(basename16(live2.streamPath, ".jsonl"));
31444
31636
  const rowId = input?.agentLogRowId();
31445
31637
  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
31638
  try {
@@ -31515,8 +31707,8 @@ async function route(deps, method, url, req, abort) {
31515
31707
  if (p.startsWith("/streams/") && get2) {
31516
31708
  const run4 = decodeURIComponent(p.slice("/streams/".length));
31517
31709
  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");
31710
+ const file = join65(deps.stateDir, "streams", run4.endsWith(".jsonl") ? run4 : `${run4}.jsonl`);
31711
+ if (!existsSync60(file)) return err2(404, "no such run");
31520
31712
  return tailReply(file, url.searchParams, false, abort);
31521
31713
  }
31522
31714
  const note = /^\/streams\/([^/]+)\/messages$/.exec(p);
@@ -31565,7 +31757,7 @@ function send2(res, r) {
31565
31757
  res.end(body);
31566
31758
  }
31567
31759
  async function socketIsStale(path) {
31568
- if (!existsSync58(path)) return false;
31760
+ if (!existsSync60(path)) return false;
31569
31761
  return new Promise((resolve9) => {
31570
31762
  const c = createConnection(path);
31571
31763
  c.once("connect", () => {
@@ -31584,7 +31776,7 @@ async function startControlServer(deps) {
31584
31776
  return null;
31585
31777
  }
31586
31778
  if (await socketIsStale(path)) rmSync25(path, { force: true });
31587
- else if (existsSync58(path)) {
31779
+ else if (existsSync60(path)) {
31588
31780
  log(`control API not started: ${path} is in use by another process`);
31589
31781
  return null;
31590
31782
  }
@@ -31621,7 +31813,7 @@ async function startControlServer(deps) {
31621
31813
  });
31622
31814
  server.listen(path, () => {
31623
31815
  try {
31624
- chmodSync4(path, 384);
31816
+ chmodSync5(path, 384);
31625
31817
  } catch {
31626
31818
  }
31627
31819
  server.on("error", (e) => log(`control API error: ${e.message}`));
@@ -31683,31 +31875,31 @@ function crewJson(args, timeoutMs = CREW_JSON_TIMEOUT_MS) {
31683
31875
 
31684
31876
  // src/periscope-mcp.ts
31685
31877
  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";
31878
+ import { basename as basename17, dirname as dirname38, isAbsolute as isAbsolute5, join as join67, relative as relative2, resolve as resolve7, sep } from "path";
31687
31879
  import { z } from "zod";
31688
31880
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
31689
31881
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
31690
31882
 
31691
31883
  // src/periscope-endpoints.ts
31692
31884
  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`);
31885
+ import { chmodSync as chmodSync6, existsSync as existsSync61, mkdirSync as mkdirSync43, readdirSync as readdirSync21, readFileSync as readFileSync59, rmSync as rmSync26, writeFileSync as writeFileSync46 } from "fs";
31886
+ import { join as join66 } from "path";
31887
+ var secretDir = (stateDir) => join66(stateDir, "periscope-mcp");
31888
+ var secretFile = (stateDir, id) => join66(secretDir(stateDir), `${id}.json`);
31889
+ var endpointDir = (stateDir) => join66(stateDir, "periscope-endpoints");
31890
+ var endpointFile = (stateDir, id) => join66(endpointDir(stateDir), `${id}.json`);
31699
31891
  function mintPeriscopeSecret(stateDir, ticketRecordId) {
31700
31892
  mkdirSync43(secretDir(stateDir), { recursive: true, mode: 448 });
31701
31893
  const secret = randomBytes3(32).toString("base64url");
31702
31894
  const file = secretFile(stateDir, ticketRecordId);
31703
- writeFileSync44(file, `${JSON.stringify({ secret })}
31895
+ writeFileSync46(file, `${JSON.stringify({ secret })}
31704
31896
  `, { mode: 384 });
31705
- chmodSync5(file, 384);
31897
+ chmodSync6(file, 384);
31706
31898
  return secret;
31707
31899
  }
31708
31900
  function readPeriscopeSecret(stateDir, ticketRecordId) {
31709
31901
  try {
31710
- const v = JSON.parse(readFileSync57(secretFile(stateDir, ticketRecordId), "utf8"));
31902
+ const v = JSON.parse(readFileSync59(secretFile(stateDir, ticketRecordId), "utf8"));
31711
31903
  return typeof v.secret === "string" && v.secret ? v.secret : void 0;
31712
31904
  } catch {
31713
31905
  return void 0;
@@ -31718,14 +31910,14 @@ function removePeriscopeSecret(stateDir, ticketRecordId) {
31718
31910
  }
31719
31911
  function readPeriscopeEndpoint(stateDir, ticketRecordId) {
31720
31912
  try {
31721
- return JSON.parse(readFileSync57(endpointFile(stateDir, ticketRecordId), "utf8"));
31913
+ return JSON.parse(readFileSync59(endpointFile(stateDir, ticketRecordId), "utf8"));
31722
31914
  } catch {
31723
31915
  return void 0;
31724
31916
  }
31725
31917
  }
31726
31918
  function writePeriscopeEndpoint(stateDir, rec) {
31727
31919
  mkdirSync43(endpointDir(stateDir), { recursive: true });
31728
- writeFileSync44(endpointFile(stateDir, rec.ticketRecordId), `${JSON.stringify(rec, null, 2)}
31920
+ writeFileSync46(endpointFile(stateDir, rec.ticketRecordId), `${JSON.stringify(rec, null, 2)}
31729
31921
  `);
31730
31922
  }
31731
31923
  function removePeriscopeEndpointRecord(stateDir, ticketRecordId) {
@@ -31733,7 +31925,7 @@ function removePeriscopeEndpointRecord(stateDir, ticketRecordId) {
31733
31925
  }
31734
31926
  function listPeriscopeEndpoints(stateDir) {
31735
31927
  const dir = endpointDir(stateDir);
31736
- if (!existsSync59(dir)) return [];
31928
+ if (!existsSync61(dir)) return [];
31737
31929
  const out = [];
31738
31930
  for (const name of readdirSync21(dir)) {
31739
31931
  if (!name.endsWith(".json")) continue;
@@ -31821,12 +32013,12 @@ async function realAncestor(p) {
31821
32013
  }
31822
32014
  if (isLink) {
31823
32015
  if (++hops > 40) throw new PathRefusal(`too many symbolic links resolving ${p}`);
31824
- cur = resolve7(dirname37(cur), await readlink(cur));
32016
+ cur = resolve7(dirname38(cur), await readlink(cur));
31825
32017
  continue;
31826
32018
  }
31827
- const parent = dirname37(cur);
32019
+ const parent = dirname38(cur);
31828
32020
  if (parent === cur) throw new PathRefusal(`cannot resolve ${p}`);
31829
- tail3.push(basename16(cur));
32021
+ tail3.push(basename17(cur));
31830
32022
  cur = parent;
31831
32023
  }
31832
32024
  }
@@ -31836,13 +32028,13 @@ async function resolveInWorktree(root, requested) {
31836
32028
  let abs;
31837
32029
  if (isAbsolute5(requested)) {
31838
32030
  abs = resolve7(requested);
31839
- if (isInside(root, abs)) abs = join66(realRoot, relative2(root, abs));
32031
+ if (isInside(root, abs)) abs = join67(realRoot, relative2(root, abs));
31840
32032
  } else {
31841
32033
  abs = resolve7(realRoot, requested);
31842
32034
  }
31843
32035
  if (!isInside(realRoot, abs)) throw new PathRefusal(`${requested} is outside this periscope's worktree`);
31844
32036
  const { real, rest } = await realAncestor(abs);
31845
- const final = rest ? join66(real, rest) : real;
32037
+ const final = rest ? join67(real, rest) : real;
31846
32038
  if (!isInside(realRoot, final)) throw new PathRefusal(`${requested} is outside this periscope's worktree`);
31847
32039
  if (relative2(realRoot, final).split(sep).includes(".git")) throw new PathRefusal(".git is not reachable from a periscope");
31848
32040
  return final;
@@ -31910,7 +32102,7 @@ function createPeriscopeMcpServer(d, sc) {
31910
32102
  const entries = (await readdir(abs, { withFileTypes: true })).filter((e) => e.name !== ".git");
31911
32103
  const lines2 = await Promise.all(entries.map(async (e) => {
31912
32104
  if (e.isDirectory()) return `[DIR] ${e.name}`;
31913
- const size = (await lstat(join66(abs, e.name))).size;
32105
+ const size = (await lstat(join67(abs, e.name))).size;
31914
32106
  return `[FILE] ${e.name} (${size} bytes)`;
31915
32107
  }));
31916
32108
  return text(lines2.join("\n") || "(empty)");
@@ -31935,7 +32127,7 @@ function createPeriscopeMcpServer(d, sc) {
31935
32127
  if (Buffer.byteLength(content) > MAX_WRITE_BYTES) return text(`content exceeds ${MAX_WRITE_BYTES} bytes`, true);
31936
32128
  const abs = await inTree(path);
31937
32129
  if (abs === await realpath(root)) return text("path must name a file", true);
31938
- await mkdir(dirname37(abs), { recursive: true });
32130
+ await mkdir(dirname38(abs), { recursive: true });
31939
32131
  await inTree(path);
31940
32132
  await writeFile(abs, content);
31941
32133
  return text(`Wrote ${Buffer.byteLength(content)} bytes to ${await rel(abs)}`);
@@ -31975,9 +32167,9 @@ function createPeriscopeMcpServer(d, sc) {
31975
32167
  inputSchema: { path: z.string() },
31976
32168
  annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: false }
31977
32169
  }, 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);
32170
+ const parent = await inTree(dirname38(path) === "" ? "." : dirname38(path));
32171
+ const abs = join67(parent, basename17(path));
32172
+ if (basename17(path) === ".git" || abs === parent) return text("path must name a file", true);
31981
32173
  const st = await lstat(abs).catch(() => void 0);
31982
32174
  if (!st) return text(`${path} does not exist`, true);
31983
32175
  if (st.isDirectory()) return text(`${path} is a directory; only files are deleted`, true);
@@ -32097,7 +32289,7 @@ function findPeriscope(sidecars, segment) {
32097
32289
  }
32098
32290
 
32099
32291
  // src/cli.ts
32100
- var CREW_HOME = isCompiledBinary(import.meta.url) ? dirname38(process.execPath) : resolve8(dirname38(fileURLToPath2(import.meta.url)), "..");
32292
+ var CREW_HOME = isCompiledBinary(import.meta.url) ? dirname39(process.execPath) : resolve8(dirname39(fileURLToPath2(import.meta.url)), "..");
32101
32293
  {
32102
32294
  const v = crewVersion(CREW_HOME);
32103
32295
  if (v !== "0.0.0") setRunningCrewVersion(v);
@@ -32511,7 +32703,7 @@ if (command === "provision") {
32511
32703
  process.exit(outcome.code);
32512
32704
  }
32513
32705
  if (command === "pool-member") {
32514
- const pool = poolConfigFrom(argv, process.env, () => readFileSync58(0, "utf8"));
32706
+ const pool = poolConfigFrom(argv, process.env, () => readFileSync60(0, "utf8"));
32515
32707
  if (typeof pool === "string") {
32516
32708
  process.stderr.write(`crew pool-member: ${pool}
32517
32709
  `);
@@ -32856,7 +33048,7 @@ if (command === "passenger-sync-daemon") {
32856
33048
  } else {
32857
33049
  const toleratesNoRoutes = command === "routes" || command === "credential" || command === "forge" || command === "repos" || command === "ship" || command === "disconnect" && flag("reset") || command === "deprovision" || command === "connect" && flag("sign-out");
32858
33050
  const configless = command === "routes" || command === "connect" && flag("sign-out") || command === "disconnect" && flag("reset") || command === "deprovision";
32859
- if (configless && !existsSync60(findConfigFile(CREW_HOME))) {
33051
+ if (configless && !existsSync62(findConfigFile(CREW_HOME))) {
32860
33052
  cfg = loadConfig(CREW_HOME, firstRunConfigPath(), { text: "ship: {}\n", allowNoRoutes: true });
32861
33053
  } else {
32862
33054
  cfg = loadConfig(CREW_HOME, void 0, toleratesNoRoutes ? { allowNoRoutes: true } : {});
@@ -32879,7 +33071,7 @@ if (command === "passenger-sync-daemon") {
32879
33071
  throw e;
32880
33072
  }
32881
33073
  if (command === "credential") {
32882
- const r = runCredential(positional[1], readFileSync58(0, "utf8"), cfg.ship.forges, cfg.ship.stateDir, process.env, !flag("no-miss"));
33074
+ const r = runCredential(positional[1], readFileSync60(0, "utf8"), cfg.ship.forges, cfg.ship.stateDir, process.env, !flag("no-miss"));
32883
33075
  process.stdout.write(r.out);
32884
33076
  process.stderr.write(r.err);
32885
33077
  process.exit(r.code);
@@ -32891,9 +33083,9 @@ if (command === "passenger-sync-daemon") {
32891
33083
  forges: cfg.ship.forges,
32892
33084
  stateDir: cfg.ship.stateDir,
32893
33085
  configFile: cfg.configFile,
32894
- readFile: (p) => readFileSync58(p, "utf8"),
32895
- writeFile: (p, t) => writeFileSync45(p, t),
32896
- stdin: () => readFileSync58(0, "utf8"),
33086
+ readFile: (p) => readFileSync60(p, "utf8"),
33087
+ writeFile: (p, t) => writeFileSync47(p, t),
33088
+ stdin: () => readFileSync60(0, "utf8"),
32897
33089
  env: process.env
32898
33090
  }
32899
33091
  );
@@ -33253,15 +33445,15 @@ if (command === "passenger-sync-daemon") {
33253
33445
  for (const l of summarizeJobs(results, { dryRun, verbose: flag("verbose"), host })) emit.emit(l);
33254
33446
  if (host === "linux" && hasSystemd) {
33255
33447
  const label = labelFor(CREW_HOME, "run");
33256
- const staleTimer = join67(homedir11(), ".config", "systemd", "user", `${label}.timer`);
33257
- if (existsSync60(staleTimer)) {
33448
+ const staleTimer = join68(homedir11(), ".config", "systemd", "user", `${label}.timer`);
33449
+ if (existsSync62(staleTimer)) {
33258
33450
  emit.emit(
33259
33451
  `removing stale run timer from before the persistent-service cutover: ${staleTimer}${dryRun ? " (dry run, not applied)" : ""}`
33260
33452
  );
33261
33453
  if (!dryRun) {
33262
33454
  spawnSync15("systemctl", ["--user", "disable", "--now", `${label}.timer`], { cwd: CREW_HOME, env: withUserBusEnv() });
33263
33455
  try {
33264
- unlinkSync6(staleTimer);
33456
+ unlinkSync7(staleTimer);
33265
33457
  } catch {
33266
33458
  }
33267
33459
  }
@@ -33303,7 +33495,7 @@ if (command === "passenger-sync-daemon") {
33303
33495
  const { settled: doctorRepos, errors: refusedRepos } = await settleRepos(reposOf(c), (t) => t.name, (t) => resolveOneRepo(c, t));
33304
33496
  for (const e of refusedRepos) problems.push(`repo ${e.repo}: ${e.detail}`);
33305
33497
  for (const r of doctorRepos) {
33306
- if (!existsSync60(r.dir)) problems.push(`repo ${r.name}: ${r.dir} is missing on disk`);
33498
+ if (!existsSync62(r.dir)) problems.push(`repo ${r.name}: ${r.dir} is missing on disk`);
33307
33499
  if (!satisfies(host, r.config.platform)) problems.push(`repo ${r.name}: requires ${r.config.platform}, this host is ${host}`);
33308
33500
  readiness.push(...validateEffective(r.config).map((p) => `repo ${r.name}: ${p}`));
33309
33501
  }
@@ -33326,7 +33518,7 @@ if (command === "passenger-sync-daemon") {
33326
33518
  problems.push(`tracker unreachable: ${e instanceof Error ? e.message : String(e)}`);
33327
33519
  }
33328
33520
  if (await tracker.eventLogTracksStatus() === false) problems.push(EVENT_LOG_STATUS_UNTRACKED(tracker.contract.columns.status));
33329
- for (const l of interfaceReport(await readForRoute(c, cfg.ship), { storedMappingKey: c.resolved?.trackerInterface?.mappingKey, contractAuthored: c.contractAuthored })) {
33521
+ for (const l of interfaceReport(await readForRoute(c, cfg.ship), { storedMappingKey: c.resolved?.trackerInterface?.mappingKey, contractAuthored: c.contractAuthored, stored: c.resolved })) {
33330
33522
  if (l.problem) problems.push(l.line);
33331
33523
  }
33332
33524
  const diff = await snapshotDiffFor(c);
@@ -33343,7 +33535,7 @@ if (command === "passenger-sync-daemon") {
33343
33535
  }
33344
33536
  async function doctorFix(o) {
33345
33537
  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);
33538
+ const unitExists = (p) => existsSync62(p);
33347
33539
  const crontab = o.host === "linux" ? spawnSync15("crontab", ["-l"], { encoding: "utf8" }).stdout ?? "" : "";
33348
33540
  const schedulerAbsent = o.host !== "windows" ? !schedulerInstalled(planInstall(cfg.ship, CREW_HOME, o.host, detectSystemd(), "run", installContext()), unitExists, crontab) : true;
33349
33541
  const plan = planFix({ routes, schedulerAbsent, host: o.host });
@@ -33373,7 +33565,7 @@ if (command === "passenger-sync-daemon") {
33373
33565
  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
33566
  } else if (a.kind === "enable") {
33375
33567
  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));
33568
+ writeFileSync47(cfg.configFile, planEnable(readFileSync60(cfg.configFile, "utf8"), a.route));
33377
33569
  enabledSound.add(a.route);
33378
33570
  changed2.push(`enabled route ${a.route} in ${cfg.configFile}`);
33379
33571
  } else {
@@ -33626,7 +33818,7 @@ ${changed2.map((c) => ` - ${c}
33626
33818
  harnessBin: "claude",
33627
33819
  ...contract.sandboxNetwork ? { extraHosts: contract.sandboxNetwork.hosts, toolchains: contract.sandboxNetwork.toolchains } : {}
33628
33820
  },
33629
- policyFile: join67(cfg.ship.stateDir, "release", `${target.name}.policy.yaml`),
33821
+ policyFile: join68(cfg.ship.stateDir, "release", `${target.name}.policy.yaml`),
33630
33822
  repo: mirror,
33631
33823
  origin: forgeDescriptorFor(forgeHost).httpsUrl(mirror.host, mirror.path),
33632
33824
  base: effective.branch.base,
@@ -35049,7 +35241,7 @@ ${f2.tail.trimEnd()}
35049
35241
  logFile: cfg.ship.logFile
35050
35242
  });
35051
35243
  }
35052
- const watchPaths = isCompiledBinary(import.meta.url) ? [process.execPath] : [join67(CREW_HOME, "src"), join67(CREW_HOME, "dist"), join67(CREW_HOME, "bin")];
35244
+ const watchPaths = isCompiledBinary(import.meta.url) ? [process.execPath] : [join68(CREW_HOME, "src"), join68(CREW_HOME, "dist"), join68(CREW_HOME, "bin")];
35053
35245
  const configPaths = daemonConfigPaths(cfg);
35054
35246
  watchPaths.push(...configPaths);
35055
35247
  noteDaemonStarted(cfg.ship.stateDir);
@@ -35358,10 +35550,10 @@ ${f2.tail.trimEnd()}
35358
35550
  for (const w of result.warnings) emit.warn(w);
35359
35551
  if (!dryRun) {
35360
35552
  const resolvedPath = resolvedPathFor(cfg.ship.stateDir, target.route);
35361
- const raw = existsSync60(resolvedPath) ? JSON.parse(readFileSync58(resolvedPath, "utf8")) : {};
35553
+ const raw = existsSync62(resolvedPath) ? JSON.parse(readFileSync60(resolvedPath, "utf8")) : {};
35362
35554
  raw.agentSkills = result.agentSkills;
35363
35555
  mkdirSync44(dirOf2(resolvedPath), { recursive: true });
35364
- writeFileSync45(resolvedPath, `${JSON.stringify(raw, null, 2)}
35556
+ writeFileSync47(resolvedPath, `${JSON.stringify(raw, null, 2)}
35365
35557
  `);
35366
35558
  }
35367
35559
  if (result.outcomes.some((o) => o.action === "diverged")) process.exitCode = 1;
@@ -35382,7 +35574,7 @@ ${f2.tail.trimEnd()}
35382
35574
  throw e;
35383
35575
  }
35384
35576
  const oldName = cfg.ship.name;
35385
- writeFileSync45(cfg.configFile, setShipNameInYaml(readFileSync58(cfg.configFile, "utf8"), newName));
35577
+ writeFileSync47(cfg.configFile, setShipNameInYaml(readFileSync60(cfg.configFile, "utf8"), newName));
35386
35578
  cfg.ship.name = newName;
35387
35579
  let renameMachineId;
35388
35580
  try {
@@ -35429,14 +35621,14 @@ ${f2.tail.trimEnd()}
35429
35621
  process.exit(2);
35430
35622
  };
35431
35623
  if (sub !== "add" && sub !== "list" && sub !== "clone" && sub !== "hooks" && sub !== "check") usage2();
35432
- const configText = readFileSync58(cfg.configFile, "utf8");
35624
+ const configText = readFileSync60(cfg.configFile, "utf8");
35433
35625
  if (sub === "check") {
35434
35626
  try {
35435
35627
  const routeArg = value("route") ?? positional[2];
35436
35628
  const found = cfg.routes.find((r) => r.route === routeArg);
35437
35629
  if (!found) throw new ReposError(`no route "${routeArg}" in the config (have: ${cfg.routes.map((r) => r.route).join(", ") || "none"})`);
35438
35630
  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] ?? ".");
35631
+ const dir = named2 ? repoDirOf(configText, dirname39(cfg.configFile), found.route, named2) : resolvePath(positional[value("route") ? 2 : 3] ?? ".");
35440
35632
  const target = reposOf(found).find((t) => resolvePath(t.dir) === dir || t.name === named2);
35441
35633
  const o = target ? found.repoOverrides[target.name] : void 0;
35442
35634
  runReposCheck(dir, {
@@ -35458,9 +35650,9 @@ ${f2.tail.trimEnd()}
35458
35650
  if (sub === "hooks") {
35459
35651
  try {
35460
35652
  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) => {
35653
+ const dir = repoDirOf(configText, dirname39(cfg.configFile), a.route, a.name);
35654
+ if (!existsSync62(dir)) throw new ReposError(`${dir} does not exist on disk`);
35655
+ const files = { exists: (r) => existsSync62(resolvePath(dir, r)), list: (r) => {
35464
35656
  try {
35465
35657
  return readdirSync22(resolvePath(dir, r));
35466
35658
  } catch {
@@ -35468,7 +35660,7 @@ ${f2.tail.trimEnd()}
35468
35660
  }
35469
35661
  }, read: (r) => {
35470
35662
  try {
35471
- return readFileSync58(resolvePath(dir, r), "utf8");
35663
+ return readFileSync60(resolvePath(dir, r), "utf8");
35472
35664
  } catch {
35473
35665
  return void 0;
35474
35666
  }
@@ -35510,19 +35702,19 @@ ${f2.tail.trimEnd()}
35510
35702
  let cleared;
35511
35703
  if (clear2) {
35512
35704
  const plan = clearRouteHooks(configText, a.route, a.name);
35513
- if (plan.removed.length > 0) writeFileSync45(cfg.configFile, plan.text);
35705
+ if (plan.removed.length > 0) writeFileSync47(cfg.configFile, plan.text);
35514
35706
  cleared = { file: cfg.configFile, removed: plan.removed };
35515
35707
  }
35516
35708
  if (write && suggestion.source === null && recipeIds.length === 0 && hookSpecs.length === 0) throw new ReposError(`nothing to write: ${suggestion.notes[0]}`);
35517
35709
  if (write === "route") {
35518
35710
  const plan = planRouteHooks(configText, a.route, a.name, picked.hooks, { replace: flag("replace") });
35519
- writeFileSync45(cfg.configFile, plan.text);
35711
+ writeFileSync47(cfg.configFile, plan.text);
35520
35712
  written = { target: "route", file: cfg.configFile, hooks: plan.written, kept: plan.kept, replaced: plan.replaced };
35521
35713
  } else if (write === "repo") {
35522
35714
  const have = existingRepoConfig(files);
35523
35715
  if (have) throw new ReposError(`${resolvePath(dir, have)} already exists; not overwriting it`);
35524
35716
  const file = resolvePath(dir, ".crew.yaml");
35525
- writeFileSync45(file, starterRepoConfig(picked.hooks, picked.release), { flag: "wx" });
35717
+ writeFileSync47(file, starterRepoConfig(picked.hooks, picked.release), { flag: "wx" });
35526
35718
  written = { target: "repo", file, hooks: Object.keys(picked.hooks), kept: [], replaced: [] };
35527
35719
  }
35528
35720
  if (flag("json")) {
@@ -35575,7 +35767,7 @@ ${f2.tail.trimEnd()}
35575
35767
  if (sub === "list" && !routeName) usage2();
35576
35768
  if (sub === "add") {
35577
35769
  try {
35578
- const a = parseAddArgs(positional.slice(2), routeNamesOf(configText), (p) => existsSync60(resolvePath(p.replace(/^~(?=\/|$)/, homedir11()))));
35770
+ const a = parseAddArgs(positional.slice(2), routeNamesOf(configText), (p) => existsSync62(resolvePath(p.replace(/^~(?=\/|$)/, homedir11()))));
35579
35771
  routeName = a.route;
35580
35772
  addPath = a.path;
35581
35773
  addName = a.name;
@@ -35601,7 +35793,7 @@ ${f2.tail.trimEnd()}
35601
35793
  const resolvedFile = resolvedPathFor(cfg.ship.stateDir, routeName);
35602
35794
  if (sub === "list" || sub === "add") {
35603
35795
  const liveRoute = cfg.routes.find((r) => r.route === routeName);
35604
- if (liveRoute?.resolved?.reposModelId && existsSync60(resolvedFile) && !dryRun) {
35796
+ if (liveRoute?.resolved?.reposModelId && existsSync62(resolvedFile) && !dryRun) {
35605
35797
  try {
35606
35798
  await hydrateApiKeys([liveRoute]);
35607
35799
  persistRepoRows(cfg.ship.stateDir, liveRoute.route, await new Tracker(liveRoute, cfg.ship).repoRowsForMap());
@@ -35610,16 +35802,16 @@ ${f2.tail.trimEnd()}
35610
35802
  }
35611
35803
  }
35612
35804
  let resolvedRemotes;
35613
- if (existsSync60(resolvedFile)) {
35805
+ if (existsSync62(resolvedFile)) {
35614
35806
  try {
35615
- resolvedRemotes = JSON.parse(readFileSync58(resolvedFile, "utf8"));
35807
+ resolvedRemotes = JSON.parse(readFileSync60(resolvedFile, "utf8"));
35616
35808
  } catch {
35617
35809
  }
35618
35810
  }
35619
35811
  const originOf = (dir) => gitOk(dir, ["remote", "get-url", "origin"]) ?? void 0;
35620
35812
  const text2 = configText;
35621
- const base = dirname38(cfg.configFile);
35622
- const isCheckout = (d) => existsSync60(`${d}/.git`);
35813
+ const base = dirname39(cfg.configFile);
35814
+ const isCheckout = (d) => existsSync62(`${d}/.git`);
35623
35815
  try {
35624
35816
  if (sub === "list") {
35625
35817
  if (flag("json")) {
@@ -35629,12 +35821,12 @@ ${f2.tail.trimEnd()}
35629
35821
  base,
35630
35822
  resolved: resolvedRemotes,
35631
35823
  originOf,
35632
- exists: (d) => existsSync60(d),
35824
+ exists: (d) => existsSync62(d),
35633
35825
  isCheckout,
35634
35826
  repoHasHooks: (d) => REPO_CONFIG_FILENAMES.some((f2) => {
35635
35827
  try {
35636
35828
  const path = resolvePath(d, f2);
35637
- return Object.keys(parseRepoConfig(readFileSync58(path, "utf8"), path).hooks).length > 0;
35829
+ return Object.keys(parseRepoConfig(readFileSync60(path, "utf8"), path).hooks).length > 0;
35638
35830
  } catch {
35639
35831
  return false;
35640
35832
  }
@@ -35651,7 +35843,7 @@ ${f2.tail.trimEnd()}
35651
35843
  for (const r of repos) {
35652
35844
  const origin2 = originOf(r.dir);
35653
35845
  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)"}`;
35846
+ const note = !existsSync62(r.dir) ? "missing on disk" : row ? `Repos row: ${row}` : `no Repos row matches ${normalizeRemote2(origin2) ?? "this checkout (no origin remote)"}`;
35655
35847
  process.stdout.write(`${r.name} ${r.dir} ${note}
35656
35848
  `);
35657
35849
  }
@@ -35663,9 +35855,9 @@ ${f2.tail.trimEnd()}
35663
35855
  ` : `${human}
35664
35856
  `);
35665
35857
  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)) {
35858
+ if (existsSync62(plan2.target) && (existsSync62(`${plan2.target}/.git`) || readdirSync22(plan2.target).length > 0)) {
35667
35859
  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`
35860
+ existsSync62(`${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
35861
  );
35670
35862
  }
35671
35863
  if (dryRun) {
@@ -35683,13 +35875,13 @@ ${f2.tail.trimEnd()}
35683
35875
  throw new ReposError(`${e.message}${authHint}
35684
35876
  crew.yaml was not changed`);
35685
35877
  }
35686
- writeFileSync45(cfg.configFile, plan2.text);
35878
+ writeFileSync47(cfg.configFile, plan2.text);
35687
35879
  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
35880
  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
35881
  break;
35690
35882
  }
35691
35883
  const target = resolvePath(addPath.replace(/^~(?=\/|$)/, homedir11()));
35692
- if (!existsSync60(target)) throw new ReposError(`${target} does not exist`);
35884
+ if (!existsSync62(target)) throw new ReposError(`${target} does not exist`);
35693
35885
  let top;
35694
35886
  try {
35695
35887
  top = git(target, ["rev-parse", "--show-toplevel"]);
@@ -35773,15 +35965,15 @@ would need a project first: the tracker has none (\`crew projects add NAME --pre
35773
35965
  const created = await rowTracker.createRepoRow(rowPayload);
35774
35966
  process.stdout.write(`created Repos row ${String(rowPayload.name)} (${String(rowPayload.remote)}) ${created.id}
35775
35967
  `);
35776
- if (existsSync60(resolvedFile)) {
35777
- const raw = JSON.parse(readFileSync58(resolvedFile, "utf8"));
35968
+ if (existsSync62(resolvedFile)) {
35969
+ const raw = JSON.parse(readFileSync60(resolvedFile, "utf8"));
35778
35970
  raw.repoNames = { ...raw.repoNames, [created.id]: String(rowPayload.name) };
35779
35971
  raw.repoRemotes = { ...raw.repoRemotes, [created.id]: String(rowPayload.remote) };
35780
- writeFileSync45(resolvedFile, `${JSON.stringify(raw, null, 2)}
35972
+ writeFileSync47(resolvedFile, `${JSON.stringify(raw, null, 2)}
35781
35973
  `);
35782
35974
  }
35783
35975
  }
35784
- writeFileSync45(cfg.configFile, plan.text);
35976
+ writeFileSync47(cfg.configFile, plan.text);
35785
35977
  process.stdout.write(`added ${top} to ${routeName} as ${plan.mode === "dir" ? "dir" : `repos.${plan.name}`} in ${cfg.configFile}
35786
35978
  `);
35787
35979
  } catch (e) {
@@ -36147,7 +36339,7 @@ Waiting for approval`
36147
36339
  ${found.problems.map((p) => ` - ${p}`).join("\n")}`, "fix the problems above, then run `crew connect` again");
36148
36340
  }
36149
36341
  if (found.shipNameAdopted && !dryRun) {
36150
- writeFileSync45(cfg.configFile, setShipNameInYaml(readFileSync58(cfg.configFile, "utf8"), found.shipNameAdopted));
36342
+ writeFileSync47(cfg.configFile, setShipNameInYaml(readFileSync60(cfg.configFile, "utf8"), found.shipNameAdopted));
36151
36343
  cfg.ship.name = found.shipNameAdopted;
36152
36344
  }
36153
36345
  if (found.shipRow) {
@@ -36188,10 +36380,10 @@ ${found.problems.map((p) => ` - ${p}`).join("\n")}`, "fix the problems above, t
36188
36380
  }
36189
36381
  }
36190
36382
  let previous;
36191
- const hadPreviousFile = existsSync60(resolvedPath);
36383
+ const hadPreviousFile = existsSync62(resolvedPath);
36192
36384
  if (hadPreviousFile) {
36193
36385
  try {
36194
- previous = JSON.parse(readFileSync58(resolvedPath, "utf8"));
36386
+ previous = JSON.parse(readFileSync60(resolvedPath, "utf8"));
36195
36387
  } catch {
36196
36388
  }
36197
36389
  }
@@ -36337,12 +36529,12 @@ ${found.problems.map((p) => ` - ${p}`).join("\n")}`, "fix the problems above, t
36337
36529
  process.stderr.write(`(dry run) would write resolved ids to ${resolvedPath}
36338
36530
  `);
36339
36531
  } else {
36340
- mkdirSync44(dirname38(resolvedPath), { recursive: true });
36341
- if (hadPreviousFile) copyFileSync2(resolvedPath, `${resolvedPath}.bak`);
36532
+ mkdirSync44(dirname39(resolvedPath), { recursive: true });
36533
+ if (hadPreviousFile) copyFileSync3(resolvedPath, `${resolvedPath}.bak`);
36342
36534
  const tmpPath = `${resolvedPath}.tmp${process.pid}`;
36343
- writeFileSync45(tmpPath, `${JSON.stringify(resolved, null, 2)}
36535
+ writeFileSync47(tmpPath, `${JSON.stringify(resolved, null, 2)}
36344
36536
  `);
36345
- renameSync10(tmpPath, resolvedPath);
36537
+ renameSync12(tmpPath, resolvedPath);
36346
36538
  emit.note(`Resolved ids written to ${resolvedPath}`);
36347
36539
  }
36348
36540
  let mintOutcomes = [];
@@ -36409,8 +36601,8 @@ ${found.problems.map((p) => ` - ${p}`).join("\n")}`, "fix the problems above, t
36409
36601
  process.stderr.write(`(dry run) would write the API key to ${apiKeyFile}
36410
36602
  `);
36411
36603
  } else {
36412
- mkdirSync44(dirname38(apiKeyFile), { recursive: true });
36413
- writeFileSync45(apiKeyFile, `${apiKeyVar}=${apiKey}
36604
+ mkdirSync44(dirname39(apiKeyFile), { recursive: true });
36605
+ writeFileSync47(apiKeyFile, `${apiKeyVar}=${apiKey}
36414
36606
  `, { mode: 384 });
36415
36607
  routineLine(`API key written to ${apiKeyFile}`);
36416
36608
  }
@@ -36434,6 +36626,17 @@ ${found.problems.map((p) => ` - ${p}`).join("\n")}`, "fix the problems above, t
36434
36626
  }
36435
36627
  );
36436
36628
  let wroteConfig = false;
36629
+ const routeAlreadyInConfig = cfg.routes.some((r) => r.route === route3);
36630
+ let appendReason;
36631
+ let appendedToExisting = false;
36632
+ if (!wizard && !routeAlreadyInConfig) {
36633
+ const appended = planAppendToConfig(CREW_HOME, cfg.configFile, route3, routeBlock, keyPersisted);
36634
+ if (!appended.ok) appendReason = appended.reason;
36635
+ else if (!dryRun) {
36636
+ replaceFileKeepingMode(cfg.configFile, appended.text);
36637
+ appendedToExisting = true;
36638
+ } else appendReason = "dry-run";
36639
+ }
36437
36640
  if (writeFirstRun) {
36438
36641
  wroteConfig = writeNewConfig(wizard.configPath, renderFullConfig(wizard.answers, routeBlock));
36439
36642
  if (!wroteConfig) emit.warn(`${wizard.configPath} appeared while connecting \u2014 leaving it alone`);
@@ -36445,8 +36648,10 @@ ${found.problems.map((p) => ` - ${p}`).join("\n")}`, "fix the problems above, t
36445
36648
  connectEvents.emit("config", `${wizard.configPath} appeared while connecting; left alone`, { written: false, path: wizard.configPath, reason: "appeared while connecting" });
36446
36649
  } else if (wizard) {
36447
36650
  connectEvents.emit("config", `no key file or keychain entry to name; ${wizard.configPath} not written`, { written: false, path: wizard.configPath, reason: "no-key" });
36651
+ } else if (appendedToExisting) {
36652
+ connectEvents.emit("config", `added the route ${route3} to ${cfg.configFile}, disabled`, { written: true, path: cfg.configFile, appended: true });
36448
36653
  } else {
36449
- connectEvents.emit("config", `${cfg.configFile} already exists; left alone`, { written: false, path: cfg.configFile, reason: "exists" });
36654
+ connectEvents.emit("config", `${cfg.configFile} already exists; left alone`, { written: false, path: cfg.configFile, reason: appendReason ? `exists: ${appendReason}` : "exists" });
36450
36655
  }
36451
36656
  }
36452
36657
  const routeInConfig = cfg.routes.some((r) => r.route === route3);
@@ -36459,7 +36664,13 @@ ${found.problems.map((p) => ` - ${p}`).join("\n")}`, "fix the problems above, t
36459
36664
  keys: mintOutcomes.map((m) => ({ role: m.role, action: m.action }))
36460
36665
  }) : "";
36461
36666
  if (routeInConfig) (connectEvents.json ? process.stderr : process.stdout).write(existingReport);
36462
- else if (!wroteConfig) (connectEvents.json ? process.stderr : process.stdout).write(routeBlock);
36667
+ else if (appendedToExisting) {
36668
+ (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.
36669
+ `);
36670
+ } else if (dryRun && appendReason === "dry-run") {
36671
+ (connectEvents.json ? process.stderr : process.stdout).write(`(dry run) would add the route ${route3} to ${cfg.configFile}, disabled.
36672
+ `);
36673
+ } else if (!wroteConfig) (connectEvents.json ? process.stderr : process.stdout).write(routeBlock);
36463
36674
  if (!flag("no-mcp") && apiKey) {
36464
36675
  const replace = value("mcp") === "replace";
36465
36676
  const seen = /* @__PURE__ */ new Set();
@@ -36509,6 +36720,8 @@ ${found.problems.map((p) => ` - ${p}`).join("\n")}`);
36509
36720
  }));
36510
36721
  if (!operator) process.stderr.write(` Also set operator in ${resolvedPath} before arming it.
36511
36722
  `);
36723
+ } else if (appendedToExisting) {
36724
+ if (!operator) emit.warn(`no operator resolved: set it in ${resolvedPath} before arming this route`);
36512
36725
  } else if (routeInConfig) {
36513
36726
  if (!operator) emit.warn(`no operator resolved: set it in ${resolvedPath} before arming this route`);
36514
36727
  } else if (operator) {
@@ -37062,10 +37275,10 @@ ${found.problems.map((p) => ` - ${p}`).join("\n")}`);
37062
37275
  startupSeconds: cfg.ship.intelStartupSeconds,
37063
37276
  prepare: async (path) => {
37064
37277
  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));
37278
+ const src = join68(repoWt.dir, f2);
37279
+ if (!existsSync62(src) || existsSync62(join68(path, f2))) continue;
37280
+ mkdirSync44(dirOf2(join68(path, f2)), { recursive: true });
37281
+ copyFileSync3(src, join68(path, f2));
37069
37282
  }
37070
37283
  const setup = repoWt.config.hooks.setup;
37071
37284
  return setup ? runScript(setup, { cwd: path, shell: shellWt }) : null;
@@ -37289,7 +37502,7 @@ ${found.problems.map((p) => ` - ${p}`).join("\n")}`);
37289
37502
  const shellR = hit && resolveShell(hit.repo.config.shell ?? cfg.ship.shell);
37290
37503
  const resumed = await runPeriscopeResume({
37291
37504
  find: async () => hit && { row: hit.row, tag: hit.tag },
37292
- worktreeExists: (p) => existsSync60(p),
37505
+ worktreeExists: (p) => existsSync62(p),
37293
37506
  prepareDropFile,
37294
37507
  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
37508
  relay: hit && previewRelayFor(hit.route) && {
@@ -37392,10 +37605,10 @@ ${where.join("\n")}`);
37392
37605
  },
37393
37606
  prepare: async (path) => {
37394
37607
  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));
37608
+ const src = join68(repoP.dir, f2);
37609
+ if (!existsSync62(src)) continue;
37610
+ mkdirSync44(dirOf2(join68(path, f2)), { recursive: true });
37611
+ copyFileSync3(src, join68(path, f2));
37399
37612
  }
37400
37613
  const setup = repoP.config.hooks.setup;
37401
37614
  return setup ? runScript(setup, { cwd: path, shell: shellP, onLine: (l) => {
@@ -37578,6 +37791,7 @@ ${where.join("\n")}`);
37578
37791
  }
37579
37792
  answersA.push({ label: raw.slice(0, at).trim(), detail: raw.slice(at + 2).trim() });
37580
37793
  });
37794
+ if (!new Tracker(route2, cfg.ship).questionsPart()) await refreshForRoute(route2, cfg.ship, !dryRun);
37581
37795
  const trA = new Tracker(route2, cfg.ship);
37582
37796
  const partA = trA.questionsPart();
37583
37797
  if (!partA) {
@@ -37800,7 +38014,7 @@ ${where.join("\n")}`);
37800
38014
  };
37801
38015
  const droppedRoutes = [];
37802
38016
  try {
37803
- const rawCfg = parseYaml3(readFileSync58(cfg.configFile, "utf8"));
38017
+ const rawCfg = parseYaml3(readFileSync60(cfg.configFile, "utf8"));
37804
38018
  for (const r of rawCfg?.routes ?? []) {
37805
38019
  if (typeof r?.route !== "string" || cfg.routes.some((x) => x.route === r.route)) continue;
37806
38020
  try {
@@ -37864,7 +38078,7 @@ ${where.join("\n")}`);
37864
38078
  break;
37865
38079
  }
37866
38080
  mkdirSync44(cfg.ship.stateDir, { recursive: true });
37867
- writeFileSync45(sentinel, `${(/* @__PURE__ */ new Date()).toISOString()}
38081
+ writeFileSync47(sentinel, `${(/* @__PURE__ */ new Date()).toISOString()}
37868
38082
  `);
37869
38083
  process.stdout.write(
37870
38084
  "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 +38140,7 @@ ${where.join("\n")}`);
37926
38140
  }
37927
38141
  case "log": {
37928
38142
  try {
37929
- const text2 = readFileSync58(cfg.ship.logFile, "utf8").split("\n");
38143
+ const text2 = readFileSync60(cfg.ship.logFile, "utf8").split("\n");
37930
38144
  process.stdout.write(`${text2.slice(-(Number(value("tail")) || 40)).join("\n")}
37931
38145
  `);
37932
38146
  } catch {
@@ -37950,8 +38164,8 @@ ${where.join("\n")}`);
37950
38164
  };
37951
38165
  if (!route2.resolved) fail2(`route ${route2.route} is not connected \u2014 run \`crew connect\` first`);
37952
38166
  const tracker = new Tracker(route2, cfg.ship);
37953
- const configText = readFileSync58(cfg.configFile, "utf8");
37954
- const cfgBase = dirname38(cfg.configFile);
38167
+ const configText = readFileSync60(cfg.configFile, "utf8");
38168
+ const cfgBase = dirname39(cfg.configFile);
37955
38169
  const configured2 = configuredRepos(configText, route2.route, cfgBase);
37956
38170
  const dir = configured2.find((r) => r.name === SAMPLE_REPO)?.dir ?? sampleDir(configured2.map((r) => r.dir), route2.reposBasePath, route2.route.split("/")[0]);
37957
38171
  const resolvedFile = resolvedPathFor(cfg.ship.stateDir, route2.route);
@@ -37979,7 +38193,7 @@ ${where.join("\n")}`);
37979
38193
  }
37980
38194
  if (configured2.some((r) => r.dir === dir)) {
37981
38195
  try {
37982
- writeFileSync45(cfg.configFile, planRepoRemove(configText, cfgBase, route2.route, dir).text);
38196
+ writeFileSync47(cfg.configFile, planRepoRemove(configText, cfgBase, route2.route, dir).text);
37983
38197
  } catch (e) {
37984
38198
  if (e instanceof ReposError) fail2(e.message);
37985
38199
  throw e;
@@ -37987,29 +38201,29 @@ ${where.join("\n")}`);
37987
38201
  }
37988
38202
  if (row) {
37989
38203
  await tracker.deleteRepoRow(row.id);
37990
- if (existsSync60(resolvedFile)) {
37991
- const raw = JSON.parse(readFileSync58(resolvedFile, "utf8"));
38204
+ if (existsSync62(resolvedFile)) {
38205
+ const raw = JSON.parse(readFileSync60(resolvedFile, "utf8"));
37992
38206
  if (raw.repoNames) delete raw.repoNames[row.id];
37993
38207
  if (raw.repoRemotes) delete raw.repoRemotes[row.id];
37994
- writeFileSync45(resolvedFile, `${JSON.stringify(raw, null, 2)}
38208
+ writeFileSync47(resolvedFile, `${JSON.stringify(raw, null, 2)}
37995
38209
  `);
37996
38210
  }
37997
38211
  }
37998
- if (existsSync60(join67(dir, ".git")) && basename17(dir) === SAMPLE_REPO) rmSync27(dir, { recursive: true, force: true });
38212
+ if (existsSync62(join68(dir, ".git")) && basename18(dir) === SAMPLE_REPO) rmSync27(dir, { recursive: true, force: true });
37999
38213
  say("removed", { dir, closed }, `removed the sample repo${closed.length ? `, closed ${closed.join(", ")}` : ""}`);
38000
38214
  break;
38001
38215
  }
38002
38216
  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`);
38217
+ const fresh = !existsSync62(join68(dir, ".git"));
38218
+ if (existsSync62(dir) && fresh && readdirSync22(dir).length > 0) fail2(`${dir} exists and is not a git checkout \u2014 move it aside`);
38005
38219
  if (dryRun) {
38006
38220
  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
38221
  break;
38008
38222
  }
38009
38223
  if (fresh) {
38010
38224
  mkdirSync44(dir, { recursive: true });
38011
- writeFileSync45(join67(dir, "README.md"), SAMPLE_README);
38012
- writeFileSync45(join67(dir, ".crew.yaml"), SAMPLE_CREW_YAML);
38225
+ writeFileSync47(join68(dir, "README.md"), SAMPLE_README);
38226
+ writeFileSync47(join68(dir, ".crew.yaml"), SAMPLE_CREW_YAML);
38013
38227
  const g = (...a) => {
38014
38228
  const r = spawnSync15("git", a, { cwd: dir, encoding: "utf8" });
38015
38229
  if (r.status !== 0) fail2(`git ${a[0]} failed in ${dir}: ${(r.stderr || r.stdout).trim()}`);
@@ -38027,17 +38241,17 @@ ${where.join("\n")}`);
38027
38241
  spec: { platform: "unix", releaseMode: "integrate", ciProvider: "none" }
38028
38242
  });
38029
38243
  repoId = (await tracker.createRepoRow(payload)).id;
38030
- if (existsSync60(resolvedFile)) {
38031
- const raw = JSON.parse(readFileSync58(resolvedFile, "utf8"));
38244
+ if (existsSync62(resolvedFile)) {
38245
+ const raw = JSON.parse(readFileSync60(resolvedFile, "utf8"));
38032
38246
  raw.repoNames = { ...raw.repoNames, [repoId]: SAMPLE_REPO };
38033
38247
  raw.repoRemotes = { ...raw.repoRemotes, [repoId]: SAMPLE_REMOTE };
38034
- writeFileSync45(resolvedFile, `${JSON.stringify(raw, null, 2)}
38248
+ writeFileSync47(resolvedFile, `${JSON.stringify(raw, null, 2)}
38035
38249
  `);
38036
38250
  }
38037
38251
  }
38038
38252
  if (!configured2.some((r) => r.dir === dir)) {
38039
38253
  try {
38040
- writeFileSync45(cfg.configFile, planRepoAdd({ text: configText, base: cfgBase, route: route2.route, path: dir, name: SAMPLE_REPO }).text);
38254
+ writeFileSync47(cfg.configFile, planRepoAdd({ text: configText, base: cfgBase, route: route2.route, path: dir, name: SAMPLE_REPO }).text);
38041
38255
  } catch (e) {
38042
38256
  if (e instanceof ReposError) fail2(e.message);
38043
38257
  throw e;
@@ -38369,7 +38583,7 @@ ${where.join("\n")}`);
38369
38583
  // `synthesis-tabl-123`. `worktreePrefix` above is kept for
38370
38584
  // config-provenance display; this is the field that actually
38371
38585
  // 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>`),
38586
+ worktreeDirPattern: r.config.worktrees.name ?? (r.config.provenance["worktrees.prefix"] !== "default" ? `${r.config.worktrees.prefix}<number>` : `${basename18(r.dir.replace(/[/\\]+$/, ""))}-<branch>`),
38373
38587
  worktreeParent: resolvePath(r.dir, "..")
38374
38588
  })),
38375
38589
  waiting: waiting ? { ticket: waiting.ticket, since: waiting.since, streak: fairness.streak() } : null
@@ -38472,7 +38686,7 @@ ${where.join("\n")}`);
38472
38686
  plan,
38473
38687
  label,
38474
38688
  uid: process.getuid?.() ?? 0,
38475
- system: plan.mechanism === "systemd" && existsSync60(systemUnitPathFor(label)),
38689
+ system: plan.mechanism === "systemd" && existsSync62(systemUnitPathFor(label)),
38476
38690
  stamp: readDaemonStamp(cfg.ship.stateDir)
38477
38691
  });
38478
38692
  })();
@@ -38488,7 +38702,7 @@ ${where.join("\n")}`);
38488
38702
  }
38489
38703
  for (const r of repos) {
38490
38704
  const remote = r.config.branch.remote;
38491
- if (existsSync60(r.dir)) {
38705
+ if (existsSync62(r.dir)) {
38492
38706
  pushAuth.push({
38493
38707
  route: c.route,
38494
38708
  repo: r.name,
@@ -38577,7 +38791,7 @@ ${where.join("\n")}`);
38577
38791
  else passed++;
38578
38792
  }
38579
38793
  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);
38794
+ const runtimeDir = runtimeDirWarning(process.platform, process.getuid?.() ?? null, existsSync62, userInfo2().username);
38581
38795
  if (runtimeDir) problems.push({ severity: "attention", kind: "runtime_dir_missing", message: runtimeDir });
38582
38796
  if (!flag("offline")) {
38583
38797
  const shipKind = await doctorShipKind(route2, cfg.ship);
@@ -38674,7 +38888,7 @@ routes: ${cfg.routes.map((c) => c.route).join(", ")}
38674
38888
  }
38675
38889
  try {
38676
38890
  const evFile = eventFileFor(cfg.ship.stateDir);
38677
- const evSize = existsSync60(evFile) ? statSync19(evFile).size : 0;
38891
+ const evSize = existsSync62(evFile) ? statSync20(evFile).size : 0;
38678
38892
  R.line(
38679
38893
  evSize > cfg.ship.eventsRotateBytes * 4 ? `events log: WARN ${evFile} is ${Math.round(evSize / 1048576)} MB (> 4x eventsRotateBytes); run \`crew reap\` to rotate it
38680
38894
  ` : "events log: ok\n"
@@ -38685,7 +38899,7 @@ routes: ${cfg.routes.map((c) => c.route).join(", ")}
38685
38899
  const unitPlan = planInstall(cfg.ship, CREW_HOME, host, detectSystemd(), "run", installContext());
38686
38900
  const abandons = unitAbandonsAgents(unitPlan, (p) => {
38687
38901
  try {
38688
- return readFileSync58(p, "utf8");
38902
+ return readFileSync60(p, "utf8");
38689
38903
  } catch {
38690
38904
  return null;
38691
38905
  }
@@ -38700,7 +38914,7 @@ routes: ${cfg.routes.map((c) => c.route).join(", ")}
38700
38914
  const pPlan = planInstall(cfg.ship, CREW_HOME, host, true, "passengers", installContext());
38701
38915
  const keeps = unitAbandonsAgents(pPlan, (p) => {
38702
38916
  try {
38703
- return readFileSync58(p, "utf8");
38917
+ return readFileSync60(p, "utf8");
38704
38918
  } catch {
38705
38919
  return null;
38706
38920
  }
@@ -38714,7 +38928,7 @@ routes: ${cfg.routes.map((c) => c.route).join(", ")}
38714
38928
  if (host === "linux" && detectSystemd()) {
38715
38929
  const ctl = planDaemonControl(CREW_HOME, host, true);
38716
38930
  const unitPlan = planInstall(cfg.ship, CREW_HOME, host, true, "run", installContext());
38717
- if (ctl.statusCommand && unitPlan.unitPaths.some((p) => existsSync60(p))) {
38931
+ if (ctl.statusCommand && unitPlan.unitPaths.some((p) => existsSync62(p))) {
38718
38932
  const st = spawnSync15(ctl.statusCommand[0], ctl.statusCommand.slice(1), { cwd: CREW_HOME, encoding: "utf8" });
38719
38933
  if (!st.error && st.status !== 0) {
38720
38934
  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 +38953,8 @@ routes: ${cfg.routes.map((c) => c.route).join(", ")}
38739
38953
  const changed2 = configChangedAfter(daemonConfigPaths(cfg), daemonStartedAt);
38740
38954
  if (changed2) {
38741
38955
  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\`
38956
+ 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
38957
+ ` : `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
38958
  `
38745
38959
  );
38746
38960
  }
@@ -38759,7 +38973,7 @@ routes: ${cfg.routes.map((c) => c.route).join(", ")}
38759
38973
  `);
38760
38974
  }
38761
38975
  }
38762
- for (const l of interfaceReport(await readForRoute(route2, cfg.ship), { storedMappingKey: route2.resolved?.trackerInterface?.mappingKey, contractAuthored: route2.contractAuthored })) {
38976
+ for (const l of interfaceReport(await readForRoute(route2, cfg.ship), { storedMappingKey: route2.resolved?.trackerInterface?.mappingKey, contractAuthored: route2.contractAuthored, stored: route2.resolved })) {
38763
38977
  R.line(`${l.line.startsWith(" ") ? "" : `${l.problem ? "WARN " : ""}`}${l.line}
38764
38978
  `);
38765
38979
  }
@@ -38773,7 +38987,7 @@ routes: ${cfg.routes.map((c) => c.route).join(", ")}
38773
38987
  for (const r of await resolvedRepos(route2)) {
38774
38988
  const { config } = r;
38775
38989
  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)}`);
38990
+ const worktreePattern = config.worktrees.name ?? (config.provenance["worktrees.prefix"] !== "default" ? `${config.worktrees.prefix}<number>` : `${basename18(r.dir.replace(/[/\\]+$/, ""))}-${effectiveBranchTemplate(config, void 0)}`);
38777
38991
  R.line(
38778
38992
  `${`repo ${r.name}:`.padEnd(19)}${r.dir}
38779
38993
  worktrees at ../${worktreePattern} (${config.provenance["worktrees.name"] ?? config.provenance["worktrees.prefix"] ?? "default"}), branch ${config.branch.name}