@careerarchitect/cli 0.0.0-stage → 0.1.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.
@@ -0,0 +1,134 @@
1
+ import { spawn } from "node:child_process";
2
+ import { baseUrl } from "../config.js";
3
+ import { CliError, EXIT } from "../errors.js";
4
+ import { info, printJson, warn } from "../io.js";
5
+ import { pollForTokens, revokeToken, startDeviceAuthorization } from "../auth/oauth.js";
6
+ import { credentialsFilePath, deleteCredentials, loadCredentials, saveCredentials } from "../auth/store.js";
7
+ import { scopesOf } from "../auth/session.js";
8
+ import { callTool } from "../mcp.js";
9
+ import { outWhoami, readReply, replyAccount } from "../shapes.js";
10
+ function openBrowser(url) {
11
+ try {
12
+ const [cmd, args] = process.platform === "win32"
13
+ ? ["rundll32", ["url.dll,FileProtocolHandler", url]]
14
+ : process.platform === "darwin"
15
+ ? ["open", [url]]
16
+ : ["xdg-open", [url]];
17
+ const child = spawn(cmd, args, { stdio: "ignore", detached: true });
18
+ child.on("error", () => undefined);
19
+ child.unref();
20
+ return true;
21
+ }
22
+ catch {
23
+ return false;
24
+ }
25
+ }
26
+ /** Over SSH, or with no display, a browser here would open on the wrong machine (or not at all). */
27
+ function shouldOpenBrowser(ctx) {
28
+ if (ctx.flags.noBrowser)
29
+ return false;
30
+ if (process.env.SSH_CONNECTION || process.env.SSH_TTY)
31
+ return false;
32
+ if (process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY)
33
+ return false;
34
+ return true;
35
+ }
36
+ export function accessLabel(scopes) {
37
+ if (scopes.includes("spend"))
38
+ return "View, update and use credits";
39
+ if (scopes.includes("write"))
40
+ return "View and update";
41
+ return "View only";
42
+ }
43
+ /** Shown once after `ca login`, so a new user knows what to try first. Tailored to the access level chosen. */
44
+ export function welcomeLines(scopes, credits) {
45
+ const canSpend = scopes.includes("spend");
46
+ const lines = [
47
+ "",
48
+ "Welcome to CareerArchitect in your terminal. Here's where to start:",
49
+ "",
50
+ ];
51
+ if (canSpend) {
52
+ lines.push(" ca cv score ./cv.pdf Score a CV out of 5 and see what to fix first", " ca fit <job-link> Import a job and check how well your Master CV fits", " ca journey start <job> Optimise your CV for a job you've saved");
53
+ }
54
+ lines.push(" ca jobs Your saved jobs and their scores", " ca cv show Your Master CV and its appraisal", " ca lint ./cv.pdf Free offline checks, no credits", "");
55
+ if (canSpend) {
56
+ lines.push(`Commands that use credits show the price and ask before spending${credits != null ? ` (you have ${credits})` : ""}.`);
57
+ }
58
+ else {
59
+ lines.push("You chose view-only access, so scoring, importing and optimising are off.", "To turn them on, run ca login again and choose \"View, update and use credits\".");
60
+ }
61
+ lines.push("Run ca --help for every command.");
62
+ return lines;
63
+ }
64
+ export async function login(ctx) {
65
+ const server = baseUrl();
66
+ const auth = await startDeviceAuthorization(server);
67
+ const link = auth.verification_uri_complete ?? auth.verification_uri;
68
+ info(ctx, "");
69
+ info(ctx, ` Your code: ${auth.user_code}`);
70
+ info(ctx, "");
71
+ const opened = shouldOpenBrowser(ctx) && openBrowser(link);
72
+ info(ctx, opened ? `Opened ${link}` : `Open this link to sign in: ${link}`);
73
+ info(ctx, "Check the code on that page matches the one above, then choose an access level.");
74
+ info(ctx, "Waiting for you to approve…");
75
+ const creds = await pollForTokens(server, auth);
76
+ const where = await saveCredentials(creds);
77
+ if (where === "file") {
78
+ warn(`No system keychain found; your sign-in is saved in ${credentialsFilePath()} (readable only by you).`);
79
+ }
80
+ const account = readReply(replyAccount, await callTool("get_account"), "account");
81
+ const access = accessLabel(scopesOf(creds));
82
+ if (ctx.json) {
83
+ printJson(whoamiPayload(server, account, scopesOf(creds)));
84
+ }
85
+ else {
86
+ info(ctx, `Signed in${account.name ? ` as ${account.name}` : ""}. Access: ${access}.`);
87
+ for (const line of welcomeLines(scopesOf(creds), account.credits))
88
+ info(ctx, line);
89
+ }
90
+ }
91
+ export async function logout(ctx) {
92
+ const server = baseUrl();
93
+ const creds = await loadCredentials(server);
94
+ if (!creds) {
95
+ info(ctx, "You're not signed in.");
96
+ if (ctx.json)
97
+ printJson({ schema: "logout/v1", signed_out: false });
98
+ return;
99
+ }
100
+ await revokeToken(server, creds.refresh_token);
101
+ await revokeToken(server, creds.access_token);
102
+ await deleteCredentials(server);
103
+ if (ctx.json)
104
+ printJson({ schema: "logout/v1", signed_out: true });
105
+ else
106
+ info(ctx, "Signed out. This terminal's access has been revoked.");
107
+ }
108
+ function whoamiPayload(server, a, scopes) {
109
+ return outWhoami.parse({
110
+ schema: "whoami/v1",
111
+ server,
112
+ name: a.name,
113
+ plan: a.plan,
114
+ status: a.status,
115
+ credits: a.credits,
116
+ trial_days_left: a.trialDaysLeft,
117
+ access: scopes,
118
+ });
119
+ }
120
+ export async function whoami(ctx) {
121
+ const server = baseUrl();
122
+ const creds = await loadCredentials(server);
123
+ if (!creds)
124
+ throw new CliError("You're not signed in. Run ca login.", EXIT.auth);
125
+ const account = readReply(replyAccount, await callTool("get_account"), "account");
126
+ const scopes = scopesOf((await loadCredentials(server)) ?? creds);
127
+ if (ctx.json)
128
+ return printJson(whoamiPayload(server, account, scopes));
129
+ info(ctx, `${account.name ?? "Signed in"} · ${account.plan ?? "–"}${account.status === "TRIAL" && account.trialDaysLeft != null ? ` (trial, ${account.trialDaysLeft} days left)` : ""}`);
130
+ info(ctx, `Credits: ${account.credits ?? "–"}`);
131
+ info(ctx, `Access: ${accessLabel(scopes)}`);
132
+ if (server !== "https://careerarchitect.coach")
133
+ info(ctx, `Server: ${server}`);
134
+ }
@@ -0,0 +1,38 @@
1
+ import { CliError } from "../errors.js";
2
+ import { info, printJson } from "../io.js";
3
+ import { callTool } from "../mcp.js";
4
+ import { outCalendar, readReply, replyCalendar } from "../shapes.js";
5
+ const YMD = /^\d{4}-\d{2}-\d{2}$/;
6
+ export async function calendar(ctx) {
7
+ const args = {};
8
+ for (const k of ["from", "to"]) {
9
+ const v = ctx.flags[k];
10
+ if (v) {
11
+ if (!YMD.test(v))
12
+ throw new CliError(`--${k} must be a date like 2026-12-01.`);
13
+ args[k] = v;
14
+ }
15
+ }
16
+ const r = readReply(replyCalendar, await callTool("list_calendar", args), "calendar");
17
+ const payload = outCalendar.parse({
18
+ schema: "calendar/v1",
19
+ from: r.from,
20
+ to: r.to,
21
+ events: r.events.map((e) => ({
22
+ date: e.date,
23
+ kind: e.kind,
24
+ title: e.title,
25
+ when: e.when,
26
+ company: e.company ?? null,
27
+ job_id: e.job_id ?? null,
28
+ })),
29
+ });
30
+ if (ctx.json)
31
+ return printJson(payload);
32
+ info(ctx, `${r.from} to ${r.to}`);
33
+ if (!r.events.length)
34
+ return info(ctx, " Nothing on the calendar.");
35
+ for (const e of payload.events) {
36
+ info(ctx, ` ${e.date} ${e.kind.padEnd(9)} ${e.title}${e.company ? ` · ${e.company}` : ""} (${e.when})`);
37
+ }
38
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,138 @@
1
+ import { CliError } from "../errors.js";
2
+ import { baseUrl } from "../config.js";
3
+ import { confirm, formatScore, info, printJson } from "../io.js";
4
+ import { callTool } from "../mcp.js";
5
+ import { callWithQuote } from "../spend.js";
6
+ import { readCvFileBytes } from "../cv-file.js";
7
+ import { outCvList, outCvRm, outCvScore, outCvShow, readReply, replyAppraisal, replyMasterSummary, replyScoreCvFile, replyScoredList, } from "../shapes.js";
8
+ const BAND_TEXT = {
9
+ strong: "Strong. You can still run a targeted journey for a specific job.",
10
+ room_to_grow: "Room to grow. An optimisation journey for a target job would help.",
11
+ needs_work: "Needs significant work. A journey for a target job is strongly recommended.",
12
+ };
13
+ const DIM_LABELS = [
14
+ ["structure", "Structure"],
15
+ ["clarity", "Clarity"],
16
+ ["evidence", "Evidence"],
17
+ ["ats_readiness", "ATS-readiness"],
18
+ ["narrative", "Narrative"],
19
+ ];
20
+ export async function cvScore(ctx, path) {
21
+ if (!path)
22
+ throw new CliError("Usage: ca cv score <file>");
23
+ const { name, bytes } = await readCvFileBytes(path);
24
+ const reply = await callWithQuote("score_cv_file", { file_name: name, file_base64: bytes.toString("base64") }, ctx);
25
+ const r = readReply(replyScoreCvFile, reply, "score");
26
+ const f = r.scored_cv_file;
27
+ const payload = outCvScore.parse({
28
+ schema: "cv-score/v1",
29
+ id: f.id,
30
+ file_name: f.file_name,
31
+ source_format: f.source_format,
32
+ overall_score: f.overall_score,
33
+ band: f.band,
34
+ dimensions: f.dimensions,
35
+ verdict: f.verdict,
36
+ top_issues: f.top_issues,
37
+ credits_charged: r.credits_charged,
38
+ balance: r.balance,
39
+ created_at: f.created_at,
40
+ expires_at: f.expires_at,
41
+ });
42
+ if (ctx.json)
43
+ return printJson(payload);
44
+ info(ctx, "");
45
+ info(ctx, `${f.file_name}: ${formatScore(f.overall_score)}`);
46
+ info(ctx, BAND_TEXT[f.band] ?? "");
47
+ info(ctx, "");
48
+ for (const [key, label] of DIM_LABELS)
49
+ info(ctx, ` ${label.padEnd(14)} ${formatScore(f.dimensions[key])}`);
50
+ info(ctx, "");
51
+ info(ctx, f.verdict);
52
+ if (f.top_issues.length) {
53
+ info(ctx, "");
54
+ info(ctx, "Fix first:");
55
+ f.top_issues.slice(0, 3).forEach((issue, i) => info(ctx, ` ${i + 1}. ${issue}`));
56
+ }
57
+ info(ctx, "");
58
+ info(ctx, `Saved as ${f.id} (not your Master CV). ${r.credits_charged} credits used, ${r.balance} left.`);
59
+ }
60
+ export async function cvList(ctx) {
61
+ const limit = ctx.flags.limit ? Number(ctx.flags.limit) : undefined;
62
+ const r = readReply(replyScoredList, await callTool("list_scored_cv_files", limit ? { limit } : {}), "scored files");
63
+ if (ctx.json)
64
+ return printJson(outCvList.parse({ schema: "cv-list/v1", files: r.scored_cv_files }));
65
+ if (r.scored_cv_files.length === 0) {
66
+ info(ctx, "No scored files yet. Try: ca cv score ./cv.pdf");
67
+ return;
68
+ }
69
+ for (const f of r.scored_cv_files) {
70
+ info(ctx, `${f.id} ${formatScore(f.overall_score).padEnd(8)} ${f.created_at.slice(0, 10)} ${f.file_name}`);
71
+ }
72
+ }
73
+ export async function cvRm(ctx, id) {
74
+ if (!id)
75
+ throw new CliError("Usage: ca cv rm <id> (ids are listed by ca cv list)");
76
+ if (!ctx.yes) {
77
+ const ok = await confirm(`Delete scored file ${id}? This can't be undone.`, "Deleting needs confirmation. Rerun with --yes.");
78
+ if (!ok)
79
+ return info(ctx, "Kept.");
80
+ }
81
+ const reply = await callTool("delete_scored_cv_file", { id });
82
+ const r = reply;
83
+ if (r?.ok !== true)
84
+ throw new CliError(typeof r?.error === "string" ? r.error : "Could not delete it.");
85
+ if (ctx.json)
86
+ return printJson(outCvRm.parse({ schema: "cv-rm/v1", deleted: id }));
87
+ info(ctx, `Deleted ${id}.`);
88
+ }
89
+ export async function cvShow(ctx) {
90
+ const [summaryRaw, appraisalRaw] = await Promise.all([
91
+ callTool("get_master_cv_summary"),
92
+ callTool("get_cv_appraisal"),
93
+ ]);
94
+ const summary = readReply(replyMasterSummary, summaryRaw, "Master CV");
95
+ const appraisalParsed = replyAppraisal.safeParse(appraisalRaw);
96
+ const hasAppraisal = appraisalParsed.success && !(appraisalRaw && typeof appraisalRaw === "object" && "appraisal" in appraisalRaw);
97
+ const appraisal = hasAppraisal && appraisalParsed.success ? appraisalParsed.data : null;
98
+ const payload = outCvShow.parse({
99
+ schema: "cv-show/v1",
100
+ cv_id: summary.cvId,
101
+ current_role: summary.currentRole,
102
+ current_company: summary.currentCompany,
103
+ baseline: summary.cvId
104
+ ? {
105
+ overall_score: summary.baselineOverallScore,
106
+ verdict: summary.baselineVerdict,
107
+ top_issues: summary.baselineTopIssues,
108
+ }
109
+ : null,
110
+ appraisal: appraisal
111
+ ? { overall_score: appraisal.overallScore, verdict: appraisal.verdict, findings: appraisal.findings }
112
+ : null,
113
+ });
114
+ if (ctx.json)
115
+ return printJson(payload);
116
+ if (!summary.cvId) {
117
+ info(ctx, `No Master CV yet. Upload one at ${baseUrl()}/app/cv`);
118
+ return;
119
+ }
120
+ const role = [summary.currentRole, summary.currentCompany].filter(Boolean).join(" at ");
121
+ info(ctx, `Master CV${role ? `: ${role}` : ""}`);
122
+ info(ctx, `Baseline score: ${formatScore(summary.baselineOverallScore)}`);
123
+ if (summary.baselineVerdict)
124
+ info(ctx, summary.baselineVerdict);
125
+ if (appraisal) {
126
+ info(ctx, "");
127
+ info(ctx, `Appraisal: ${formatScore(appraisal.overallScore)}`);
128
+ if (appraisal.verdict)
129
+ info(ctx, appraisal.verdict);
130
+ for (const f of appraisal.findings.slice(0, 8))
131
+ info(ctx, ` • ${f.title ?? ""}${f.severity ? ` (${f.severity})` : ""}`);
132
+ }
133
+ else if (summary.baselineTopIssues.length) {
134
+ info(ctx, "");
135
+ info(ctx, "Fix first:");
136
+ summary.baselineTopIssues.slice(0, 3).forEach((issue, i) => info(ctx, ` ${i + 1}. ${issue}`));
137
+ }
138
+ }
@@ -0,0 +1,264 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { z } from "zod";
3
+ import { CliError } from "../errors.js";
4
+ import { askText, canPrompt, confirm, info, printJson } from "../io.js";
5
+ import { callTool } from "../mcp.js";
6
+ import { callWithQuote } from "../spend.js";
7
+ import { outFit, outJobImport, outJobReject, outJobs, outReport, readReply, replyImport, replyJobs, replyReject, replyReport, } from "../shapes.js";
8
+ import { LAST, resolveJobRef } from "../job-ref.js";
9
+ import { rememberJob } from "../state.js";
10
+ import { startJourneyFor } from "./journey.js";
11
+ // ——— the import's own questions (design decision 11) ———
12
+ const GateSchema = z.object({
13
+ ok: z.literal(false),
14
+ gate: z.enum(["city", "company", "agency"]),
15
+ code: z.string().optional(),
16
+ job_city: z.unknown().optional(),
17
+ city_to_add: z.unknown().optional(),
18
+ company_hint: z.unknown().optional(),
19
+ message: z.unknown().optional(),
20
+ });
21
+ const LinkedInSchema = z.object({ ok: z.literal(false), blocked_source: z.literal("linkedin") });
22
+ const asText = (v) => (typeof v === "string" && v.trim() ? v.trim() : undefined);
23
+ async function answerGate(ctx, gate) {
24
+ const message = asText(gate.message);
25
+ if (message)
26
+ info(ctx, message);
27
+ if (gate.gate === "city") {
28
+ const suggested = asText(gate.city_to_add) ?? asText(gate.job_city);
29
+ const city = await askText(suggested ? "Add this city to your job search and import?" : "Which city is this job in?", "The import needs the job's city. Rerun with --city \"<city>\".", suggested);
30
+ if (!city)
31
+ throw new CliError("Cancelled. Nothing was imported.");
32
+ return { city };
33
+ }
34
+ if (gate.gate === "company") {
35
+ const company = await askText("What's the employer's name?", "The import needs the employer's name. Rerun with --company \"<name>\".", asText(gate.company_hint));
36
+ if (!company)
37
+ throw new CliError("Cancelled. Nothing was imported.");
38
+ return { company };
39
+ }
40
+ const yes = await confirm("Is this advert from a recruitment or staffing agency (not the employer)?", "The import needs to know if this is an agency advert. Rerun with --agency yes or --agency no.");
41
+ return { agency: yes ? "yes" : "no" };
42
+ }
43
+ function presetAnswers(ctx) {
44
+ const out = {};
45
+ if (ctx.flags.city)
46
+ out.city = ctx.flags.city;
47
+ if (ctx.flags.company)
48
+ out.company = ctx.flags.company;
49
+ if (ctx.flags.agency) {
50
+ const a = ctx.flags.agency.toLowerCase();
51
+ if (a !== "yes" && a !== "no")
52
+ throw new CliError("--agency must be yes or no.");
53
+ out.agency = a;
54
+ }
55
+ return out;
56
+ }
57
+ async function importJob(ctx, tool, base) {
58
+ const args = { ...base, ...presetAnswers(ctx) };
59
+ let reply = await callWithQuote(tool, args, ctx);
60
+ // Each question is asked at most once; the quote was already agreed, so retries confirm.
61
+ for (let i = 0; i < 3; i++) {
62
+ if (LinkedInSchema.safeParse(reply).success) {
63
+ throw new CliError("CareerArchitect can't fetch LinkedIn job pages. Save the job description to a file and run: ca job import --text <file>");
64
+ }
65
+ const gate = GateSchema.safeParse(reply);
66
+ if (!gate.success)
67
+ break;
68
+ Object.assign(args, await answerGate(ctx, gate.data));
69
+ reply = await callTool(tool, { ...args, confirm: true });
70
+ }
71
+ return readReply(replyImport, reply, "import");
72
+ }
73
+ async function importFromArgs(ctx, url) {
74
+ if (ctx.flags.text) {
75
+ const text = (await readFile(ctx.flags.text, "utf8").catch(() => {
76
+ throw new CliError(`Can't read ${ctx.flags.text}.`);
77
+ })).trim();
78
+ if (text.length < 40)
79
+ throw new CliError("That file is too short to be a job description.");
80
+ return importJob(ctx, "import_job_from_text", { text });
81
+ }
82
+ if (!url)
83
+ throw new CliError("Usage: ca job import <url> or ca job import --text <file>");
84
+ if (!/^https?:\/\//i.test(url))
85
+ throw new CliError("The job link must start with http:// or https://");
86
+ return importJob(ctx, "import_job_from_url", { url });
87
+ }
88
+ export async function jobImport(ctx, url) {
89
+ const r = await importFromArgs(ctx, url);
90
+ await rememberJob({ id: r.job.id, title: r.job.title ?? null, company: r.job.company ?? null });
91
+ const payload = outJobImport.parse({
92
+ schema: "job-import/v1",
93
+ job: { id: r.job.id, title: r.job.title, company: r.job.company },
94
+ already_existed: r.alreadyExisted ?? false,
95
+ });
96
+ if (ctx.json)
97
+ return printJson(payload);
98
+ info(ctx, `${r.alreadyExisted ? "Already saved" : "Imported"}: ${r.job.company ?? "?"} — ${r.job.title ?? "?"}`);
99
+ info(ctx, `It's in your jobs on the website too. Next, check your fit: ca fit --job ${LAST}`);
100
+ }
101
+ // ——— jobs list and report ———
102
+ export async function jobs(ctx) {
103
+ const limit = ctx.flags.limit ? Number(ctx.flags.limit) : undefined;
104
+ const r = readReply(replyJobs, await callTool("list_jobs", limit ? { limit } : {}), "jobs");
105
+ const payload = outJobs.parse({
106
+ schema: "jobs/v1",
107
+ jobs: r.jobs.map((j) => ({
108
+ id: j.id,
109
+ title: j.title,
110
+ company: j.company,
111
+ location: j.location,
112
+ status: j.status,
113
+ score: j.scoreGlobal,
114
+ recommendation: j.finalRecommendation,
115
+ journey_id: j.linkedJourneyId,
116
+ created_at: j.createdAt,
117
+ })),
118
+ });
119
+ if (ctx.json)
120
+ return printJson(payload);
121
+ if (payload.jobs.length === 0)
122
+ return info(ctx, "No saved jobs yet. Try: ca fit <job-url>");
123
+ info(ctx, " # Fit Status Job");
124
+ payload.jobs.forEach((j, i) => {
125
+ const score = j.score == null ? " –" : String(j.score).padStart(3);
126
+ info(ctx, `${String(i + 1).padStart(3)} ${score} ${(j.status ?? "").padEnd(14)} ${j.company ?? "?"} — ${j.title ?? "?"}`);
127
+ });
128
+ info(ctx, "");
129
+ info(ctx, "Use the number with other commands, e.g. ca report 1 or ca journey start 1.");
130
+ }
131
+ export function reportBody(r) {
132
+ if (!r.analyzed) {
133
+ return { job_id: r.jobId, title: null, company: null, analyzed: false, scores: null, recommendation: null, summaries: null };
134
+ }
135
+ return {
136
+ job_id: r.jobId,
137
+ title: r.title,
138
+ company: r.company,
139
+ analyzed: true,
140
+ scores: {
141
+ overall: r.scores.global,
142
+ cv_match: r.scores.cvMatch,
143
+ compensation: r.scores.compensation,
144
+ culture: r.scores.culture,
145
+ north_star: r.scores.northStar,
146
+ red_flags: r.scores.redFlags,
147
+ },
148
+ recommendation: r.finalRecommendation,
149
+ summaries: {
150
+ overall: r.summaries.global,
151
+ cv_match: r.summaries.cvMatch,
152
+ compensation: r.summaries.compensation,
153
+ culture: r.summaries.culture,
154
+ north_star: r.summaries.northStar,
155
+ red_flags: r.summaries.redFlags,
156
+ },
157
+ };
158
+ }
159
+ function printReport(ctx, b, showNextStep = true) {
160
+ if (!b.analyzed || !b.scores) {
161
+ info(ctx, `No fit report yet for this job. Run one with: ca fit --job ${LAST}`);
162
+ return;
163
+ }
164
+ info(ctx, `${b.company ?? "?"} — ${b.title ?? "?"}`);
165
+ info(ctx, `Overall fit: ${b.scores.overall ?? "–"}${b.recommendation ? ` Recommendation: ${b.recommendation}` : ""}`);
166
+ info(ctx, "");
167
+ const rows = [
168
+ ["CV match", b.scores.cv_match, b.summaries?.cv_match],
169
+ ["Compensation", b.scores.compensation, b.summaries?.compensation],
170
+ ["Culture", b.scores.culture, b.summaries?.culture],
171
+ ["North star", b.scores.north_star, b.summaries?.north_star],
172
+ ["Red flags", b.scores.red_flags, b.summaries?.red_flags],
173
+ ];
174
+ for (const [label, score, summary] of rows) {
175
+ info(ctx, ` ${label.padEnd(13)} ${score ?? "–"}`);
176
+ if (summary)
177
+ info(ctx, ` ${summary.length > 300 ? `${summary.slice(0, 297)}…` : summary}`);
178
+ }
179
+ if (b.summaries?.overall) {
180
+ info(ctx, "");
181
+ info(ctx, b.summaries.overall);
182
+ }
183
+ if (showNextStep) {
184
+ info(ctx, "");
185
+ info(ctx, `Optimise your CV for it: ca journey start ${LAST}`);
186
+ }
187
+ }
188
+ export async function report(ctx, ref) {
189
+ const { id: jobId } = await resolveJobRef(ctx, ref, "Usage: ca report <job> (job numbers are listed by ca jobs)");
190
+ const body = reportBody(readReply(replyReport, await callTool("get_job_report", { job_id: jobId }), "report"));
191
+ if (ctx.json)
192
+ return printJson(outReport.parse({ schema: "report/v1", ...body }));
193
+ printReport(ctx, body);
194
+ }
195
+ /** Import a job (unless --job is given), run the fit report against the Master CV, show it. */
196
+ export async function fit(ctx, positionals, jobFlag) {
197
+ if (positionals.length > 1) {
198
+ throw new CliError("ca fit takes one job link. It always uses your Master CV; to score another file, use ca cv score <file>.");
199
+ }
200
+ let job;
201
+ let alreadyExisted = true;
202
+ if (jobFlag) {
203
+ job = await resolveJobRef(ctx, jobFlag, "Usage: ca fit --job <job>");
204
+ }
205
+ else {
206
+ const imported = await importFromArgs(ctx, positionals[0]);
207
+ job = { id: imported.job.id, title: imported.job.title ?? null, company: imported.job.company ?? null };
208
+ alreadyExisted = imported.alreadyExisted ?? false;
209
+ await rememberJob(job);
210
+ info(ctx, `${alreadyExisted ? "Already saved" : "Imported"}: ${job.company ?? "?"} — ${job.title ?? "?"}`);
211
+ }
212
+ let current = reportBody(readReply(replyReport, await callTool("get_job_report", { job_id: job.id }), "report"));
213
+ if (!current.analyzed || ctx.flags.refresh) {
214
+ const analysis = await callWithQuote("analyze_job", { job_id: job.id }, ctx);
215
+ const a = analysis;
216
+ if (a && typeof a === "object" && (a.ok === false || a.success === false)) {
217
+ throw new CliError(typeof a.error === "string" ? a.error : "The fit report failed. No credits were taken.");
218
+ }
219
+ current = reportBody(readReply(replyReport, await callTool("get_job_report", { job_id: job.id }), "report"));
220
+ }
221
+ else {
222
+ info(ctx, "Showing the existing report (add --refresh to run it again).");
223
+ }
224
+ if (ctx.json) {
225
+ return printJson(outFit.parse({
226
+ schema: "fit/v1",
227
+ job: { id: job.id, title: current.title ?? job.title, company: current.company ?? job.company },
228
+ already_existed: alreadyExisted,
229
+ report: current,
230
+ }));
231
+ }
232
+ info(ctx, "");
233
+ // In a terminal, offer the next step instead of printing a command to copy.
234
+ const offer = current.analyzed && !ctx.yes && canPrompt();
235
+ printReport(ctx, current, !offer);
236
+ if (!offer)
237
+ return;
238
+ info(ctx, "");
239
+ if (await confirm("Optimise your CV for this job now?", "")) {
240
+ info(ctx, "");
241
+ return startJourneyFor(ctx, { id: job.id, title: current.title ?? job.title, company: current.company ?? job.company });
242
+ }
243
+ info(ctx, `Later: ca journey start ${LAST}`);
244
+ }
245
+ export async function jobReject(ctx, ref) {
246
+ const { id: jobId } = await resolveJobRef(ctx, ref, "Usage: ca job reject <job> [--ended-at cv_screen|after_interview|went_quiet|withdrew] [--feedback <text>]");
247
+ const args = { job_id: jobId };
248
+ if (ctx.flags.endedAt)
249
+ args.ended_at = ctx.flags.endedAt;
250
+ if (ctx.flags.feedback)
251
+ args.feedback = ctx.flags.feedback;
252
+ const reply = await callWithQuote("mark_job_rejected", args, ctx);
253
+ if (typeof reply === "string") {
254
+ // e.g. "… is already marked as rejected."
255
+ if (ctx.json)
256
+ return printJson(outJobReject.parse({ schema: "job-reject/v1", job_id: jobId, company: null, title: null, status: "REJECTED" }));
257
+ return info(ctx, reply);
258
+ }
259
+ const r = readReply(replyReject, reply, "reject");
260
+ if (ctx.json) {
261
+ return printJson(outJobReject.parse({ schema: "job-reject/v1", job_id: r.job_id, company: r.company, title: r.title, status: r.status }));
262
+ }
263
+ info(ctx, `Marked ${r.company ?? "?"} — ${r.title ?? "?"} as rejected.`);
264
+ }