@tablation/crew 0.130.7 → 0.131.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/cli.js +167 -14
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -18241,6 +18241,91 @@ function flagWizardAnswers(f, env) {
18241
18241
  };
18242
18242
  }
18243
18243
 
18244
+ // src/diagnostics.ts
18245
+ import { execFile as execFile3 } from "child_process";
18246
+ var BUNDLE_BUDGET_MS = 3e4;
18247
+ var JOURNAL_LINES = 200;
18248
+ var MAX_SECTION_BYTES = 256 * 1024;
18249
+ var REDACTED = "[redacted]";
18250
+ var SENSITIVE_KEY_RE = /token|key|secret|password|authorization/i;
18251
+ var SK_RE = /\bsk_[A-Za-z0-9_-]{4,}/g;
18252
+ var BEARER_RE = /\b(bearer)\s+[A-Za-z0-9._~+/=-]{4,}/gi;
18253
+ var AUTH_HEADER_RE = /\b(authorization)(["']?\s*[:=]\s*["']?)[^\s"',}]+(?:\s+[^\s"',}]+)?/gi;
18254
+ var KV_RE = /\b([A-Za-z0-9_.-]*(?:token|key|secret|password)[A-Za-z0-9_.-]*)(["']?\s*[:=]\s*["']?)[^\s"',}&]+/gi;
18255
+ function redactText(s) {
18256
+ return s.replace(AUTH_HEADER_RE, (_m, k, sep2) => `${k}${sep2}${REDACTED}`).replace(BEARER_RE, (_m, b) => `${b} ${REDACTED}`).replace(SK_RE, REDACTED).replace(KV_RE, (m, k, sep2) => m.endsWith(REDACTED) ? m : `${k}${sep2}${REDACTED}`);
18257
+ }
18258
+ function redactValue(v) {
18259
+ if (typeof v === "string") return redactText(v);
18260
+ if (Array.isArray(v)) return v.map(redactValue);
18261
+ if (v && typeof v === "object") {
18262
+ return Object.fromEntries(Object.entries(v).map(([k, x]) => [
18263
+ k,
18264
+ SENSITIVE_KEY_RE.test(k) && x !== null && x !== void 0 && x !== "" ? REDACTED : redactValue(x)
18265
+ ]));
18266
+ }
18267
+ return v;
18268
+ }
18269
+ var defaultExec = (bin, args, timeoutMs) => new Promise((resolve8, reject) => {
18270
+ execFile3(bin, args, { timeout: timeoutMs, maxBuffer: 4 * 1024 * 1024 }, (e, stdout) => {
18271
+ if (e && e.code === "ENOENT") return reject(new Error(`${bin} is not installed`));
18272
+ if (e && e.killed) return reject(new Error(`${bin} timed out`));
18273
+ resolve8({ stdout: String(stdout), code: typeof e?.code === "number" ? e.code : 0 });
18274
+ });
18275
+ });
18276
+ var clip = (s) => s.length > MAX_SECTION_BYTES ? `${s.slice(0, MAX_SECTION_BYTES)}
18277
+ [truncated]` : s;
18278
+ async function collectDiagnostics(d) {
18279
+ const exec = d.exec ?? defaultExec;
18280
+ const budget = d.budgetMs ?? BUNDLE_BUDGET_MS;
18281
+ const now = d.now ?? Date.now;
18282
+ const started = now();
18283
+ const left = () => Math.max(1, budget - (now() - started));
18284
+ const ctl = d.userScope ? ["systemctl", "--user"] : ["systemctl"];
18285
+ const jctl = d.userScope ? ["--user"] : [];
18286
+ const units = d.unitStems.flatMap((s) => [`${s}.service`, `${s}.timer`]);
18287
+ const sections = {
18288
+ doctor: async () => {
18289
+ const doc = await d.doctor();
18290
+ if (!doc) throw new Error("could not produce the doctor report");
18291
+ return doc;
18292
+ },
18293
+ units: async () => {
18294
+ if (!units.length) throw new Error("no systemd units on this host");
18295
+ const out = {};
18296
+ for (const u of units) {
18297
+ const r = await exec(ctl[0], [...ctl.slice(1), "show", u, "--no-pager", "--property=LoadState,ActiveState,SubState,Result,ExecMainStatus,ActiveEnterTimestamp"], left());
18298
+ out[u] = Object.fromEntries(r.stdout.split("\n").filter((l) => l.includes("=")).map((l) => [l.slice(0, l.indexOf("=")), l.slice(l.indexOf("=") + 1)]));
18299
+ }
18300
+ return out;
18301
+ },
18302
+ journal: async () => {
18303
+ if (!units.length) throw new Error("no systemd units on this host");
18304
+ const r = await exec("journalctl", [...jctl, ...units.flatMap((u) => ["-u", u]), "-n", String(JOURNAL_LINES), "--no-pager", "-o", "short-iso"], left());
18305
+ return { lines: clip(r.stdout).split("\n").filter((l) => l.length) };
18306
+ },
18307
+ tunnel: async () => Object.fromEntries(d.workspaceIds.map((w) => [w, readPersistedTunnel(d.stateDir, w) ?? null])),
18308
+ sandbox: async () => {
18309
+ if (d.runner !== "sandbox") return { runner: d.runner };
18310
+ const r = await exec("openshell", ["sandbox", "list"], left());
18311
+ return { runner: d.runner, list: clip(r.stdout).split("\n").filter((l) => l.length), exitCode: r.code };
18312
+ }
18313
+ };
18314
+ const deadline = new Promise((resolve8) => {
18315
+ setTimeout(() => resolve8("timeout"), budget).unref();
18316
+ });
18317
+ const entries = await Promise.all(Object.entries(sections).map(async ([name, run3]) => {
18318
+ try {
18319
+ const out = await Promise.race([run3(), deadline]);
18320
+ if (out === "timeout") return [name, { ok: false, error: `timed out after ${Math.round(budget / 1e3)}s` }];
18321
+ return [name, { ok: true, data: redactValue(out) }];
18322
+ } catch (e) {
18323
+ return [name, { ok: false, error: redactText(e.message) }];
18324
+ }
18325
+ }));
18326
+ return { collectedAt: new Date(started).toISOString(), budgetMs: budget, sections: Object.fromEntries(entries) };
18327
+ }
18328
+
18244
18329
  // src/release-run.ts
18245
18330
  import { readFileSync as readFileSync37, writeFileSync as writeFileSync31, existsSync as existsSync38, copyFileSync, mkdirSync as mkdirSync28, mkdtempSync as mkdtempSync3, rmSync as rmSync19 } from "fs";
18246
18331
  import { dirname as dirname24, join as join43 } from "path";
@@ -20087,13 +20172,25 @@ function firstReport(key) {
20087
20172
  reported.add(key);
20088
20173
  return true;
20089
20174
  }
20175
+ function judgeServable(o) {
20176
+ if (o.platforms.some(o.satisfied)) return true;
20177
+ return o.tolerateUnmirrored && o.unreadable.some((n) => o.unmirrored.has(n));
20178
+ }
20179
+ function explainRefusal(readable, unreadable) {
20180
+ const parts = [
20181
+ ...readable.map((r) => `${r.name} requires ${r.platform}`),
20182
+ ...unreadable.map((e) => `${e.repo}'s contract could not be read (${e.detail.split("\n")[0]})`)
20183
+ ];
20184
+ if (readable.length === 0) parts.unshift("no repository contract could be read");
20185
+ return parts.join(", ");
20186
+ }
20090
20187
 
20091
20188
  // src/release-sandbox.ts
20092
- import { execFile as execFile3 } from "child_process";
20189
+ import { execFile as execFile4 } from "child_process";
20093
20190
  import { mkdirSync as mkdirSync30, writeFileSync as writeFileSync32 } from "fs";
20094
20191
  import { dirname as dirname26 } from "path";
20095
20192
  import { promisify as promisify3 } from "util";
20096
- var execFileP3 = promisify3(execFile3);
20193
+ var execFileP3 = promisify3(execFile4);
20097
20194
  var RELEASE_CLONE_DEPTH = 50;
20098
20195
  var FORGE_TOKEN_VAR = "CREW_FORGE_TOKEN";
20099
20196
  var FORGE_USER_VAR = "CREW_FORGE_USER";
@@ -24684,7 +24781,7 @@ import {
24684
24781
  import { createConnection } from "net";
24685
24782
  import { createServer as createServer2 } from "http";
24686
24783
  import { basename as basename14, dirname as dirname33, join as join53 } from "path";
24687
- import { execFile as execFile4, spawn as spawn12 } from "child_process";
24784
+ import { execFile as execFile5, spawn as spawn12 } from "child_process";
24688
24785
 
24689
24786
  // src/periscope-control.ts
24690
24787
  import { spawn as spawn11 } from "child_process";
@@ -25225,7 +25322,8 @@ async function route(deps, method, url, req, abort) {
25225
25322
  const doc = await deps.doctor();
25226
25323
  return doc ? reply2(200, doc) : err2(502, "could not produce the doctor report");
25227
25324
  }
25228
- const known = ["/status", "/events", "/streams", "/pause", "/resume", "/release/pause", "/release/resume", "/doctor"];
25325
+ if (p === "/diagnostics" && get2 && deps.diagnostics) return reply2(200, await deps.diagnostics());
25326
+ const known = ["/status", "/events", "/streams", "/pause", "/resume", "/release/pause", "/release/resume", "/doctor", ...deps.diagnostics ? ["/diagnostics"] : []];
25229
25327
  if (known.includes(p) || p.startsWith("/streams/") || sched) return err2(405, "method not allowed");
25230
25328
  return err2(404, "not found");
25231
25329
  }
@@ -25336,7 +25434,7 @@ function schedulerHandler(control, run3 = runDetached) {
25336
25434
  }
25337
25435
  function crewJson(args, timeoutMs = 6e4) {
25338
25436
  return new Promise((resolve8) => {
25339
- execFile4(process.execPath, [process.argv[1] ?? "", ...args], { timeout: timeoutMs, maxBuffer: 16 * 1024 * 1024 }, (_e, stdout) => {
25437
+ execFile5(process.execPath, [process.argv[1] ?? "", ...args], { timeout: timeoutMs, maxBuffer: 16 * 1024 * 1024 }, (_e, stdout) => {
25340
25438
  try {
25341
25439
  const v = JSON.parse(String(stdout));
25342
25440
  resolve8(v && typeof v === "object" && !Array.isArray(v) ? v : null);
@@ -25943,7 +26041,7 @@ function usage(problem, requested = false) {
25943
26041
  crew shell-init [--shell zsh|bash|fish] print the periscope shell function (install: eval "$(crew shell-init)")
25944
26042
  crew worktree [route] NNN cut (or refresh) this run's worktree for a ticket from the remote; prints its path
25945
26043
  crew unassign [route] NNN hand back a session's ticket \u2014 clears assignee, next cycle picks it up
25946
- crew sandbox cache [--prune|--reset] [--json] list the sandbox cache volume's mirrors; --prune drops unserved repositories, --reset recreates the volume
26044
+ crew sandbox cache [--refresh|--prune|--reset] [--json] list the sandbox cache volume's mirrors; --refresh runs the daemon's cache pass once (creates missing mirrors), --prune drops unserved repositories, --reset recreates the volume
25947
26045
  crew sync [route] fast-forward the checkout and its worktrees from the remote
25948
26046
  crew pause|resume [route] [R|release] pause everything, one role, or releases only (merge/deploy/release; passengers keeps running).
25949
26047
  resume with no argument clears only the whole-crew pause; a role or release pause needs its own resume
@@ -26825,6 +26923,9 @@ ${changed2.map((c) => ` - ${c}
26825
26923
  `).join("")}` : "fix: nothing changed\n");
26826
26924
  }
26827
26925
  async function resolvedRepos(c) {
26926
+ return (await resolveRoute(c)).settled;
26927
+ }
26928
+ async function resolveRoute(c) {
26828
26929
  const { settled, errors } = await settleRepos(reposOf(c), (t) => t.name, (t) => resolveOneRepo(c, t));
26829
26930
  for (const e of errors) {
26830
26931
  try {
@@ -26834,7 +26935,7 @@ ${changed2.map((c) => ` - ${c}
26834
26935
  }
26835
26936
  const refused = new Set(errors.map((e) => e.repo));
26836
26937
  for (const t of reposOf(c)) if (!refused.has(t.name)) clearShipAttention(state, repoContractRefusedKey(t.name));
26837
- return settled;
26938
+ return { settled, errors };
26838
26939
  }
26839
26940
  async function sandboxReposOf(routes) {
26840
26941
  const out = /* @__PURE__ */ new Map();
@@ -26890,11 +26991,35 @@ ${changed2.map((c) => ` - ${c}
26890
26991
  parent: resolvePath(r.dir, ".."),
26891
26992
  prefix: r.config.worktrees.prefix
26892
26993
  }));
26893
- async function anyRepoServable(c) {
26894
- return (await resolvedRepos(c)).some((r) => satisfies(cfg.ship.platform, r.config.platform));
26994
+ async function anyRepoServable(c, tolerateUnmirrored = false) {
26995
+ const { settled, errors } = await resolveRoute(c);
26996
+ return judgeServable({
26997
+ platforms: settled.map((r) => r.config.platform),
26998
+ satisfied: (p) => satisfies(cfg.ship.platform, p),
26999
+ unreadable: errors.map((e) => e.repo),
27000
+ tolerateUnmirrored,
27001
+ unmirrored: tolerateUnmirrored && errors.length > 0 ? await unmirroredTargets(c) : /* @__PURE__ */ new Set()
27002
+ });
27003
+ }
27004
+ async function unmirroredTargets(c) {
27005
+ const settings = cfg.ship.runner === "sandbox" ? cacheSettingsOf(cfg.ship.sandbox) : null;
27006
+ if (!settings) return /* @__PURE__ */ new Set();
27007
+ try {
27008
+ const have = new Set((await new SandboxCache(settings).list()).map((m) => `${m.repo.host}/${m.repo.path}`));
27009
+ const out = /* @__PURE__ */ new Set();
27010
+ for (const t of reposOf(c)) {
27011
+ if (!lacksCheckout(cfg.ship, t.dir)) continue;
27012
+ const m = mirrorRepoOfTarget(t);
27013
+ if (m && !have.has(`${m.host}/${m.path}`)) out.add(t.name);
27014
+ }
27015
+ return out;
27016
+ } catch {
27017
+ return /* @__PURE__ */ new Set();
27018
+ }
26895
27019
  }
26896
27020
  async function explainUnservable(c) {
26897
- return (await resolvedRepos(c)).map((r) => `${r.name} requires ${r.config.platform}`).join(", ");
27021
+ const { settled, errors } = await resolveRoute(c);
27022
+ return explainRefusal(settled.map((r) => ({ name: r.name, platform: String(r.config.platform) })), errors);
26898
27023
  }
26899
27024
  async function environmentFor(c, ticket) {
26900
27025
  const tracker = new Tracker(c, cfg.ship);
@@ -28073,13 +28198,22 @@ ${cu.tail.trimEnd()}
28073
28198
  process.stderr.write("crew: daemon does not support --dry-run \u2014 it only ever performs real cycles.\n");
28074
28199
  process.exit(2);
28075
28200
  }
28076
- if (!await anyRepoServable(route2)) {
28201
+ requireArmed("run the daemon loop");
28202
+ const sandboxCachePass = cfg.ship.runner === "sandbox" ? buildSandboxCachePass(route2, cfg.ship, state, emit) : void 0;
28203
+ if (sandboxCachePass && (await unmirroredTargets(route2)).size > 0) {
28204
+ emit.emit("sandbox cache: some served repositories have no mirror yet; refreshing before reading their contracts");
28205
+ try {
28206
+ await sandboxCachePass();
28207
+ } catch (e) {
28208
+ emit.warn(`sandbox cache refresh failed: ${e instanceof Error ? e.message : String(e)}`);
28209
+ }
28210
+ }
28211
+ if (!await anyRepoServable(route2, true)) {
28077
28212
  emit.error(
28078
28213
  `refusing this route \u2014 this ship is ${cfg.ship.platform}, but ${await explainUnservable(route2)}`
28079
28214
  );
28080
28215
  process.exit(1);
28081
28216
  }
28082
- requireArmed("run the daemon loop");
28083
28217
  const watchPaths = isCompiledBinary(import.meta.url) ? [process.execPath] : [join56(CREW_HOME, "src"), join56(CREW_HOME, "dist"), join56(CREW_HOME, "bin")];
28084
28218
  const configPaths = daemonConfigPaths(cfg);
28085
28219
  watchPaths.push(...configPaths);
@@ -28141,12 +28275,19 @@ ${cu.tail.trimEnd()}
28141
28275
  periscopeMcp: controlRoutes.some((r) => r.enabled && r.hostPeriscopes) ? (req, res, ticket) => handlePeriscopeMcp(periscopeMcpDeps(), req, res, ticket) : void 0,
28142
28276
  status: () => crewJson(["status", route2.route, "--json"]),
28143
28277
  doctor: () => crewJson(["doctor", route2.route, "--json", "--offline"]),
28278
+ diagnostics: () => collectDiagnostics({
28279
+ stateDir: cfg.ship.stateDir,
28280
+ workspaceIds: [...new Set(controlRoutes.map((r) => r.resolved.workspaceId))],
28281
+ runner: cfg.ship.runner ?? "host",
28282
+ unitStems: detectSystemd() ? ["run", "release", "passengers"].map((j) => labelFor(CREW_HOME, j)) : [],
28283
+ userScope: process.getuid?.() !== 0,
28284
+ doctor: () => crewJson(["doctor", route2.route, "--json", "--offline"])
28285
+ }),
28144
28286
  scheduler: schedulerHandler(planDaemonControl(CREW_HOME, hostPlatform(), detectSystemd())),
28145
28287
  log: (m) => emit.warn(m)
28146
28288
  });
28147
28289
  if (controlServer) emit.emit(`control API listening on ${controlServer.path}`);
28148
28290
  const inFlight = /* @__PURE__ */ new Set();
28149
- const sandboxCachePass = cfg.ship.runner === "sandbox" ? buildSandboxCachePass(route2, cfg.ship, state, emit) : void 0;
28150
28291
  let sandboxBuilding = false;
28151
28292
  const stopReason = await runDaemonLoop({
28152
28293
  inFlight,
@@ -29795,6 +29936,17 @@ Signed in as ${result.identity.email} \u2014 minted an API key in workspace "${r
29795
29936
  `);
29796
29937
  break;
29797
29938
  }
29939
+ let refreshFailed = false;
29940
+ if (flag("refresh")) {
29941
+ for (const r of cfg.routes) {
29942
+ const pass = buildSandboxCachePass(r, cfg.ship, state, emit);
29943
+ for (const out of await pass?.() ?? []) {
29944
+ if (!out.ok) refreshFailed = true;
29945
+ process.stdout.write(`${out.ok ? "refreshed" : "FAILED "} ${out.repo.host}/${out.repo.path}${out.ok ? "" : ` (${out.detail})`}
29946
+ `);
29947
+ }
29948
+ }
29949
+ }
29798
29950
  const dropped = flag("prune") ? await cache.prune(served) : [];
29799
29951
  const mirrors = await cache.list();
29800
29952
  const open = openShipAttention(new State(cfg.ship.stateDir));
@@ -29817,6 +29969,7 @@ Signed in as ${result.identity.email} \u2014 minted an API key in workspace "${r
29817
29969
  for (const f of failures) process.stdout.write(`${f.repo} REFRESH FAILING (last failed ${f.lastFailedAt}): ${f.message}
29818
29970
  `);
29819
29971
  }
29972
+ if (refreshFailed) process.exitCode = 1;
29820
29973
  } catch (e) {
29821
29974
  process.stderr.write(`crew sandbox cache: ${e instanceof Error ? e.message : String(e)}
29822
29975
  `);
@@ -29829,7 +29982,7 @@ Signed in as ${result.identity.email} \u2014 minted an API key in workspace "${r
29829
29982
  "crew sandbox policy --route ROUTE --role ROLE [--repo NAME] [--json]",
29830
29983
  "crew sandbox build [REPO] [--route ROUTE] [--json]",
29831
29984
  "crew sandbox images [--route ROUTE] [--json]",
29832
- "crew sandbox cache [--prune|--reset] [--json]",
29985
+ "crew sandbox cache [--refresh|--prune|--reset] [--json]",
29833
29986
  ""
29834
29987
  ].join("\n"));
29835
29988
  process.exit(2);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tablation/crew",
3
- "version": "0.130.7",
3
+ "version": "0.131.0",
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",