@bli-cockpit/cli 0.2.125 → 0.2.127

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.
@@ -0,0 +1,111 @@
1
+ import { stat, writeFile } from 'node:fs/promises';
2
+ import { writeLine } from './cli-io.js';
3
+ import { askAgentDoor, emitAgentDoor, failAgentDoor } from './agent-door.js';
4
+ /**
5
+ * `cockpit careers resume <id>` — the drawer's "Open resume" button, typed
6
+ * (BLI-4462).
7
+ *
8
+ * It lives beside `careers.ts` rather than inside it because it is the only
9
+ * careers verb that does not end at `emitAgentDoor`: the Tower door answers
10
+ * with a SIGNED URL that lives 60 seconds, and `--out <path>` spends it here,
11
+ * fetching the private object straight from storage and writing the bytes to
12
+ * disk. Two requests, one act.
13
+ *
14
+ * The URL is a bearer credential for that object, so it goes to stdout only
15
+ * when a person asked for it and NEVER into a log line: every `[careers
16
+ * resume]` line carries the application id, a byte count, the seconds left and
17
+ * a reason label. The overwrite refusal is checked twice, once before the
18
+ * link is fetched so the sentence is the useful one, and again by opening the
19
+ * file with `wx`, which is what actually closes the race.
20
+ */
21
+ const TAG = '[careers resume]';
22
+ const RESUME_TIMEOUT_MS = 60_000;
23
+ /** What the door promises the link is good for. Read from the answer when it says. */
24
+ const DEFAULT_EXPIRES_IN_SECONDS = 60;
25
+ export async function runCareersResume(command, door) {
26
+ const id = command.id ?? '';
27
+ const outPath = command.outPath;
28
+ if (outPath !== undefined && command.force !== true && await fileExists(outPath)) {
29
+ return failAgentDoor(door, TAG, 'file_exists', `${outPath} is already there, so nothing was downloaded. Pass --force to overwrite it, or name another path.`);
30
+ }
31
+ const answer = await askAgentDoor(door, {
32
+ path: `/api/careers/applications/${encodeURIComponent(id)}/resume-url`,
33
+ method: 'GET',
34
+ label: 'careers resume',
35
+ timeoutMs: RESUME_TIMEOUT_MS,
36
+ });
37
+ if (!answer.ok)
38
+ return failAgentDoor(door, TAG, answer.reason, answer.detail);
39
+ const url = readUrl(answer.body);
40
+ if (!url) {
41
+ return failAgentDoor(door, TAG, 'no_signed_url', 'Tower answered that door without a link, so there is nothing to open or download. That application may have no resume on file.');
42
+ }
43
+ const expiresInSeconds = readExpiry(answer.body);
44
+ if (outPath === undefined)
45
+ return emitLink(door, id, url, expiresInSeconds);
46
+ return downloadResume(door, { id, url, outPath, force: command.force === true, expiresInSeconds });
47
+ }
48
+ /** No `--out`: the link itself, on stdout, and never in the receipt line. */
49
+ function emitLink(door, id, url, expiresInSeconds) {
50
+ writeLine(door.io.stderr, `${TAG} link ${JSON.stringify({ application_id: id, expires_in_seconds: expiresInSeconds, reason: 'signed_url_issued' })}`);
51
+ if (door.json)
52
+ return emitAgentDoor(door, { url, expires_in_seconds: expiresInSeconds });
53
+ writeLine(door.io.stdout, url);
54
+ return 0;
55
+ }
56
+ async function downloadResume(door, file) {
57
+ // Straight to storage, not through Tower: this URL IS the authorisation, and
58
+ // the device token has no business on a request to another host.
59
+ let response;
60
+ try {
61
+ response = await door.io.fetch(file.url, { method: 'GET' });
62
+ }
63
+ catch (error) {
64
+ return failAgentDoor(door, TAG, 'download_failed', `Could not reach the storage that holds that resume: ${error instanceof Error ? error.message : String(error)}. Nothing was written to ${file.outPath}.`);
65
+ }
66
+ if (!response.ok) {
67
+ return failAgentDoor(door, TAG, `http_${response.status}`, `Storage answered ${response.status} for that resume; the link is only good for ${file.expiresInSeconds} seconds. Nothing was written to ${file.outPath}.`);
68
+ }
69
+ const bytes = Buffer.from(await response.arrayBuffer());
70
+ try {
71
+ // `wx` fails rather than clobbering: the check above is the good sentence,
72
+ // this is the one that holds when the file appears in between.
73
+ await writeFile(file.outPath, bytes, file.force ? {} : { flag: 'wx' });
74
+ }
75
+ catch (error) {
76
+ const reason = error?.code === 'EEXIST' ? 'file_exists' : 'write_failed';
77
+ writeLine(door.io.stderr, `${TAG} download ${JSON.stringify({ application_id: file.id, bytes: bytes.length, reason })}`);
78
+ return failAgentDoor(door, TAG, reason, `Downloaded ${bytes.length} bytes and could not write them to ${file.outPath}: ${error instanceof Error ? error.message : String(error)}`);
79
+ }
80
+ writeLine(door.io.stderr, `${TAG} download ${JSON.stringify({ application_id: file.id, bytes: bytes.length, reason: 'written' })}`);
81
+ if (door.json)
82
+ return emitAgentDoor(door, { path: file.outPath, bytes: bytes.length });
83
+ writeLine(door.io.stdout, `Wrote ${bytes.length} bytes to ${file.outPath}.`);
84
+ return 0;
85
+ }
86
+ function readUrl(body) {
87
+ if (!body || typeof body !== 'object')
88
+ return null;
89
+ const value = body['url'];
90
+ return typeof value === 'string' && value.trim() !== '' ? value : null;
91
+ }
92
+ /**
93
+ * The door answers `expires_in`; every surface a person reads says
94
+ * `expires_in_seconds`, because "60" with no unit is the kind of number that
95
+ * gets read as minutes.
96
+ */
97
+ function readExpiry(body) {
98
+ if (!body || typeof body !== 'object')
99
+ return DEFAULT_EXPIRES_IN_SECONDS;
100
+ const value = body['expires_in'];
101
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : DEFAULT_EXPIRES_IN_SECONDS;
102
+ }
103
+ async function fileExists(path) {
104
+ try {
105
+ await stat(path);
106
+ return true;
107
+ }
108
+ catch {
109
+ return false;
110
+ }
111
+ }
@@ -1,5 +1,6 @@
1
1
  import { readFile } from 'node:fs/promises';
