@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.
package/dist/mcp.js ADDED
@@ -0,0 +1,79 @@
1
+ import { z } from "zod";
2
+ import { cliVersion } from "./config.js";
3
+ import { CliError, EXIT } from "./errors.js";
4
+ import { currentCredentials, forceRefresh } from "./auth/session.js";
5
+ /**
6
+ * JSON-RPC client for CareerArchitect's MCP server (`/api/mcp`, design decision 2).
7
+ * The CLI reads only JSON fields from tool replies, never the prose written for AI hosts.
8
+ */
9
+ const RpcResponseSchema = z.object({
10
+ jsonrpc: z.literal("2.0"),
11
+ id: z.union([z.string(), z.number(), z.null()]),
12
+ result: z
13
+ .object({
14
+ content: z.array(z.object({ type: z.string(), text: z.string().optional() })),
15
+ isError: z.boolean().optional(),
16
+ })
17
+ .optional(),
18
+ error: z.object({ code: z.number(), message: z.string() }).optional(),
19
+ });
20
+ let nextId = 1;
21
+ /** A tool replied with `isError: true`: its text is a message for the user. */
22
+ export class ToolError extends CliError {
23
+ constructor(message) {
24
+ super(message, EXIT.error, "tool_error");
25
+ }
26
+ }
27
+ /** Unwrap `result.content[0].text`: JSON when it parses, else the plain string. */
28
+ export function unwrapToolResult(result) {
29
+ const text = result.content.find((c) => c.type === "text")?.text ?? "";
30
+ if (result.isError)
31
+ throw new ToolError(text || "The tool failed.");
32
+ try {
33
+ return JSON.parse(text);
34
+ }
35
+ catch {
36
+ return text;
37
+ }
38
+ }
39
+ async function post(baseUrl, token, body) {
40
+ try {
41
+ return await fetch(`${baseUrl}/api/mcp`, {
42
+ method: "POST",
43
+ headers: {
44
+ Authorization: `Bearer ${token}`,
45
+ "Content-Type": "application/json",
46
+ Accept: "application/json",
47
+ "User-Agent": `careerarchitect-cli/${cliVersion()}`,
48
+ },
49
+ body: JSON.stringify(body),
50
+ });
51
+ }
52
+ catch (err) {
53
+ throw new CliError(`Could not reach ${baseUrl}: ${err instanceof Error ? err.message : String(err)}`);
54
+ }
55
+ }
56
+ export async function callTool(name, args = {}) {
57
+ let creds = await currentCredentials();
58
+ const body = { jsonrpc: "2.0", id: nextId++, method: "tools/call", params: { name, arguments: args } };
59
+ let res = await post(creds.base_url, creds.access_token, body);
60
+ if (res.status === 401) {
61
+ // The access token was revoked or expired early: refresh once and retry.
62
+ creds = await forceRefresh(creds);
63
+ res = await post(creds.base_url, creds.access_token, body);
64
+ }
65
+ if (res.status === 401)
66
+ throw new CliError("Your sign-in has expired. Run ca login.", EXIT.auth);
67
+ if (res.status === 413)
68
+ throw new CliError("That request is too large for the server.");
69
+ if (!res.ok)
70
+ throw new CliError(`The server returned HTTP ${res.status}. Try again in a minute.`);
71
+ const parsed = RpcResponseSchema.safeParse(await res.json().catch(() => null));
72
+ if (!parsed.success)
73
+ throw new CliError("The server sent a reply the CLI does not understand. Try updating the CLI.");
74
+ if (parsed.data.error)
75
+ throw new CliError(parsed.data.error.message);
76
+ if (!parsed.data.result)
77
+ throw new CliError("The server sent an empty reply.");
78
+ return unwrapToolResult(parsed.data.result);
79
+ }
package/dist/shapes.js ADDED
@@ -0,0 +1,374 @@
1
+ import { z } from "zod";
2
+ import { CliError } from "./errors.js";
3
+ /**
4
+ * Design decision 9: every `--json` payload has its own small, versioned shape, built by the CLI
5
+ * from the tool reply, and carries `"schema": "<command>/v1"`. A server reply reworded for AI hosts
6
+ * does not change these. The `reply*` schemas below read only the fields the CLI needs, leniently;
7
+ * the `out*` schemas are the public contract and are strict.
8
+ */
9
+ // ——— helpers for reading replies ———
10
+ /** Prisma Decimals arrive as strings ("3.5"); floats as numbers. */
11
+ const num = z
12
+ .union([z.number(), z.string(), z.null(), z.undefined()])
13
+ .transform((v) => {
14
+ if (v == null || v === "")
15
+ return null;
16
+ const n = typeof v === "number" ? v : Number(v);
17
+ return Number.isFinite(n) ? n : null;
18
+ });
19
+ const str = z.union([z.string(), z.null(), z.undefined()]).transform((v) => v ?? null);
20
+ // ——— whoami ———
21
+ export const replyAccount = z.object({
22
+ name: str,
23
+ plan: str,
24
+ status: str,
25
+ credits: num,
26
+ trialDaysLeft: num,
27
+ });
28
+ export const outWhoami = z
29
+ .object({
30
+ schema: z.literal("whoami/v1"),
31
+ server: z.string(),
32
+ name: z.string().nullable(),
33
+ plan: z.string().nullable(),
34
+ status: z.string().nullable(),
35
+ credits: z.number().nullable(),
36
+ trial_days_left: z.number().nullable(),
37
+ access: z.array(z.string()),
38
+ })
39
+ .strict();
40
+ // ——— scored CV files ———
41
+ const dims = z.object({
42
+ structure: z.number(),
43
+ clarity: z.number(),
44
+ evidence: z.number(),
45
+ ats_readiness: z.number(),
46
+ narrative: z.number(),
47
+ });
48
+ export const replyScoredFile = z.object({
49
+ id: z.string(),
50
+ file_name: z.string(),
51
+ source_format: z.string(),
52
+ overall_score: z.number(),
53
+ band: z.string(),
54
+ dimensions: dims,
55
+ verdict: z.string(),
56
+ top_issues: z.array(z.string()),
57
+ credits_charged: z.number(),
58
+ created_at: z.string(),
59
+ expires_at: z.string().nullable(),
60
+ });
61
+ export const replyScoreCvFile = z.object({
62
+ ok: z.literal(true),
63
+ scored_cv_file: replyScoredFile,
64
+ credits_charged: z.number(),
65
+ balance: z.number(),
66
+ });
67
+ export const outCvScore = z
68
+ .object({
69
+ schema: z.literal("cv-score/v1"),
70
+ id: z.string(),
71
+ file_name: z.string(),
72
+ source_format: z.string(),
73
+ overall_score: z.number(),
74
+ band: z.string(),
75
+ dimensions: dims.strict(),
76
+ verdict: z.string(),
77
+ top_issues: z.array(z.string()),
78
+ credits_charged: z.number(),
79
+ balance: z.number().nullable(),
80
+ created_at: z.string(),
81
+ expires_at: z.string().nullable(),
82
+ })
83
+ .strict();
84
+ const listItem = z.object({
85
+ id: z.string(),
86
+ file_name: z.string(),
87
+ source_format: z.string(),
88
+ overall_score: z.number(),
89
+ band: z.string(),
90
+ created_at: z.string(),
91
+ expires_at: z.string().nullable(),
92
+ });
93
+ export const replyScoredList = z.object({ ok: z.literal(true), scored_cv_files: z.array(listItem) });
94
+ export const outCvList = z.object({ schema: z.literal("cv-list/v1"), files: z.array(listItem.strict()) }).strict();
95
+ export const outCvRm = z.object({ schema: z.literal("cv-rm/v1"), deleted: z.string() }).strict();
96
+ // ——— Master CV ———
97
+ export const replyMasterSummary = z.object({
98
+ cvId: str,
99
+ currentRole: str,
100
+ currentCompany: str,
101
+ baselineOverallScore: num,
102
+ baselineVerdict: str,
103
+ baselineTopIssues: z.array(z.string()).nullish().transform((v) => v ?? []),
104
+ });
105
+ export const replyAppraisal = z.object({
106
+ overallScore: num,
107
+ verdict: str,
108
+ findings: z
109
+ .array(z.object({ severity: str, title: str }))
110
+ .nullish()
111
+ .transform((v) => v ?? []),
112
+ });
113
+ export const outCvShow = z
114
+ .object({
115
+ schema: z.literal("cv-show/v1"),
116
+ cv_id: z.string().nullable(),
117
+ current_role: z.string().nullable(),
118
+ current_company: z.string().nullable(),
119
+ baseline: z
120
+ .object({ overall_score: z.number().nullable(), verdict: z.string().nullable(), top_issues: z.array(z.string()) })
121
+ .strict()
122
+ .nullable(),
123
+ appraisal: z
124
+ .object({
125
+ overall_score: z.number().nullable(),
126
+ verdict: z.string().nullable(),
127
+ findings: z.array(z.object({ severity: z.string().nullable(), title: z.string().nullable() }).strict()),
128
+ })
129
+ .strict()
130
+ .nullable(),
131
+ })
132
+ .strict();
133
+ // ——— jobs ———
134
+ export const replyJobs = z.object({
135
+ jobs: z.array(z.object({
136
+ id: z.string(),
137
+ title: str,
138
+ company: str,
139
+ location: str,
140
+ status: str,
141
+ scoreGlobal: num,
142
+ finalRecommendation: str,
143
+ linkedJourneyId: str,
144
+ createdAt: str,
145
+ })),
146
+ });
147
+ const outJob = z
148
+ .object({
149
+ id: z.string(),
150
+ title: z.string().nullable(),
151
+ company: z.string().nullable(),
152
+ location: z.string().nullable(),
153
+ status: z.string().nullable(),
154
+ score: z.number().nullable(),
155
+ recommendation: z.string().nullable(),
156
+ journey_id: z.string().nullable(),
157
+ created_at: z.string().nullable(),
158
+ })
159
+ .strict();
160
+ export const outJobs = z.object({ schema: z.literal("jobs/v1"), jobs: z.array(outJob) }).strict();
161
+ const scoreKeys = ["global", "cvMatch", "compensation", "culture", "northStar", "redFlags"];
162
+ const scoreObj = z.object(Object.fromEntries(scoreKeys.map((k) => [k, num])));
163
+ const summaryObj = z.object(Object.fromEntries(scoreKeys.map((k) => [k, str])));
164
+ export const replyReport = z.union([
165
+ z.object({ jobId: z.string(), analyzed: z.literal(false) }),
166
+ z.object({
167
+ jobId: z.string(),
168
+ analyzed: z.literal(true),
169
+ title: str,
170
+ company: str,
171
+ scores: scoreObj,
172
+ finalRecommendation: str,
173
+ summaries: summaryObj,
174
+ }),
175
+ ]);
176
+ const outScores = z
177
+ .object({
178
+ overall: z.number().nullable(),
179
+ cv_match: z.number().nullable(),
180
+ compensation: z.number().nullable(),
181
+ culture: z.number().nullable(),
182
+ north_star: z.number().nullable(),
183
+ red_flags: z.number().nullable(),
184
+ })
185
+ .strict();
186
+ const outSummaries = z
187
+ .object({
188
+ overall: z.string().nullable(),
189
+ cv_match: z.string().nullable(),
190
+ compensation: z.string().nullable(),
191
+ culture: z.string().nullable(),
192
+ north_star: z.string().nullable(),
193
+ red_flags: z.string().nullable(),
194
+ })
195
+ .strict();
196
+ export const outReportBody = z
197
+ .object({
198
+ job_id: z.string(),
199
+ title: z.string().nullable(),
200
+ company: z.string().nullable(),
201
+ analyzed: z.boolean(),
202
+ scores: outScores.nullable(),
203
+ recommendation: z.string().nullable(),
204
+ summaries: outSummaries.nullable(),
205
+ })
206
+ .strict();
207
+ export const outReport = outReportBody.extend({ schema: z.literal("report/v1") }).strict();
208
+ export const replyImport = z.object({
209
+ success: z.literal(true),
210
+ alreadyExisted: z.boolean().nullish(),
211
+ job: z.object({ id: z.string(), title: str, company: str }),
212
+ });
213
+ const outImportedJob = z.object({ id: z.string(), title: z.string().nullable(), company: z.string().nullable() }).strict();
214
+ export const outJobImport = z
215
+ .object({ schema: z.literal("job-import/v1"), job: outImportedJob, already_existed: z.boolean() })
216
+ .strict();
217
+ export const outFit = z
218
+ .object({ schema: z.literal("fit/v1"), job: outImportedJob, already_existed: z.boolean(), report: outReportBody })
219
+ .strict();
220
+ export const replyReject = z.object({
221
+ ok: z.literal(true),
222
+ job_id: z.string(),
223
+ company: str,
224
+ title: str,
225
+ status: z.string(),
226
+ });
227
+ export const outJobReject = z
228
+ .object({
229
+ schema: z.literal("job-reject/v1"),
230
+ job_id: z.string(),
231
+ company: z.string().nullable(),
232
+ title: z.string().nullable(),
233
+ status: z.string(),
234
+ })
235
+ .strict();
236
+ // ——— journeys ———
237
+ export const replyJourneyStatus = z.object({
238
+ jobId: z.string(),
239
+ journeyId: str,
240
+ status: str,
241
+ initialScore: num,
242
+ finalScore: num,
243
+ stages: z
244
+ .array(z.object({ stageType: z.string(), stageOrder: z.number(), status: z.string(), scoreBefore: num, scoreAfter: num }))
245
+ .nullish()
246
+ .transform((v) => v ?? []),
247
+ unfixableGaps: z
248
+ .array(z.object({ gapDescription: z.string(), mitigation: str }))
249
+ .nullish()
250
+ .transform((v) => v ?? []),
251
+ });
252
+ export const outJourneyStatusBody = z
253
+ .object({
254
+ job_id: z.string(),
255
+ journey_id: z.string().nullable(),
256
+ status: z.string().nullable(),
257
+ initial_score: z.number().nullable(),
258
+ final_score: z.number().nullable(),
259
+ stages: z.array(z
260
+ .object({
261
+ stage: z.string(),
262
+ order: z.number(),
263
+ status: z.string(),
264
+ score_before: z.number().nullable(),
265
+ score_after: z.number().nullable(),
266
+ })
267
+ .strict()),
268
+ unfixable_gaps: z.array(z.object({ description: z.string(), mitigation: z.string().nullable() }).strict()),
269
+ })
270
+ .strict();
271
+ export const outJourneyStatus = outJourneyStatusBody.extend({ schema: z.literal("journey-status/v1") }).strict();
272
+ export const replyOptimiseOptions = z.object({
273
+ ok: z.literal(true),
274
+ needs_stage_choice: z.literal(true),
275
+ suggested_stages: z.array(z.string()),
276
+ stages: z.array(z.object({
277
+ key: z.string(),
278
+ label: z.string(),
279
+ unlocked: z.boolean(),
280
+ recommended: z.boolean(),
281
+ reason: str,
282
+ })),
283
+ });
284
+ export const replyStageRun = z.object({
285
+ ok: z.boolean().optional(),
286
+ error: z.string().optional(),
287
+ journeyId: z.string().optional(),
288
+ stageType: z.string().optional(),
289
+ done: z.boolean().optional(),
290
+ alreadyStarted: z.boolean().optional(),
291
+ });
292
+ export const outJourneyRun = z
293
+ .object({
294
+ schema: z.literal("journey-run/v1"),
295
+ job_id: z.string(),
296
+ stage_run: z.string().nullable(),
297
+ done: z.boolean(),
298
+ journey: outJourneyStatusBody,
299
+ })
300
+ .strict();
301
+ // ——— calendar ———
302
+ export const replyCalendar = z.object({
303
+ from: z.string(),
304
+ to: z.string(),
305
+ events: z.array(z.object({
306
+ date: z.string(),
307
+ kind: z.string(),
308
+ title: z.string(),
309
+ when: z.string(),
310
+ company: z.string().optional(),
311
+ job_id: z.string().optional(),
312
+ })),
313
+ });
314
+ export const outCalendar = z
315
+ .object({
316
+ schema: z.literal("calendar/v1"),
317
+ from: z.string(),
318
+ to: z.string(),
319
+ events: z.array(z
320
+ .object({
321
+ date: z.string(),
322
+ kind: z.string(),
323
+ title: z.string(),
324
+ when: z.string(),
325
+ company: z.string().nullable(),
326
+ job_id: z.string().nullable(),
327
+ })
328
+ .strict()),
329
+ })
330
+ .strict();
331
+ // ——— lint (offline) ———
332
+ export const outLint = z
333
+ .object({
334
+ schema: z.literal("lint/v1"),
335
+ file: z.string(),
336
+ passed: z.boolean(),
337
+ stats: z
338
+ .object({
339
+ words: z.number(),
340
+ bullets: z.number(),
341
+ bullets_with_numbers: z.number(),
342
+ roles_with_dates: z.number(),
343
+ })
344
+ .strict(),
345
+ checks: z.array(z
346
+ .object({
347
+ id: z.string(),
348
+ status: z.enum(["pass", "warn", "fail"]),
349
+ message: z.string(),
350
+ details: z.array(z.string()),
351
+ })
352
+ .strict()),
353
+ })
354
+ .strict();
355
+ /** Read a tool reply with `schema`, or explain that the server changed in a way this version misses. */
356
+ export function readReply(schema, reply, what) {
357
+ const parsed = schema.safeParse(reply);
358
+ if (parsed.success)
359
+ return parsed.data;
360
+ const message = reply && typeof reply === "object" && "error" in reply && typeof reply.error === "string"
361
+ ? reply.error
362
+ : reply && typeof reply === "object" && "message" in reply && typeof reply.message === "string"
363
+ ? reply.message
364
+ : typeof reply === "string"
365
+ ? reply
366
+ : `The server's ${what} reply was not in the expected shape. Try updating the CLI (npm i -g @careerarchitect/cli).`;
367
+ throw new ReplyShapeError(message);
368
+ }
369
+ export class ReplyShapeError extends CliError {
370
+ constructor(message) {
371
+ super(message);
372
+ this.name = "ReplyShapeError";
373
+ }
374
+ }
package/dist/spend.js ADDED
@@ -0,0 +1,55 @@
1
+ import { z } from "zod";
2
+ import { callTool } from "./mcp.js";
3
+ import { CliError, EXIT } from "./errors.js";
4
+ import { confirm, info } from "./io.js";
5
+ import { baseUrl } from "./config.js";
6
+ const creditsUrl = () => `${baseUrl()}/app/account?tab=credits`;
7
+ /**
8
+ * Every credit action shows the server's own spend quote and waits for `y` (design summary).
9
+ * The first call quotes; the second, with `confirm: true`, spends.
10
+ */
11
+ export const SpendQuoteSchema = z.object({
12
+ needs_confirmation: z.literal(true),
13
+ action: z.string(),
14
+ credits: z.number(),
15
+ balance: z.number().optional(),
16
+ summary: z.string(),
17
+ what_happens: z.string().optional(),
18
+ });
19
+ export function asQuote(reply) {
20
+ const parsed = SpendQuoteSchema.safeParse(reply);
21
+ return parsed.success ? parsed.data : null;
22
+ }
23
+ export function describeQuote(q) {
24
+ const lines = [q.summary];
25
+ if (q.credits > 0) {
26
+ const balance = q.balance != null ? ` (you have ${q.balance})` : "";
27
+ lines.push(`Cost: ${q.credits} credits${balance}.`);
28
+ }
29
+ if (q.what_happens)
30
+ lines.push(q.what_happens);
31
+ return lines;
32
+ }
33
+ /**
34
+ * Call `tool`; if it replies with a quote, show it, ask (or accept --yes), then call again with
35
+ * `confirm: true`. Returns the final reply. Declining exits with a CliError.
36
+ */
37
+ export async function callWithQuote(tool, args, opts) {
38
+ const first = await callTool(tool, args);
39
+ const quote = asQuote(first);
40
+ if (!quote)
41
+ return first;
42
+ if (quote.balance != null && quote.credits > quote.balance) {
43
+ throw new CliError(`This needs ${quote.credits} credits and you have ${quote.balance}. Top up at ${creditsUrl()}.`);
44
+ }
45
+ for (const line of describeQuote(quote))
46
+ info(opts, line);
47
+ if (!opts.yes) {
48
+ const ok = await confirm(quote.credits > 0 ? `Spend ${quote.credits} credits?` : "Go ahead?", quote.credits > 0
49
+ ? `This spends ${quote.credits} credits. Rerun with --yes to agree without a prompt.`
50
+ : "This needs your confirmation. Rerun with --yes to agree without a prompt.");
51
+ if (!ok)
52
+ throw new CliError("Cancelled. Nothing was charged.", EXIT.ok, "cancelled");
53
+ }
54
+ return callTool(tool, { ...args, confirm: true });
55
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Turn what someone typed at "Which stages?" into stage keys. Forgiving on purpose: numbers from the
3
+ * list ("1,5" or "1 5"), names in any case ("gap analysis", "Human Touch"), the keys themselves
4
+ * ("gap_analysis"), the start of a name ("ats"), and small typos ("gap analyis"). Separate several
5
+ * names with commas. Pure, so it is unit-tested in test/stage-pick.test.ts.
6
+ */
7
+ export function normaliseStageText(s) {
8
+ return s
9
+ .toLowerCase()
10
+ .replace(/[_-]+/g, " ")
11
+ .replace(/[^a-z0-9 ]+/g, "")
12
+ .replace(/\s+/g, " ")
13
+ .trim();
14
+ }
15
+ export function editDistance(a, b) {
16
+ const prev = Array.from({ length: b.length + 1 }, (_, j) => j);
17
+ for (let i = 1; i <= a.length; i++) {
18
+ let diag = prev[0];
19
+ prev[0] = i;
20
+ for (let j = 1; j <= b.length; j++) {
21
+ const up = prev[j];
22
+ prev[j] = Math.min(up + 1, prev[j - 1] + 1, diag + (a[i - 1] === b[j - 1] ? 0 : 1));
23
+ diag = up;
24
+ }
25
+ }
26
+ return prev[b.length];
27
+ }
28
+ /** One stage for one piece of text, or null when nothing (or more than one stage) fits. */
29
+ export function matchStage(text, stages) {
30
+ const t = normaliseStageText(text);
31
+ if (!t)
32
+ return null;
33
+ const names = (s) => [normaliseStageText(s.key), normaliseStageText(s.label)];
34
+ const unique = (found) => {
35
+ const distinct = [...new Set(found)];
36
+ return distinct.length === 1 ? distinct[0] : null;
37
+ };
38
+ const exact = stages.filter((s) => names(s).includes(t));
39
+ if (exact.length)
40
+ return unique(exact);
41
+ if (t.length >= 3) {
42
+ const prefix = stages.filter((s) => names(s).some((n) => n.startsWith(t)));
43
+ if (prefix.length)
44
+ return unique(prefix);
45
+ }
46
+ let best = Infinity;
47
+ let found = [];
48
+ for (const s of stages) {
49
+ for (const n of names(s)) {
50
+ const d = editDistance(t, n);
51
+ if (d > Math.max(1, Math.floor(n.length / 6)))
52
+ continue;
53
+ if (d < best) {
54
+ best = d;
55
+ found = [s];
56
+ }
57
+ else if (d === best)
58
+ found.push(s);
59
+ }
60
+ }
61
+ return unique(found);
62
+ }
63
+ export function pickStages(answer, stages, ticked) {
64
+ const trimmed = answer.trim();
65
+ if (!trimmed) {
66
+ return ticked.length ? { ok: true, keys: ticked } : { ok: false, problems: ["Choose at least one stage."] };
67
+ }
68
+ const picked = [];
69
+ const problems = [];
70
+ for (const part of trimmed.split(/[,;]+/).map((p) => p.trim()).filter(Boolean)) {
71
+ if (/^#?\d+(\s+#?\d+)*$/.test(part)) {
72
+ for (const n of part.split(/\s+/).map((x) => Number(x.replace(/^#/, "")))) {
73
+ const s = stages[n - 1];
74
+ if (s)
75
+ picked.push(s);
76
+ else
77
+ problems.push(`There's no stage ${n}. Use 1 to ${stages.length}.`);
78
+ }
79
+ continue;
80
+ }
81
+ const s = matchStage(part, stages);
82
+ if (s)
83
+ picked.push(s);
84
+ else
85
+ problems.push(`"${part}" doesn't match a stage. Use its number or name, and separate several with commas.`);
86
+ }
87
+ for (const s of picked) {
88
+ if (!s.unlocked)
89
+ problems.push(`${s.label} isn't on your plan.`);
90
+ }
91
+ if (problems.length)
92
+ return { ok: false, problems: [...new Set(problems)] };
93
+ // Keep the list's order and drop repeats.
94
+ const keys = stages.filter((s) => picked.includes(s)).map((s) => s.key);
95
+ return keys.length ? { ok: true, keys } : { ok: false, problems: ["Choose at least one stage."] };
96
+ }
package/dist/state.js ADDED
@@ -0,0 +1,55 @@
1
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
2
+ import { dirname, join } from "node:path";
3
+ import { z } from "zod";
4
+ import { credentialsFilePath } from "./auth/store.js";
5
+ import { baseUrl } from "./config.js";
6
+ /**
7
+ * Small local memory next to the credentials file, kept per server like the credentials. Never
8
+ * holds secrets.
9
+ * - `last_job`: the last job you worked with, so commands can take `last` instead of a job id.
10
+ * - `journey_stages`: the stages you chose for each job's journey. The server does not keep that
11
+ * choice; `run_next_stage` needs it sent again on every run, or it runs the next stage in its own
12
+ * order instead.
13
+ */
14
+ const LastJob = z.object({ id: z.string(), title: z.string().nullable(), company: z.string().nullable() });
15
+ const ServerState = z.object({
16
+ last_job: LastJob.optional(),
17
+ journey_stages: z.record(z.string(), z.array(z.string())).optional(),
18
+ });
19
+ const StateFile = z.record(z.string(), ServerState);
20
+ function statePath() {
21
+ return join(dirname(credentialsFilePath()), "state.json");
22
+ }
23
+ async function readState() {
24
+ try {
25
+ const parsed = StateFile.safeParse(JSON.parse(await readFile(statePath(), "utf8")));
26
+ return parsed.success ? parsed.data : {};
27
+ }
28
+ catch {
29
+ return {};
30
+ }
31
+ }
32
+ /** Best effort: a read-only config folder must never make a command fail. */
33
+ async function updateServerState(change) {
34
+ try {
35
+ const state = await readState();
36
+ state[baseUrl()] = change(state[baseUrl()] ?? {});
37
+ await mkdir(dirname(statePath()), { recursive: true, mode: 0o700 });
38
+ await writeFile(statePath(), JSON.stringify(state, null, 2) + "\n", { mode: 0o600 });
39
+ }
40
+ catch {
41
+ // ignore
42
+ }
43
+ }
44
+ export async function loadLastJob() {
45
+ return (await readState())[baseUrl()]?.last_job ?? null;
46
+ }
47
+ export async function rememberJob(job) {
48
+ await updateServerState((s) => ({ ...s, last_job: job }));
49
+ }
50
+ export async function loadJourneyStages(jobId) {
51
+ return (await readState())[baseUrl()]?.journey_stages?.[jobId] ?? null;
52
+ }
53
+ export async function rememberJourneyStages(jobId, stages) {
54
+ await updateServerState((s) => ({ ...s, journey_stages: { ...s.journey_stages, [jobId]: stages } }));
55
+ }