@tablation/crew 0.157.2 → 0.158.2

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 +281 -68
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -6769,6 +6769,15 @@ function agentLogRefusedItem(route2, role, status2, request2, nowIso = (/* @__PU
6769
6769
  message: `${route2}: the tracker refused ${what} (${status2}) for the ${role} seat \u2014 runs and ticket spend are not being recorded; update crew if a newer version exists, otherwise report this`
6770
6770
  };
6771
6771
  }
6772
+ var listTruncatedKey = (route2, what) => `list_truncated:${route2}:${what}`;
6773
+ function listTruncatedItem(route2, what, limit, nowIso = (/* @__PURE__ */ new Date()).toISOString()) {
6774
+ return {
6775
+ kind: "list_truncated",
6776
+ key: listTruncatedKey(route2, what),
6777
+ since: nowIso,
6778
+ message: `${route2}: the ${what} list came back full at ${limit} rows and may be missing more \u2014 decisions made from it can skip tickets; report this`
6779
+ };
6780
+ }
6772
6781
  var workspaceAuthKey = (role) => `workspace_auth:${role}`;
6773
6782
  var workspaceAllowanceKey = (role) => `workspace_allowance:${role}`;
6774
6783
  function workspaceAllowanceItem(route2, role, nowIso = (/* @__PURE__ */ new Date()).toISOString()) {
@@ -9260,16 +9269,6 @@ function isAutomatic(t, wm) {
9260
9269
  if (!wm || wm.modes.size === 0) return true;
9261
9270
  return modeOf(t, wm) === "automatic";
9262
9271
  }
9263
- function skippedByMode(tickets, wm) {
9264
- const out = { manual: 0, hybrid: 0 };
9265
- if (!wm || wm.modes.size === 0) return out;
9266
- const kept = new Set(withinWorkMode(tickets, wm));
9267
- for (const t of tickets) {
9268
- if (kept.has(t)) continue;
9269
- out[modeOf(t, wm) === "manual" ? "manual" : "hybrid"]++;
9270
- }
9271
- return out;
9272
- }
9273
9272
  function withoutManualVerified(tickets, verifiedStatus, wm) {
9274
9273
  if (!wm || wm.modes.size === 0) return tickets;
9275
9274
  return tickets.filter((t) => t.status !== verifiedStatus || modeOf(t, wm) !== "manual");
@@ -9387,7 +9386,42 @@ function referenceKeys(t) {
9387
9386
  }
9388
9387
  var RESOLVED_STATUSES = new Set(DEFAULT_CONTRACT.statuses.resolved);
9389
9388
  var encodeFilters = (f) => JSON.stringify(f);
9390
- var Tracker = class {
9389
+ var encodeSort = (s) => JSON.stringify(s);
9390
+ var LIST_PAGE_SIZE = 500;
9391
+ var LIST_MAX_PAGES = 200;
9392
+ var LIST_SORT = encodeSort([{ columnName: "id", direction: "asc" }]);
9393
+ function actionableStatuses(c) {
9394
+ const s = c.statuses;
9395
+ const named = [s.approved, s.parked, s.building, s.handoff, s.verifying, s.verified, s.needsHuman, ...s.reviewing ? [s.reviewing] : []];
9396
+ return [...new Set(named.filter((x) => c.statuses.open.includes(x)))];
9397
+ }
9398
+ function scopedTicketQueries(c, scope) {
9399
+ const status2 = c.columns.status;
9400
+ const project = c.columns.slice;
9401
+ const assignee = c.columns.assignee;
9402
+ const manual = [...scope.modes].filter(([, m]) => m === "manual").map(([id]) => id);
9403
+ const hybrid = [...scope.modes].filter(([, m]) => m === "hybrid").map(([id]) => id);
9404
+ const actionable = actionableStatuses(c);
9405
+ const pre = c.statuses.open.filter((x) => !actionable.includes(x));
9406
+ const automatic = [{ columnName: project, operator: "IS_NOT_NULL" }];
9407
+ if (manual.length + hybrid.length > 0) automatic.push({ columnName: project, operator: "NOT_IN", value: [...manual, ...hybrid] });
9408
+ const out = [[...automatic, { columnName: status2, operator: "IN", value: actionable }]];
9409
+ if (scope.triageSeat && pre.length > 0) {
9410
+ out.push([...automatic, { columnName: status2, operator: "IN", value: pre }, { columnName: assignee, operator: "EQ", value: scope.triageSeat }]);
9411
+ }
9412
+ if (hybrid.length > 0) {
9413
+ if (scope.agentAssignees.size > 0) {
9414
+ out.push([
9415
+ { columnName: project, operator: "IN", value: hybrid },
9416
+ { columnName: status2, operator: "IN", value: actionable },
9417
+ { columnName: assignee, operator: "IN", value: [...scope.agentAssignees] }
9418
+ ]);
9419
+ }
9420
+ out.push([{ columnName: project, operator: "IN", value: hybrid }, { columnName: status2, operator: "EQ", value: c.statuses.verified }]);
9421
+ }
9422
+ return out;
9423
+ }
9424
+ var Tracker = class _Tracker {
9391
9425
  // NB: explicit fields, not TypeScript parameter properties — node's
9392
9426
  // --experimental-strip-types cannot transform those, and the test runner
9393
9427
  // uses it. The same rule applies everywhere in src/.
@@ -9433,25 +9467,83 @@ var Tracker = class {
9433
9467
  });
9434
9468
  }
9435
9469
  /**
9436
- * Every non-terminal ticket for this route's area, in one call.
9470
+ * Every non-terminal ticket for this route's area, paged to the end
9471
+ * (CREW-3453: one `limit: 500` request silently dropped everything past the
9472
+ * newest 500 once a bulk import filled the board with `new` tickets).
9437
9473
  *
9438
9474
  * The area filter is what keeps two routes on one tracker out of each
9439
9475
  * other's queue: a ship working `synthesis` and `tablation-js` from the same
9440
9476
  * Issues project must not have either seat pick up the other's tickets. A
9441
9477
  * route with no area sees everything, which is right for a tracker
9442
9478
  * nobody has sliced yet.
9479
+ *
9480
+ * With a `scope` (the poll's), only what a lane can act on is asked for; see
9481
+ * `TicketScope`. Without one, every open ticket comes back, which is what the
9482
+ * operator-facing views (`status`, `inbox`, `doctor`) want.
9443
9483
  */
9444
- async openTickets() {
9484
+ async openTickets(scope) {
9445
9485
  const c = this.contract;
9446
- const filters = [
9447
- { columnName: c.columns.status, operator: "IN", value: c.statuses.open }
9448
- ];
9486
+ const base = [];
9449
9487
  const areaId = this.route.resolved?.areaId;
9450
- if (areaId) filters.push({ columnName: c.columns.slice, operator: "EQ", value: areaId });
9451
- return this.client.records.list(this.models.issues, {
9452
- filters: encodeFilters(filters),
9453
- limit: 500
9454
- });
9488
+ if (areaId) base.push({ columnName: c.columns.slice, operator: "EQ", value: areaId });
9489
+ const queries = scope && scope.modes.size > 0 ? scopedTicketQueries(c, scope) : [[{ columnName: c.columns.status, operator: "IN", value: c.statuses.open }]];
9490
+ const seen = /* @__PURE__ */ new Map();
9491
+ for (const q2 of queries) {
9492
+ for (const t of await this.listAll(this.models.issues, "open tickets", encodeFilters([...base, ...q2]))) seen.set(t.id, t);
9493
+ }
9494
+ return [...seen.values()];
9495
+ }
9496
+ /**
9497
+ * How many open tickets match `extra` (a `crew status` number or the sweep
9498
+ * summary's skipped-by-mode count), from the count endpoint rather than
9499
+ * downloaded rows. `undefined` when the count cannot be read.
9500
+ */
9501
+ async countOpenTickets(extra) {
9502
+ const c = this.contract;
9503
+ const conds = [{ columnName: c.columns.status, operator: "IN", value: c.statuses.open }, ...extra];
9504
+ const areaId = this.route.resolved?.areaId;
9505
+ if (areaId) conds.push({ columnName: c.columns.slice, operator: "EQ", value: areaId });
9506
+ try {
9507
+ const res = await this.eventsFetch("GET", `/records/count?filters=${encodeURIComponent(encodeFilters(conds))}`);
9508
+ if (!res.ok) return void 0;
9509
+ const body = await res.json();
9510
+ return typeof body.count === "number" ? body.count : void 0;
9511
+ } catch {
9512
+ return void 0;
9513
+ }
9514
+ }
9515
+ /**
9516
+ * Lists the tracker has handed back full and this process had no way to
9517
+ * read past, by what they were (CREW-3453). A decision made from a cut-off
9518
+ * list is wrong without saying so, so every reader that can be cut off calls
9519
+ * `noteTruncated`, and the poll turns what is here into an attention item.
9520
+ */
9521
+ truncated = /* @__PURE__ */ new Map();
9522
+ /** The page backstop `listAll` stops at; a variable only so a test can reach it without a hundred thousand rows. */
9523
+ static maxPages = LIST_MAX_PAGES;
9524
+ /** Records that the list `what` hit `limit` rows and may be missing more. */
9525
+ noteTruncated(what, limit) {
9526
+ this.truncated.set(what, limit);
9527
+ }
9528
+ /**
9529
+ * Every row of `model` matching `filters`, paged until a short page. Sorted by
9530
+ * `id` so the offset windows neither skip nor repeat a row while the table
9531
+ * changes under the read.
9532
+ */
9533
+ async listAll(model, what, filters) {
9534
+ const out = [];
9535
+ for (let page = 0; page < _Tracker.maxPages; page++) {
9536
+ const rows = await this.client.records.list(model, {
9537
+ ...filters ? { filters } : {},
9538
+ limit: LIST_PAGE_SIZE,
9539
+ offset: page * LIST_PAGE_SIZE,
9540
+ sort: LIST_SORT
9541
+ });
9542
+ out.push(...rows);
9543
+ if (rows.length < LIST_PAGE_SIZE) return out;
9544
+ }
9545
+ this.noteTruncated(what, LIST_PAGE_SIZE * _Tracker.maxPages);
9546
+ return out;
9455
9547
  }
9456
9548
  /**
9457
9549
  * Tickets at the hand-off status whose row changed at or after `since`,
@@ -9459,10 +9551,11 @@ var Tracker = class {
9459
9551
  */
9460
9552
  async handedOffSince(since2, exceptId) {
9461
9553
  const c = this.contract;
9462
- const rows = await this.client.records.list(this.models.issues, {
9463
- filters: encodeFilters([{ columnName: c.columns.status, operator: "EQ", value: c.statuses.handoff }]),
9464
- limit: 100
9465
- });
9554
+ const rows = await this.listAll(
9555
+ this.models.issues,
9556
+ "handed-off tickets",
9557
+ encodeFilters([{ columnName: c.columns.status, operator: "EQ", value: c.statuses.handoff }])
9558
+ );
9466
9559
  const from = Date.parse(since2);
9467
9560
  return rows.filter((t) => t.id !== exceptId && Date.parse(t.updated_at) >= from);
9468
9561
  }
@@ -9508,23 +9601,44 @@ var Tracker = class {
9508
9601
  * from the open set. Bounded to the ids actually referenced.
9509
9602
  */
9510
9603
  async ticketsByIds(ids) {
9511
- if (ids.length === 0) return [];
9512
- return this.client.records.list(this.models.issues, {
9513
- filters: encodeFilters([{ columnName: "id", operator: "IN", value: ids }]),
9514
- limit: 500
9515
- });
9604
+ return this.ticketsByIn("id", ids);
9516
9605
  }
9517
9606
  /** Tickets by `issue_id` (CREW-3323: resolving a run's key to its display tag). */
9518
9607
  async ticketsByKeys(keys) {
9519
- if (keys.length === 0) return [];
9520
- return this.client.records.list(this.models.issues, {
9521
- filters: encodeFilters([{ columnName: this.contract.columns.key, operator: "IN", value: keys }]),
9522
- limit: 500
9523
- });
9608
+ return this.ticketsByIn(this.contract.columns.key, keys);
9609
+ }
9610
+ /** IN lists go in the URL, so each request carries at most 100 values; every request is paged. */
9611
+ async ticketsByIn(column, values) {
9612
+ const out = [];
9613
+ for (let i = 0; i < values.length; i += 100) {
9614
+ out.push(...await this.listAll(
9615
+ this.models.issues,
9616
+ "tickets by lookup",
9617
+ encodeFilters([{ columnName: column, operator: "IN", value: values.slice(i, i + 100) }])
9618
+ ));
9619
+ }
9620
+ return out;
9524
9621
  }
9525
9622
  async ticket(id) {
9526
9623
  return this.client.records.get(this.models.issues, id);
9527
9624
  }
9625
+ /**
9626
+ * Every comment on the given tickets, paged (CREW-3453). The poll feeds hold
9627
+ * answers, the new-comment signal and the digest from this, so a fixed window
9628
+ * of the newest rows would drop an older ticket's answer once the board's
9629
+ * comments outgrow it. IN lists carry at most 100 ids per request.
9630
+ */
9631
+ async commentsForTickets(ticketIds) {
9632
+ const out = [];
9633
+ for (let i = 0; i < ticketIds.length; i += 100) {
9634
+ out.push(...await this.listAll(
9635
+ this.models.comments,
9636
+ "comments",
9637
+ encodeFilters([{ columnName: this.contract.comments.parent, operator: "IN", value: ticketIds.slice(i, i + 100) }])
9638
+ ));
9639
+ }
9640
+ return out;
9641
+ }
9528
9642
  async comments(limit = 500) {
9529
9643
  return this.client.records.list(this.models.comments, { limit });
9530
9644
  }
@@ -9538,7 +9652,7 @@ var Tracker = class {
9538
9652
  }
9539
9653
  }
9540
9654
  async crewRows() {
9541
- return this.client.records.list(this.models.crew, { limit: 200 });
9655
+ return this.listAll(this.models.crew, "Crew rows");
9542
9656
  }
9543
9657
  /**
9544
9658
  * One row of the `Repos` table, for whatever it can tell the crew that
@@ -9578,7 +9692,7 @@ var Tracker = class {
9578
9692
  const model = this.route.resolved?.areaModelId;
9579
9693
  if (!model) return /* @__PURE__ */ new Map();
9580
9694
  try {
9581
- const rows = await this.client.records.list(model, { limit: 200 });
9695
+ const rows = await this.listAll(model, "Projects");
9582
9696
  return projectWorkModes(rows, this.contract);
9583
9697
  } catch {
9584
9698
  return /* @__PURE__ */ new Map();
@@ -9588,7 +9702,7 @@ var Tracker = class {
9588
9702
  async projectRows() {
9589
9703
  const model = this.route.resolved?.areaModelId;
9590
9704
  if (!model) return [];
9591
- return this.client.records.list(model, { limit: 200 });
9705
+ return this.listAll(model, "Projects");
9592
9706
  }
9593
9707
  /** Create a `Projects` (area) row (CREW-3359). Throws when the workspace has no Projects table. */
9594
9708
  async createProjectRow(fields) {
@@ -9619,13 +9733,13 @@ var Tracker = class {
9619
9733
  async repoRows() {
9620
9734
  const model = this.route.resolved?.reposModelId;
9621
9735
  if (!model) return [];
9622
- return this.client.records.list(model, { limit: 200 });
9736
+ return this.listAll(model, "Repos");
9623
9737
  }
9624
9738
  /** Every `Repos` row with the columns the resolved file mirrors (CREW-2885). */
9625
9739
  async repoRowsForMap() {
9626
9740
  const model = this.route.resolved?.reposModelId;
9627
9741
  if (!model) return [];
9628
- return this.client.records.list(model, { limit: 200 });
9742
+ return this.listAll(model, "Repos");
9629
9743
  }
9630
9744
  /** Delete a `Repos` row (`crew sample-ticket --remove`). */
9631
9745
  async deleteRepoRow(id) {
@@ -9635,10 +9749,11 @@ var Tracker = class {
9635
9749
  }
9636
9750
  /** Every ticket filed against one `Repos` row, any status. */
9637
9751
  async ticketsForRepo(repoId) {
9638
- return this.client.records.list(this.models.issues, {
9639
- filters: encodeFilters([{ columnName: this.contract.columns.repo, operator: "EQ", value: repoId }]),
9640
- limit: 200
9641
- });
9752
+ return this.listAll(
9753
+ this.models.issues,
9754
+ "tickets of a repo",
9755
+ encodeFilters([{ columnName: this.contract.columns.repo, operator: "EQ", value: repoId }])
9756
+ );
9642
9757
  }
9643
9758
  /**
9644
9759
  * The Ships rows of this workspace, if it has a Ships table.
@@ -9650,7 +9765,7 @@ var Tracker = class {
9650
9765
  const model = this.route.resolved?.shipsModelId;
9651
9766
  if (!model) return [];
9652
9767
  try {
9653
- return await this.client.records.list(model, { limit: 200 });
9768
+ return await this.listAll(model, "Ships");
9654
9769
  } catch {
9655
9770
  return [];
9656
9771
  }
@@ -9840,7 +9955,7 @@ var Tracker = class {
9840
9955
  const model = this.route.resolved?.epicsModelId;
9841
9956
  if (!model) return [];
9842
9957
  try {
9843
- return await this.client.records.list(model, { limit: 500 });
9958
+ return await this.listAll(model, "Epics");
9844
9959
  } catch {
9845
9960
  return [];
9846
9961
  }
@@ -19460,15 +19575,23 @@ async function decideCycle(o) {
19460
19575
  return fallback;
19461
19576
  }
19462
19577
  };
19463
- const [tickets, comments, crewRows, epicRows, ships, projectModes, stalledEvents] = await Promise.all([
19464
- tracker.openTickets(),
19465
- tracker.comments(200),
19578
+ const [crewRows, projectModes] = await Promise.all([
19466
19579
  tracker.crewRows(),
19580
+ optional("project work modes", tracker.projectWorkModes(), /* @__PURE__ */ new Map())
19581
+ ]);
19582
+ const scopeHolds = new Set(holdIds(buildRoster(configuredMembers(route2), crewRows)));
19583
+ const scope = {
19584
+ modes: projectModes,
19585
+ agentAssignees: agentAssigneeIds(crewRows, (id) => scopeHolds.has(id)),
19586
+ triageSeat: route2.resolved?.seats.triage
19587
+ };
19588
+ const [tickets, epicRows, ships, stalledEvents] = await Promise.all([
19589
+ tracker.openTickets(scope),
19467
19590
  optional("epics", tracker.epicRows(), []),
19468
19591
  optional("ships", tracker.shipRows(), []),
19469
- optional("project work modes", tracker.projectWorkModes(), /* @__PURE__ */ new Map()),
19470
19592
  tracker.events("stalled")
19471
19593
  ]);
19594
+ const comments = await tracker.commentsForTickets(tickets.map((t) => t.id));
19472
19595
  const directionEvents = (await Promise.all([...DIRECTION_EVENT_TYPES, ...STATUS_EVENT_TYPES, "pushed"].map((t) => tracker.events(t)))).flat();
19473
19596
  const statusChanges = await tracker.statusChanges();
19474
19597
  emit.note(`${tickets.length} open ticket(s), ${comments.length} comment(s)`, {
@@ -19501,6 +19624,7 @@ async function decideCycle(o) {
19501
19624
  }
19502
19625
  const extra = await tracker.ticketsByIds(missingBlockerIds(tickets));
19503
19626
  const info = blockerInfoMap(tickets, extra);
19627
+ await reportTruncated(tracker, route2.route, state, emit);
19504
19628
  const blocked = computeBlockedIds(tickets, info);
19505
19629
  const footprintEvents = await optional("footprint events", readFootprintEvents(tracker), { declared: /* @__PURE__ */ new Map(), pushed: /* @__PURE__ */ new Map() });
19506
19630
  const footprintPlan = planFootprintsFor(route2, tickets, footprintEvents, new Set(blocked));
@@ -19517,7 +19641,7 @@ async function decideCycle(o) {
19517
19641
  const sweep = planSweep(tickets, info, blocked, workModes, footprintPlan.waits);
19518
19642
  const holdReleases = planHoldReleases(tickets, tracker.contract);
19519
19643
  const stalled = planStalled(tickets, comments, ships, tracker.contract, holds2, Date.now(), workModes, stalledEvents);
19520
- const skipped = skippedByMode(tickets, workModes);
19644
+ const skipped = await skippedCounts(tracker, tickets, projectModes);
19521
19645
  if (skipped.manual || skipped.hybrid) {
19522
19646
  emit.note(`sweeps skipped ${skipped.manual} manual/project-less and ${skipped.hybrid} unassigned hybrid ticket(s)`, {
19523
19647
  data: { sweepSkipped: skipped }
@@ -19771,6 +19895,33 @@ ${body}` : body;
19771
19895
  function rosterFor(d, route2, role) {
19772
19896
  return rosterMarkdown(d.roster, route2.resolved.seats[role] ?? null);
19773
19897
  }
19898
+ async function skippedCounts(tracker, tickets, modes) {
19899
+ if (modes.size === 0) return { manual: 0, hybrid: 0 };
19900
+ const c = tracker.contract;
19901
+ const idsOf = (m) => [...modes].filter(([, v]) => v === m).map(([id]) => id);
19902
+ const manualIds = idsOf("manual");
19903
+ const hybridIds = idsOf("hybrid");
19904
+ const col = c.columns.slice;
19905
+ const [none, manual, hybrid] = await Promise.all([
19906
+ tracker.countOpenTickets([{ columnName: col, operator: "IS_NULL" }]),
19907
+ manualIds.length ? tracker.countOpenTickets([{ columnName: col, operator: "IN", value: manualIds }]) : Promise.resolve(0),
19908
+ hybridIds.length ? tracker.countOpenTickets([{ columnName: col, operator: "IN", value: hybridIds }]) : Promise.resolve(0)
19909
+ ]);
19910
+ const hybridFetched = tickets.filter((t) => t.project_id && hybridIds.includes(t.project_id)).length;
19911
+ return { manual: (none ?? 0) + (manual ?? 0), hybrid: Math.max(0, (hybrid ?? 0) - hybridFetched) };
19912
+ }
19913
+ async function reportTruncated(tracker, route2, state, emit) {
19914
+ const prefix = listTruncatedKey(route2, "");
19915
+ const live2 = /* @__PURE__ */ new Set();
19916
+ for (const [what, limit] of tracker.truncated) {
19917
+ const item = listTruncatedItem(route2, what, limit);
19918
+ live2.add(item.key);
19919
+ await raiseShipAttention({ state, emit }, item);
19920
+ }
19921
+ for (const i of openShipAttention(state)) {
19922
+ if (i.kind === "list_truncated" && i.key.startsWith(prefix) && !live2.has(i.key)) clearShipAttention(state, i.key);
19923
+ }
19924
+ }
19774
19925
 
19775
19926
  // src/claim.ts
19776
19927
  import { StaleWriteError as StaleWriteError6 } from "@tablation/client";
@@ -26657,13 +26808,16 @@ async function discover(o) {
26657
26808
  }
26658
26809
  if (shipRowId) {
26659
26810
  const releaseId = stored?.releaseSeat && scoped.some((r) => r.id === stored.releaseSeat) ? stored.releaseSeat : void 0;
26660
- if (releaseId) out.releaseSeat = releaseId;
26661
- else {
26811
+ if (releaseId) {
26812
+ out.releaseSeat = releaseId;
26813
+ out.releaseSeatAction = "matched";
26814
+ } else {
26662
26815
  const created = await post2(o, `/data-models/${out.models.crew}/records`, {
26663
26816
  name: "Release agent",
26664
26817
  ship_id: shipRowId
26665
26818
  });
26666
26819
  out.releaseSeat = created.id;
26820
+ out.releaseSeatAction = "created";
26667
26821
  provisioning.push("created Crew row for the release seat");
26668
26822
  }
26669
26823
  }
@@ -26770,12 +26924,11 @@ async function createOperatorRow(o, found) {
26770
26924
  }
26771
26925
  }
26772
26926
  function renderConnection(d, route2, dir, opts = {}) {
26773
- const apiKeyFileLine = opts.keychainBacked ? "" : opts.apiKeyFile ? ` apiKeyFile: "${opts.apiKeyFile}"` : ` apiKeyFile: "REPLACE \u2014 a file holding this workspace's key"`;
26774
- const apiKeyVarLine = opts.keychainBacked ? "" : opts.apiKeyVar ? `
26775
- apiKeyVar: ${opts.apiKeyVar}` : `
26776
- apiKeyVar: REPLACE_KEY_VAR`;
26777
- const baseUrlLine = opts.baseUrl ? opts.baseUrl.replace(/\/+$/, "") === DEFAULT_BASE_URL ? "" : ` baseUrl: "${opts.baseUrl}"
26778
- ` : ' baseUrl: "REPLACE \u2014 the same baseUrl as your other routes"\n';
26927
+ const apiKeyFileLine = !opts.keychainBacked && opts.apiKeyFile ? ` apiKeyFile: "${opts.apiKeyFile}"` : "";
26928
+ const apiKeyVarLine = !opts.keychainBacked && opts.apiKeyFile && opts.apiKeyVar ? `
26929
+ apiKeyVar: ${opts.apiKeyVar}` : "";
26930
+ const baseUrlLine = opts.baseUrl && opts.baseUrl.replace(/\/+$/, "") !== DEFAULT_BASE_URL ? ` baseUrl: "${opts.baseUrl}"
26931
+ ` : "";
26779
26932
  const keyLines = [apiKeyFileLine, apiKeyVarLine.replace(/^\n/, "")].filter(Boolean).join("\n");
26780
26933
  return ` - route: ${route2}
26781
26934
  enabled: false # set to true once \`crew doctor\` is green
@@ -26783,6 +26936,27 @@ ${opts.area ? ` area: "${opts.area}"
26783
26936
  ` : ""}${dir === null ? "" : ` dir: "${dir}"
26784
26937
  `}${baseUrlLine}${opts.hostPassengers ? " hostPassengers: true\n" : ""}${keyLines ? keyLines + "\n" : ""}`;
26785
26938
  }
26939
+ function renderExistingRouteReport(o) {
26940
+ const seatRows = new Map((o.found.seatRows ?? []).map((r) => [r.role, r]));
26941
+ const keyOf = (role) => o.keys?.find((k) => k.role === role)?.action;
26942
+ const lines2 = [];
26943
+ for (const role of ["dev", "design", "qa", "triage"]) {
26944
+ const row = seatRows.get(role);
26945
+ lines2.push(row ? { role, ...row.id ? { id: row.id } : {}, outcome: row.action, key: keyOf(role) } : o.found.seats[role] ? { role, id: o.found.seats[role], outcome: "matched", key: keyOf(role) } : { role, outcome: "unresolved" });
26946
+ }
26947
+ lines2.push(o.found.seats.pair ? { role: "pair", id: o.found.seats.pair, outcome: "matched" } : { role: "pair", outcome: "unresolved" });
26948
+ lines2.push(o.found.releaseSeat ? { role: "release", id: o.found.releaseSeat, outcome: o.found.releaseSeatAction ?? "matched" } : { role: "release", outcome: "unresolved" });
26949
+ const out = [
26950
+ `${o.configFile} already has the route "${o.route}"; it was not changed.`,
26951
+ o.resolvedPath ? `${o.dryRun ? "(dry run) would write" : "Resolved ids written to"} ${o.resolvedPath}` : "",
26952
+ "Seats:",
26953
+ ...lines2.map((l) => ` ${l.role.padEnd(8)} ${l.id ? `Crew row ${l.id}` : "no Crew row"} \u2014 ${l.outcome}${l.key && l.key !== "none" ? `; key ${l.key}` : ""}`),
26954
+ "",
26955
+ `Next: crew doctor ${o.route}`
26956
+ ].filter((l, i, a) => l !== "" || i === a.length - 2);
26957
+ return `${out.join("\n")}
26958
+ `;
26959
+ }
26786
26960
 
26787
26961
  // src/cli.ts
26788
26962
  import {
@@ -28366,7 +28540,7 @@ import { dirname as dirOf2, resolve as resolvePath } from "path";
28366
28540
  import { existsSync as existsSync56, readdirSync as readdirSync18, statSync as statSync17 } from "fs";
28367
28541
  import { join as join60 } from "path";
28368
28542
  function builtVersion() {
28369
- return true ? "0.157.2" : null;
28543
+ return true ? "0.158.2" : null;
28370
28544
  }
28371
28545
  var REBUILD_HINT = "rebuild with npm run build";
28372
28546
  function newestMtime(path) {
@@ -34470,10 +34644,36 @@ ${found.problems.map((p) => ` - ${p}`).join("\n")}`, "fix the problems above, t
34470
34644
  emit.error(`crew connect: ${msg}`);
34471
34645
  stopWithProblem(msg, "wizard");
34472
34646
  }
34473
- if ((mintedFromDevice || firstRunFromFlags) && !keychainBacked) {
34647
+ const storeLabel = () => {
34648
+ const r = describeSecretStore();
34649
+ return r.kind === "file" && r.dir ? `the key store under ${r.dir}` : "the OS keychain";
34650
+ };
34651
+ const keyFromFlag = givenKeySource === "flag" && !mintedFromDevice && !!apiKey;
34652
+ if (keyFromFlag && !keychainBacked && store) {
34653
+ if (dryRun) {
34654
+ keychainBacked = true;
34655
+ routineLine(`(dry run) would store the key in ${storeLabel()} for ${hostFromUrl4(baseUrl)}/${found.workspaceSlug}`);
34656
+ } else {
34657
+ try {
34658
+ await store.set(hostFromUrl4(baseUrl), found.workspaceSlug, {
34659
+ apiKey,
34660
+ workspaceId: found.workspaceId,
34661
+ identityId: found.meId ?? "",
34662
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
34663
+ });
34664
+ keychainBacked = true;
34665
+ sessionAddress = found.workspaceSlug;
34666
+ rememberSession(cfg.ship.stateDir, hostFromUrl4(baseUrl), found.workspaceSlug);
34667
+ routineLine(`API key stored in ${storeLabel()} for ${hostFromUrl4(baseUrl)}/${found.workspaceSlug}.`);
34668
+ } catch (e) {
34669
+ emit.warn(withFix(`could not store the key in ${storeLabel()} \u2014 ${e.message} \u2014 falling back to a key file`, "`crew doctor`"));
34670
+ }
34671
+ }
34672
+ }
34673
+ if ((mintedFromDevice || firstRunFromFlags || keyFromFlag) && !keychainBacked) {
34474
34674
  apiKeyFile = apiKeyPathFor(cfg.ship.stateDir, route3);
34475
34675
  if (dryRun) {
34476
- process.stderr.write(`(dry run) would write the minted API key to ${apiKeyFile}
34676
+ process.stderr.write(`(dry run) would write the API key to ${apiKeyFile}
34477
34677
  `);
34478
34678
  } else {
34479
34679
  mkdirSync43(dirname38(apiKeyFile), { recursive: true });
@@ -34489,13 +34689,14 @@ ${found.problems.map((p) => ` - ${p}`).join("\n")}`, "fix the problems above, t
34489
34689
  const routeBlock = renderConnection(
34490
34690
  found,
34491
34691
  route3,
34492
- routeDir ?? (writeFirstRun ? null : "REPLACE \u2014 the local checkout this route works"),
34692
+ routeDir ?? null,
34493
34693
  {
34494
34694
  area: value("area"),
34495
34695
  apiKeyFile,
34496
34696
  apiKeyVar: apiKeyFile ? apiKeyVar : void 0,
34497
34697
  keychainBacked,
34498
- ...writeFirstRun ? { baseUrl, hostPassengers: wizard.answers.hostPassengers } : {}
34698
+ baseUrl,
34699
+ ...writeFirstRun ? { hostPassengers: wizard.answers.hostPassengers } : {}
34499
34700
  }
34500
34701
  );
34501
34702
  let wroteConfig = false;
@@ -34514,7 +34715,17 @@ ${found.problems.map((p) => ` - ${p}`).join("\n")}`, "fix the problems above, t
34514
34715
  connectEvents.emit("config", `${cfg.configFile} already exists; left alone`, { written: false, path: cfg.configFile, reason: "exists" });
34515
34716
  }
34516
34717
  }
34517
- if (!wroteConfig) (connectEvents.json ? process.stderr : process.stdout).write(routeBlock);
34718
+ const routeInConfig = cfg.routes.some((r) => r.route === route3);
34719
+ const existingReport = routeInConfig ? renderExistingRouteReport({
34720
+ route: route3,
34721
+ configFile: cfg.configFile,
34722
+ resolvedPath,
34723
+ dryRun,
34724
+ found,
34725
+ keys: mintOutcomes.map((m) => ({ role: m.role, action: m.action }))
34726
+ }) : "";
34727
+ if (routeInConfig) (connectEvents.json ? process.stderr : process.stdout).write(existingReport);
34728
+ else if (!wroteConfig) (connectEvents.json ? process.stderr : process.stdout).write(routeBlock);
34518
34729
  if (!flag("no-mcp") && apiKey) {
34519
34730
  const replace = value("mcp") === "replace";
34520
34731
  const seen = /* @__PURE__ */ new Set();
@@ -34564,17 +34775,19 @@ ${found.problems.map((p) => ` - ${p}`).join("\n")}`);
34564
34775
  }));
34565
34776
  if (!operator) process.stderr.write(` Also set operator in ${resolvedPath} before arming it.
34566
34777
  `);
34778
+ } else if (routeInConfig) {
34779
+ if (!operator) emit.warn(`no operator resolved: set it in ${resolvedPath} before arming this route`);
34567
34780
  } else if (operator) {
34568
34781
  process.stderr.write(
34569
34782
  `
34570
- Paste the block above under routes: in crew.yaml (if "${route3}" isn't there already), then: crew doctor ${route3}
34783
+ Paste the block above under routes: in crew.yaml, then: crew doctor ${route3}
34571
34784
  `
34572
34785
  );
34573
34786
  } else {
34574
34787
  process.stderr.write(
34575
34788
  `
34576
- Paste the block above under routes: in crew.yaml (if "${route3}" isn't there
34577
- already), set operator in ${resolvedPath}, then: crew doctor ${route3}
34789
+ Paste the block above under routes: in crew.yaml, set operator in
34790
+ ${resolvedPath}, then: crew doctor ${route3}
34578
34791
  `
34579
34792
  );
34580
34793
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tablation/crew",
3
- "version": "0.157.2",
3
+ "version": "0.158.2",
4
4
  "description": "A standing team of headless agents that picks work off a Tablation board, does it on a machine you control, and reports back.",
5
5
  "type": "module",
6
6
  "license": "MIT",