2
2
  import { askAgentDoor, emitAgentDoor, failAgentDoor, openAgentDoor } from './agent-door.js';
3
+ import { runCareersResume } from './careers-resume.js';
3
4
  /**
4
5
  * `cockpit careers` — application review (BLI-3706) and, since BLI-4460, the
5
6
  * pipeline: invite, decide, the role's take-home and the settings. BLI-4461
@@ -9,9 +10,15 @@ import { askAgentDoor, emitAgentDoor, failAgentDoor, openAgentDoor } from './age
9
10
  * decides policy. The take-home body arrives from a FILE rather than a flag,
10
11
  * because an email body does not belong in an argument vector, a shell history
11
12
  * or a process list.
13
+ *
14
+ * `resume` (BLI-4462) is the one verb that does not end at `emitAgentDoor`,
15
+ * because its answer is a 60-second signed URL and `--out` spends it on a
16
+ * download. That work lives in `careers-resume.ts`.
12
17
  */
13
18
  export async function runCareers(command, io) {
14
19
  const door = await openAgentDoor('careers', command, io);
20
+ if (command.action === 'resume')
21
+ return runCareersResume(command, door);
15
22
  let plan;
16
23
  try {
17
24
  plan = await planCareersRequest(command);
@@ -47,6 +54,10 @@ async function planCareersRequest(command) {
47
54
  // names where the run actually happens rather than implying it ran here.
48
55
  case 'grade': return { path: `${application}/grade`, method: 'POST', body: { now: command.now === true } };
49
56
  case 'decide': return { path: `${application}/decide`, method: 'POST', body: { decision: command.decision } };
57
+ // `resume` never arrives here: `runCareers` hands it to `careers-resume.ts`
58
+ // above, which owns both of its requests. The case keeps the switch
59
+ // exhaustive, so a verb added later cannot fall through this table unseen.
60
+ case 'resume': throw new Error('careers resume is answered by runCareersResume, not by this table.');
50
61
  case 'takehome-show': return { path: takehomePath(command), method: 'GET' };
51
62
  case 'takehome-set': return { path: takehomePath(command), method: 'PUT', body: await takehomeBody(command) };
52
63
  case 'settings-show': return { path: '/api/careers/settings', method: 'GET' };
@@ -1,14 +1,14 @@
1
1
  import { optionalNonEmpty, optionalUrl, parseNamedArgs } from './local-arg-values.js';
2
- const ACTIONS = ['list', 'show', 'rescreen', 'invite', 'decide', 'grade', 'takehome-show', 'takehome-set', 'settings-show', 'settings-set'];
2
+ const ACTIONS = ['list', 'show', 'rescreen', 'invite', 'decide', 'grade', 'resume', 'takehome-show', 'takehome-set', 'settings-show', 'settings-set'];
3
3
  /** Typed word → the one action it means. The left side is what a person reads on the button. */
4
4
  const ALSO_SPELLED = { 'send-takehome': 'invite' };
5
5
  const DECISIONS = ['passed_on', 'archived', 'reopen'];
6
6
  /** Verbs that name an application id, a role slug, or nothing at all. */
7
- const NEEDS_ID = ['show', 'rescreen', 'invite', 'decide', 'grade'];
7
+ const NEEDS_ID = ['show', 'rescreen', 'invite', 'decide', 'grade', 'resume'];
8
8
  const NEEDS_ROLE = ['takehome-show', 'takehome-set'];
9
9
  export function parseCareersArgs(args) {
10
- const valueFlags = ['--role', '--min-score', '--since', '--home', '--dashboard-url', '--decision', '--stage', '--subject', '--body-file', '--link', '--pass-score', '--account', '--auto-invite-min-score', '--attention-min-score', '--enabled', '--booking-link', '--grader-model'];
11
- const values = parseNamedArgs(args, { allowedFlags: [...valueFlags, '--json', '--now'], valueFlags });
10
+ const valueFlags = ['--role', '--min-score', '--since', '--home', '--dashboard-url', '--decision', '--stage', '--subject', '--body-file', '--link', '--pass-score', '--account', '--auto-invite-min-score', '--attention-min-score', '--enabled', '--booking-link', '--grader-model', '--out'];
11
+ const values = parseNamedArgs(args, { allowedFlags: [...valueFlags, '--json', '--now', '--force'], valueFlags });
12
12
  const positionals = [...values.positionals];
13
13
  // `takehome show` and `settings set` are two words a person types and one
14
14
  // action everything downstream reads.
@@ -48,6 +48,16 @@ export function parseCareersArgs(args) {
48
48
  const enabledRaw = optionalNonEmpty(values.flags.get('--enabled'));
49
49
  if (enabledRaw !== undefined && enabledRaw !== 'true' && enabledRaw !== 'false')
50
50
  throw new Error('--enabled must be true or false.');
51
+ // The resume is the only thing this noun writes to disk, so both file flags
52
+ // belong to it alone and say so rather than being accepted and ignored.
53
+ const outPath = optionalNonEmpty(values.flags.get('--out'));
54
+ const force = values.booleans.has('--force');
55
+ if (outPath !== undefined && verb !== 'resume')
56
+ throw new Error('--out belongs to `cockpit careers resume <id>`.');
57
+ if (force && verb !== 'resume')
58
+ throw new Error('--force belongs to `cockpit careers resume <id> --out <path>`.');
59
+ if (force && outPath === undefined)
60
+ throw new Error('--force only means something beside --out <path>: with no file to write there is nothing to overwrite.');
51
61
  return {
52
62
  kind: 'careers', action: verb,
53
63
  id: NEEDS_ID.includes(verb) ? target : undefined,
@@ -60,6 +70,7 @@ export function parseCareersArgs(args) {
60
70
  bookingLink: httpsFlag(values.flags.get('--booking-link')),
61
71
  graderModel: optionalNonEmpty(values.flags.get('--grader-model')),
62
72
  now: values.booleans.has('--now'),
73
+ outPath, force,
63
74
  autoInviteMinScore, attentionMinScore,
64
75
  autoInviteEnabled: enabledRaw === undefined ? undefined : enabledRaw === 'true',
65
76
  homeDir: optionalNonEmpty(values.flags.get('--home')), dashboardUrl: optionalUrl(values.flags.get('--dashboard-url')), json: values.booleans.has('--json'),
@@ -1,37 +1,15 @@
1
1
  import { writeLine } from "./cli-io.js";
2
2
  import { resolveDiscoveryLimits, saveDiscoveryLimits, } from "../discovery-limits.js";
3
+ import { getCollectorRuntimePaths, readLocalCollectorConfig, } from "../local-state.js";
3
4
  import { discoverGitWorktreesInRootsWithStatus, } from "../repo-identity.js";
4
5
  export async function discoverCommandWorktrees(repoRoot, discovery = {}, io) {
5
6
  // What the operator typed this run, else what they typed some previous run,
6
7
  // else the built-in defaults (BLI-2362).
7
8
  const limits = await resolveDiscoveryLimits(discovery, discovery.homeDir);
8
- const maxWorktrees = limits.maxRepos;
9
- const roots = Array.isArray(repoRoot)
10
- ? repoRoot
11
- : [repoRoot ?? process.cwd()];
12
- const result = await discoverGitWorktreesInRootsWithStatus(roots, {
13
- maxDepth: limits.maxDepth,
14
- maxWorktrees,
15
- });
16
- if (io && result.unreadable_dirs.length > 0) {
17
- // Never silently dropped: anything under these folders is missing from the
18
- // scan, so say so even when the run otherwise succeeds.
19
- writeLine(io.stderr, unreadableDirectoriesMessage(result.unreadable_dirs));
20
- }
9
+ const askedForRoots = repoRoot === undefined ? undefined : Array.isArray(repoRoot) ? repoRoot : [repoRoot];
10
+ const roots = askedForRoots ?? [process.cwd()];
11
+ const result = await scanRootsReportingWhatItMissed(roots, limits, discovery, io);
21
12
  const worktrees = result.worktrees;
22
- if (!result.complete) {
23
- const message = incompleteDiscoveryMessage({
24
- result,
25
- roots,
26
- maxDepth: limits.maxDepth,
27
- maxRepos: maxWorktrees,
28
- found: worktrees.length,
29
- });
30
- if (io)
31
- writeLine(io.stderr, message);
32
- discovery.onPartial?.(message);
33
- console.error("[local-discovery] partial collection", JSON.stringify({ reason: result.incomplete_reasons.join(","), roots: roots.length, incomplete_roots: result.incomplete_roots.length, max_depth: limits.maxDepth, found: worktrees.length }));
34
- }
35
13
  if (worktrees.length === 0 && result.complete && !discovery.allowEmpty) {
36
14
  // "No git repos found" is only true when the scan could actually SEE
37
15
  // everywhere it looked. With unreadable folders in hand, the sentence sent
@@ -53,10 +31,86 @@ export async function discoverCommandWorktrees(repoRoot, discovery = {}, io) {
53
31
  "Fix the permissions on those folders and run the command again, or point --workspace at the project folders you can read.",
54
32
  ].join("\n"));
55
33
  }
34
+ // An explicit --workspace is an instruction about WHERE to look, so an
35
+ // empty answer there is the answer. Without one, the folder the operator
36
+ // stood in was a guess, and this machine already knows a better one — for
37
+ // the commands that asked for it (BLI-4467).
38
+ if (askedForRoots === undefined && discovery.fallbackToSavedRoots) {
39
+ return await discoverInSavedCollectionRoots(limits, discovery, io);
40
+ }
56
41
  throw new Error("No git repos found. Run from a git repo, or from a parent folder containing git repos.");
57
42
  }
58
43
  return worktrees;
59
44
  }
45
+ /**
46
+ * The second look: this machine's approved collection roots, scanned with the
47
+ * same limits and the same partial/unreadable reporting as the first. Refuses
48
+ * only when there are no approved roots to read, because then the machine
49
+ * genuinely has nothing to point the operator at (BLI-4467).
50
+ */
51
+ async function discoverInSavedCollectionRoots(limits, discovery, io) {
52
+ const savedRoots = await readSavedCollectionRoots(discovery.homeDir);
53
+ if (savedRoots.length === 0) {
54
+ console.error("[local-discovery] cwd holds no repos and this machine has no saved collection roots", JSON.stringify({ reason: "no_saved_roots" }));
55
+ throw new Error([
56
+ "No git repos found here and this machine has no approved collection roots.",
57
+ "Run `cockpit doctor` to set them up, or `cockpit roots add <dir>`.",
58
+ ].join("\n"));
59
+ }
60
+ console.error("[local-discovery] cwd holds no repos, using the saved collection roots", JSON.stringify({ reason: "roots_fallback", roots: savedRoots.length }));
61
+ if (io)
62
+ writeLine(io.stderr, "No git repo here; reading the machine's approved roots.");
63
+ const result = await scanRootsReportingWhatItMissed(savedRoots, limits, discovery, io);
64
+ console.error("[local-discovery] saved collection roots scanned", JSON.stringify({
65
+ reason: "roots_fallback_result",
66
+ roots: savedRoots.length,
67
+ found: result.worktrees.length,
68
+ complete: result.complete,
69
+ }));
70
+ return result.worktrees;
71
+ }
72
+ /** The approved roots this machine already agreed to collect, or none if the config cannot be read. */
73
+ async function readSavedCollectionRoots(homeDir) {
74
+ const paths = getCollectorRuntimePaths(homeDir);
75
+ const config = await readLocalCollectorConfig(paths).catch((error) => {
76
+ console.error("[local-discovery] could not read the saved collection roots", JSON.stringify({
77
+ reason: error.code ?? "config_unreadable",
78
+ }));
79
+ return null;
80
+ });
81
+ return config?.default_repo_paths ?? [];
82
+ }
83
+ /**
84
+ * One scan plus the two things a scan owes the operator: the folders it could
85
+ * not open, and the coverage it could not finish. Shared so the fallback scan
86
+ * reports exactly what the first one does.
87
+ */
88
+ async function scanRootsReportingWhatItMissed(roots, limits, discovery, io) {
89
+ const maxWorktrees = limits.maxRepos;
90
+ const result = await discoverGitWorktreesInRootsWithStatus(roots, {
91
+ maxDepth: limits.maxDepth,
92
+ maxWorktrees,
93
+ });
94
+ if (io && result.unreadable_dirs.length > 0) {
95
+ // Never silently dropped: anything under these folders is missing from the
96
+ // scan, so say so even when the run otherwise succeeds.
97
+ writeLine(io.stderr, unreadableDirectoriesMessage(result.unreadable_dirs));
98
+ }
99
+ if (!result.complete) {
100
+ const message = incompleteDiscoveryMessage({
101
+ result,
102
+ roots,
103
+ maxDepth: limits.maxDepth,
104
+ maxRepos: maxWorktrees,
105
+ found: result.worktrees.length,
106
+ });
107
+ if (io)
108
+ writeLine(io.stderr, message);
109
+ discovery.onPartial?.(message);
110
+ console.error("[local-discovery] partial collection", JSON.stringify({ reason: result.incomplete_reasons.join(","), roots: roots.length, incomplete_roots: result.incomplete_roots.length, max_depth: limits.maxDepth, found: result.worktrees.length }));
111
+ }
112
+ return result;
113
+ }
60
114
  /**
61
115
  * Persists `--max-depth` / `--max-repos` when a command carried them, so the
62
116
  * number survives into the background sync and the doctor's own sync — neither
@@ -25,13 +25,14 @@ export const TOWER_COMMAND_HELP = [
25
25
  [
26
26
  "careers",
27
27
  [
28
- "Usage: cockpit careers [list|show <id>|rescreen <id>|send-takehome <id>|decide <id> --decision <d>|grade <id>|takehome show <role>|takehome set <role>|settings show|settings set] [flags]",
28
+ "Usage: cockpit careers [list|show <id>|rescreen <id>|send-takehome <id>|decide <id> --decision <d>|grade <id>|resume <id>|takehome show <role>|takehome set <role>|settings show|settings set] [flags]",
29
29
  "",
30
30
  "Super-admin application review and pipeline. Lists at most 100 matches with total and has_more; use filters to narrow.",
31
31
  "list [--role <slug>] [--min-score <n>] [--since <date>] [--stage <screened|invited|submitted|graded|booking_sent|passed_on|archived>] — the board, newest first, with the two thresholds in force.",
32
32
  "send-takehome <id> (also `invite <id>`): sends that role's take-home from the configured mailbox, whatever the screening scored. The same act as Tower's Send take-home button, and only a row still at `screened`.",
33
33
  "decide <id> --decision <passed_on|archived|reopen> — your own call on a row; `reopen` puts it back to `screened`.",
34
34
  "grade <id> [--now]: puts one submission back in the take-home grader's queue. The grader runs on Railway every 15 minutes; --now says so rather than pretending the run happened here.",
35
+ "resume <id> [--out <path>] [--force]: the candidate's resume, the same file the drawer's Open resume button shows. Bare, it prints a signed link that dies in 60 seconds; --out downloads the file to that path and refuses to overwrite one already there unless you pass --force.",
35
36
  "takehome show <role> — the subject, body, link and the reviewer's rubric for that role.",
36
37
  "takehome set <role> [--subject <s>] [--body-file <path>] [--link <url>] [--pass-score <0-10>] — the body comes from a FILE and must keep {first_name} and {link}.",
37
38
  "settings show — the bar, the attention threshold, whether automatic sending is on, and which mailbox it goes out from.",
@@ -104,7 +104,7 @@ export function localCommandHelp(command) {
104
104
  " cockpit project [list] [--archived] [--dashboard-url <url>] [--json]",
105
105
  ` cockpit search "<words>" [--kind ${SEARCH_KINDS.join(",")}] [--limit <n>] [--dashboard-url <url>] [--json]`,
106
106
  " cockpit release [--dry-run] [--skip-checks] [--no-floor] [--tag <tag>] [--access <public|restricted>] [--otp <code>]",
107
- " cockpit careers [list|show <id>|rescreen <id>|send-takehome <id>|decide <id> --decision <passed_on|archived|reopen>|grade <id> [--now]|takehome show <role>|takehome set <role> --body-file <path>|settings show|settings set --enabled <true|false>] [--role <slug>] [--min-score <n>] [--since <date>] [--stage <s>] [--json]",
107
+ " cockpit careers [list|show <id>|rescreen <id>|send-takehome <id>|decide <id> --decision <passed_on|archived|reopen>|grade <id> [--now]|resume <id> [--out <path>]|takehome show <role>|takehome set <role> --body-file <path>|settings show|settings set --enabled <true|false>] [--role <slug>] [--min-score <n>] [--since <date>] [--stage <s>] [--force] [--json]",
108
108
  " cockpit usage sessions [--task <BLI-NNNN> | --subject <name>] [--repo <label>] [--since <window>] [--json]",
109
109
  " cockpit usage sessions --session <id> [--from-window <n>] [--json]",
110
110
  " --by-topic groups work types; --by-subject groups open subjects from session summaries.",
@@ -15,7 +15,7 @@ export async function runCockpitCli(argv, io) {
15
15
  }
16
16
 
17
17
  if (command === "--version" || command === "-V" || command === "version") {
18
- writeLine(io?.stdout ?? process.stdout, "0.2.125");
18
+ writeLine(io?.stdout ?? process.stdout, "0.2.127");
19
19
  return 0;
20
20
  }
21
21
 
@@ -19,7 +19,14 @@ const SESSION_SCAN_OVERRIDE_LIMIT = 10_000;
19
19
  export async function runSessions(command, io) {
20
20
  const now = new Date();
21
21
  const homeDir = command.homeDir ?? os.homedir();
22
- const worktrees = await discoverCommandWorktrees(command.repoRoot, { maxDepth: command.maxDepth, maxRepos: command.maxRepos, homeDir: command.homeDir }, io);
22
+ const worktrees = await discoverCommandWorktrees(command.repoRoot, {
23
+ maxDepth: command.maxDepth,
24
+ maxRepos: command.maxRepos,
25
+ homeDir: command.homeDir,
26
+ // BLI-4467: a read-only question about what this machine has observed,
27
+ // so the approved roots answer it from any folder.
28
+ fallbackToSavedRoots: true,
29
+ }, io);
23
30
  const window = await sessionsScanWindow(command, now);
24
31
  const { codex, claude } = await scanSessionSources(command, homeDir, worktrees, now, window);
25
32
  const { codexRows, claudeRows } = sessionRows(codex, claude);
@@ -30,11 +30,26 @@ import { normalizeCollectionRoots } from "../root-normalization.js";
30
30
  export async function runStatus(command, io) {
31
31
  const backfillCursor = await inspectBackfillCursor(command.homeDir);
32
32
  const setupReceipt = await readMachineSetupReceipt(command.homeDir, io);
33
- const worktrees = await discoverCommandWorktrees(command.repoRoot, { maxDepth: command.maxDepth, maxRepos: command.maxRepos, homeDir: command.homeDir }, io);
33
+ const worktrees = await discoverCommandWorktrees(command.repoRoot, {
34
+ maxDepth: command.maxDepth,
35
+ maxRepos: command.maxRepos,
36
+ homeDir: command.homeDir,
37
+ // BLI-4467: this command answers "what does this machine believe about
38
+ // itself", so standing in a folder with no repo is not a reason to
39
+ // refuse — the approved roots are the better answer.
40
+ fallbackToSavedRoots: true,
41
+ }, io);
34
42
  if (worktrees.length > 1) {
35
43
  return writeMultiRepoStatus(command, io, backfillCursor, setupReceipt, worktrees);
36
44
  }
37
- return writeSingleRepoStatus(command, io, backfillCursor, setupReceipt);
45
+ // BLI-4467: with no --workspace, the folder was a guess and discovery is the
46
+ // one that knows which worktree this is about — the fallback above may have
47
+ // found it under an approved root, nowhere near the cwd. Describing the guess
48
+ // printed `repo: <the empty folder>` and `branch: unknown` while exiting 0.
49
+ const single = command.repoRoot === undefined && worktrees.length === 1
50
+ ? { ...command, repoRoot: worktrees[0].repo_root }
51
+ : command;
52
+ return writeSingleRepoStatus(single, io, backfillCursor, setupReceipt);
38
53
  }
39
54
  async function readMachineSetupReceipt(homeDir, io) {
40
55
  // BLI-3731: "is this machine actually connected?" belongs beside "is it
@@ -40,20 +40,26 @@ export async function reportAgentImageArtifacts(options) {
40
40
  // Both non-2xx branches returned a label and said nothing (BLI-3483). An
41
41
  // image that never gets reported is never redacted and never OCR'd, and
42
42
  // the only place that fact existed was a return value the sync discards.
43
- if (response.status === 404) {
44
- console.error("[agent-artifacts] the dashboard has no agent-artifact route; these images stay unreported", JSON.stringify({
45
- reason: "agent_artifact_api_unavailable",
46
- http_status: 404,
47
- artifact_count: artifacts.length,
48
- }));
49
- return {
50
- posted: false,
51
- reason: "agent_artifact_api_unavailable",
52
- recorded_count: 0,
53
- };
54
- }
55
43
  if (!response.ok) {
56
- const serverReason = serverFailureDetail(await readResponseJson(response));
44
+ const errorBody = await readResponseJson(response);
45
+ // A 404 is two different facts. "No such route" is the platform
46
+ // answering with an empty or HTML body; a JSON error envelope means the
47
+ // route answered and refused, and calling that "the dashboard has no
48
+ // agent-artifact route" hid a real refusal behind a shrug for as long as
49
+ // the door rejected ambient tickets.
50
+ if (response.status === 404 && !routeAnswered(errorBody)) {
51
+ console.error("[agent-artifacts] nothing answered at the agent-artifact path; these images stay unreported", JSON.stringify({
52
+ reason: "agent_artifact_api_unavailable",
53
+ http_status: 404,
54
+ artifact_count: artifacts.length,
55
+ }));
56
+ return {
57
+ posted: false,
58
+ reason: "agent_artifact_api_unavailable",
59
+ recorded_count: 0,
60
+ };
61
+ }
62
+ const serverReason = serverFailureDetail(errorBody);
57
63
  console.error("[agent-artifacts] report refused", JSON.stringify({
58
64
  reason: "report_failed",
59
65
  http_status: response.status,
@@ -99,6 +105,20 @@ export async function reportAgentImageArtifacts(options) {
99
105
  return { posted: false, reason: "report_network_error", recorded_count: 0 };
100
106
  }
101
107
  }
108
+ /**
109
+ * Did the route answer, or did something in front of it?
110
+ *
111
+ * The dashboard's refusals are always a JSON envelope carrying a `code` (and
112
+ * sometimes a `reason`); a missing route answers with an empty body or a
113
+ * platform HTML page, which `readResponseJson` hands back as `{ message }`.
114
+ * That difference is the whole reason a 404 can mean two things.
115
+ */
116
+ function routeAnswered(body) {
117
+ if (!body || typeof body !== "object")
118
+ return false;
119
+ const record = body;
120
+ return (typeof record["code"] === "string" || typeof record["reason"] === "string");
121
+ }
102
122
  /**
103
123
  * The images this sync made durable, from both directions.
104
124
  *
@@ -39,11 +39,19 @@ export async function readResponseJson(response) {
39
39
  * The server's own reason for refusing, as something safe to log.
40
40
  *
41
41
  * The dashboard's error envelopes answer `{ code, message, reason? }`. A
42
- * `reason`/`code` that already looks like a label travels verbatim — that is
43
- * the bucket the server chose, and reproducing it is how "storage rejected 116
44
- * MB" reaches an operator instead of "upload failed" (BLI-2528). Anything else
45
- * falls back to the message, redacted and capped, because a proxy's error page
46
- * is unbounded and a route's message can carry a path.
42
+ * `reason`/`code` that already looks like a label is the bucket the server
43
+ * chose and travels verbatim at the head — that is how "storage rejected 116
44
+ * MB" reaches an operator instead of "upload failed" (BLI-2528).
45
+ *
46
+ * The label alone is not the whole fact. Every dashboard envelope carries a
47
+ * `code`, so a label-first helper that stopped at the first match never read
48
+ * `message` on any refusal: four fleet machines showed `ingest_rejected: http
49
+ * 500; server reason BLI-E001` while the server had sent "Collector device
50
+ * lookup failed: <cause>" in the same body. The failure knew its reason and
51
+ * the collector discarded it. So the sentence rides behind the label as
52
+ * `label: message`, redacted and capped — a proxy's error page is unbounded
53
+ * and a route's message can carry a path. A message that merely restates the
54
+ * `reason` is dropped rather than repeated.
47
55
  *
48
56
  * `null` means the body said nothing usable — which is itself worth logging as
49
57
  * `"none"`, since "the server gave no reason" and "we never looked" are
@@ -53,14 +61,26 @@ export function serverFailureDetail(value) {
53
61
  if (!value || typeof value !== "object")
54
62
  return null;
55
63
  const record = value;
64
+ let head = null;
65
+ let headIsReason = false;
56
66
  for (const key of ["reason", "code"]) {
57
67
  const candidate = record[key];
58
68
  if (typeof candidate === "string" && /^[a-z0-9_:.-]{1,80}$/iu.test(candidate)) {
59
- return candidate;
69
+ head = candidate;
70
+ headIsReason = key === "reason";
71
+ break;
60
72
  }
61
73
  }
62
74
  const message = record["message"] ?? record["error"];
63
- return typeof message === "string" ? boundedFailureDetail(message) : null;
75
+ const sentence = typeof message === "string" ? boundedFailureDetail(message) : null;
76
+ if (!head)
77
+ return sentence;
78
+ if (!sentence)
79
+ return head;
80
+ if (headIsReason && sentence.trim().toLowerCase() === head.trim().toLowerCase()) {
81
+ return head;
82
+ }
83
+ return `${head}: ${sentence}`;
64
84
  }
65
85
  /** The server's own words when it supplied any, otherwise our fallback. */
66
86
  export function responseErrorMessage(value, fallback) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bli-cockpit/cli",
3
- "version": "0.2.125",
3
+ "version": "0.2.127",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "bin": {
@@ -28,7 +28,7 @@
28
28
  },
29
29
  "dependencies": {
30
30
  "@bli-cockpit/memory-mcp": "0.1.32",
31
- "@bli-cockpit/mcp": "0.1.52",
31
+ "@bli-cockpit/mcp": "0.1.54",
32
32
  "@bli-cockpit/telemetry-core": "0.1.48"
33
33
  }
34
34
  }