kordexa 0.4.2 → 0.4.3

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,282 @@
1
+ import { hasRoleMatch, inferRoleKey } from "./research.js";
2
+
3
+ // Every setup answer goes through one of these parsers. A parser returns
4
+ // { ok: true, value, note? } or { ok: false, error }, and never throws.
5
+
6
+ export const MIN_PLAN_DAYS = 30;
7
+ export const MAX_PLAN_DAYS = 365;
8
+ export const MAX_WEEKLY_HOURS = 80;
9
+
10
+ export const ROLE_OPTIONS = [
11
+ "Agentic AI and LLM Engineer",
12
+ "Full-Stack Developer",
13
+ "Cybersecurity Analyst",
14
+ "Data Scientist"
15
+ ];
16
+
17
+ const ROLE_LABELS = {
18
+ "agentic-ai": "Agentic AI and LLM Engineer",
19
+ "full-stack": "Full-Stack Developer",
20
+ cybersecurity: "Cybersecurity Analyst",
21
+ "data-science": "Data Scientist"
22
+ };
23
+
24
+ // Each suggestion matches real topics in that role's plan.
25
+ const SKILL_SUGGESTIONS = {
26
+ "agentic-ai": ["RAG", "Prompt engineering", "Agent tools", "Evaluation"],
27
+ "full-stack": ["React", "API design", "Auth", "Testing"],
28
+ cybersecurity: ["SIEM", "Incident response", "Threat modeling", "Phishing"],
29
+ "data-science": ["pandas", "SQL", "Statistics", "Classification"]
30
+ };
31
+
32
+ export const STAGE_OPTIONS = ["beginner", "intermediate", "advanced"];
33
+ export const NOT_STARTED = "not started yet";
34
+
35
+ const UNSURE_ANSWERS = new Set([
36
+ "no", "n", "nope", "nah", "none", "nothing", "nothing yet", "na", "n/a", "nil", "null",
37
+ "not yet", "not started", "not started yet", "yet to start", "no idea", "idk", "i dont know",
38
+ "dont know", "not sure", "unsure", "skip", "-", "--", "."
39
+ ]);
40
+
41
+ const EMAIL_TYPOS = {
42
+ "gmial.com": "gmail.com",
43
+ "gamil.com": "gmail.com",
44
+ "gmai.com": "gmail.com",
45
+ "gmal.com": "gmail.com",
46
+ "gmail.co": "gmail.com",
47
+ "gmail.con": "gmail.com",
48
+ "gmail.cm": "gmail.com",
49
+ "yaho.com": "yahoo.com",
50
+ "yahoo.con": "yahoo.com",
51
+ "hotmal.com": "hotmail.com",
52
+ "hotmail.con": "hotmail.com",
53
+ "outlok.com": "outlook.com",
54
+ "outlook.con": "outlook.com"
55
+ };
56
+
57
+ const TIMEZONE_ALIASES = {
58
+ ist: "Asia/Kolkata", india: "Asia/Kolkata", "indian standard time": "Asia/Kolkata", kolkata: "Asia/Kolkata",
59
+ calcutta: "Asia/Kolkata", "asia/calcutta": "Asia/Kolkata", chennai: "Asia/Kolkata", madras: "Asia/Kolkata",
60
+ mumbai: "Asia/Kolkata", bombay: "Asia/Kolkata", delhi: "Asia/Kolkata", "new delhi": "Asia/Kolkata",
61
+ bangalore: "Asia/Kolkata", bengaluru: "Asia/Kolkata", hyderabad: "Asia/Kolkata", pune: "Asia/Kolkata",
62
+ coimbatore: "Asia/Kolkata", "utc+5:30": "Asia/Kolkata", "utc+05:30": "Asia/Kolkata", "gmt+5:30": "Asia/Kolkata",
63
+ "gmt+05:30": "Asia/Kolkata", "+5:30": "Asia/Kolkata", "+05:30": "Asia/Kolkata",
64
+ utc: "UTC", gmt: "UTC", z: "UTC", "etc/utc": "UTC",
65
+ uk: "Europe/London", bst: "Europe/London", cet: "Europe/Paris", cest: "Europe/Paris",
66
+ est: "America/New_York", edt: "America/New_York", et: "America/New_York",
67
+ cst: "America/Chicago", cdt: "America/Chicago", ct: "America/Chicago",
68
+ mst: "America/Denver", mdt: "America/Denver", mt: "America/Denver",
69
+ pst: "America/Los_Angeles", pdt: "America/Los_Angeles", pt: "America/Los_Angeles",
70
+ jst: "Asia/Tokyo", sgt: "Asia/Singapore", pkt: "Asia/Karachi", npt: "Asia/Kathmandu",
71
+ "asia/katmandu": "Asia/Kathmandu", "asia/saigon": "Asia/Ho_Chi_Minh", "asia/rangoon": "Asia/Yangon",
72
+ aest: "Australia/Sydney", aedt: "Australia/Sydney", uae: "Asia/Dubai"
73
+ };
74
+
75
+ const accept = (value, note) => ({ ok: true, value, ...(note ? { note } : {}) });
76
+ const reject = (error) => ({ ok: false, error });
77
+
78
+ // Removes arrow-key escape codes, control characters, wrapping quotes and extra spaces.
79
+ export function cleanText(value) {
80
+ const text = String(value ?? "")
81
+ .replace(/\u001b\[[0-9;?]*[ -/]*[@-~]/g, "")
82
+ .replace(/[\u0000-\u001f\u007f]/g, " ")
83
+ .replace(/\s+/g, " ")
84
+ .trim();
85
+ const quoted = /^(["'])(.*)\1$/.exec(text);
86
+ return quoted ? quoted[2].trim() : text;
87
+ }
88
+
89
+ export function isUnsureAnswer(value) {
90
+ const text = cleanText(value).toLowerCase().replace(/['’]/g, "");
91
+ return UNSURE_ANSWERS.has(text.replace(/[.!]+$/, "") || text);
92
+ }
93
+
94
+ const hasLetter = (text) => /\p{L}/u.test(text);
95
+
96
+ export function parseName(raw) {
97
+ const text = cleanText(raw);
98
+ if (!text) return reject("Please enter your name.");
99
+ if (isUnsureAnswer(text)) return reject("Please enter the name you'd like on your daily plan.");
100
+ if (!hasLetter(text)) return reject("A name needs at least one letter.");
101
+ if (text.length > 60) return reject("Please keep your name under 60 characters.");
102
+ return accept(text);
103
+ }
104
+
105
+ export function parseEmail(raw, { allowPlaceholder = true } = {}) {
106
+ const text = cleanText(raw);
107
+ if (!text) return reject("Please enter your email address, like name@gmail.com.");
108
+ if (text.length > 254 || !/^[^\s@]+@[^\s@.]+(\.[^\s@.]+)*\.[^\s@.]{2,}$/.test(text)) {
109
+ return reject("That doesn't look like an email address. Try the format name@gmail.com.");
110
+ }
111
+ const [local, domain] = text.split("@");
112
+ const suggestion = EMAIL_TYPOS[domain.toLowerCase()];
113
+ if (suggestion) return reject(`Did you mean ${local}@${suggestion}?`);
114
+ if (!allowPlaceholder && /(^|\.)example\.(com|org|net)$/i.test(domain)) {
115
+ return reject("Please enter your real email address so your daily plan can reach you.");
116
+ }
117
+ return accept(text);
118
+ }
119
+
120
+ export function parseRole(raw) {
121
+ const text = cleanText(raw);
122
+ if (!text || isUnsureAnswer(text)) {
123
+ return accept(ROLE_OPTIONS[0], `Starting with ${ROLE_OPTIONS[0]}. You can change this later.`);
124
+ }
125
+ if (/^\d+$/.test(text)) {
126
+ const choice = ROLE_OPTIONS[Number(text) - 1];
127
+ return choice ? accept(choice) : reject(`Please choose a number from 1 to ${ROLE_OPTIONS.length}, or type a job title.`);
128
+ }
129
+ if (!hasLetter(text) || text.length < 2) return reject("Please choose a number or type a job title, like Backend Developer.");
130
+ if (text.length > 80) return reject("Please keep the job title under 80 characters.");
131
+ const exact = ROLE_OPTIONS.find((role) => role.toLowerCase() === text.toLowerCase());
132
+ if (exact) return accept(exact);
133
+ const planLabel = ROLE_LABELS[inferRoleKey(text)];
134
+ if (!hasRoleMatch(text)) {
135
+ return accept(text, `There's no dedicated plan for ${text} yet, so Kordexa will use the ${planLabel} plan.`);
136
+ }
137
+ return accept(text, `${text} will use the ${planLabel} plan.`);
138
+ }
139
+
140
+ export function parseCurrentLearning(raw) {
141
+ const text = cleanText(raw);
142
+ if (!text || isUnsureAnswer(text)) return accept(NOT_STARTED);
143
+ if (!/[\p{L}\p{N}]/u.test(text)) return reject("Please type a topic, or press Enter if you haven't started.");
144
+ if (text.length > 120) return reject("Please keep this under 120 characters.");
145
+ return accept(text);
146
+ }
147
+
148
+ export function skillSuggestions(role) {
149
+ return SKILL_SUGGESTIONS[inferRoleKey(role || "")];
150
+ }
151
+
152
+ export function recommendedSkill(role) {
153
+ return skillSuggestions(role)[0];
154
+ }
155
+
156
+ export function parseSkill(raw, role) {
157
+ const text = cleanText(raw);
158
+ const suggestions = skillSuggestions(role);
159
+ if (!text || isUnsureAnswer(text)) return accept(suggestions[0], `Starting with ${suggestions[0]}, the recommended first skill for this role.`);
160
+ if (/^\d+$/.test(text)) {
161
+ const choice = suggestions[Number(text) - 1];
162
+ return choice ? accept(choice) : reject(`Please choose a number from 1 to ${suggestions.length}, or type a skill.`);
163
+ }
164
+ if (!hasLetter(text) || text.length < 2) return reject("Please choose a number or type a skill, like SQL.");
165
+ if (text.length > 80) return reject("Please keep the skill under 80 characters.");
166
+ return accept(text);
167
+ }
168
+
169
+ export function parseStage(raw) {
170
+ const text = cleanText(raw).toLowerCase();
171
+ if (!text || isUnsureAnswer(text)) return accept("beginner", "Starting at beginner level.");
172
+ if (/^\d+$/.test(text)) {
173
+ const choice = STAGE_OPTIONS[Number(text) - 1];
174
+ return choice ? accept(choice) : reject("Please choose 1, 2 or 3.");
175
+ }
176
+ if (/^(b|beg|begin\w*|fresher|new|newbie|novice|student)$/.test(text)) return accept("beginner");
177
+ if (/^(i|int|inter|intermediate|medium|mid)$/.test(text)) return accept("intermediate");
178
+ if (/^(a|adv|advance|advanced|expert|senior)$/.test(text)) return accept("advanced");
179
+ return reject("Please choose 1 for Beginner, 2 for Intermediate or 3 for Advanced.");
180
+ }
181
+
182
+ export function parseWeeklyHours(raw) {
183
+ const text = cleanText(raw).toLowerCase();
184
+ const match = /^(\d+(?:\.\d+)?)\s*(?:h|hr|hrs|hour|hours)?(?:\s*(?:a|per|\/)\s*(?:week|wk))?$/.exec(text);
185
+ if (!match) return reject("Please enter a number of hours, like 8.");
186
+ const hours = Math.round(Number(match[1]));
187
+ if (hours < 1) return reject("Please plan for at least 1 hour a week.");
188
+ if (hours > MAX_WEEKLY_HOURS) return reject(`Please enter ${MAX_WEEKLY_HOURS} hours a week or fewer.`);
189
+ return accept(hours);
190
+ }
191
+
192
+ export function parsePlanDays(raw) {
193
+ const text = cleanText(raw).toLowerCase();
194
+ const match = /^(\d+)\s*(d|day|days|w|wk|wks|week|weeks|m|mo|month|months)?$/.exec(text);
195
+ if (!match) return reject(`Please enter a number of days from ${MIN_PLAN_DAYS} to ${MAX_PLAN_DAYS}.`);
196
+ const unit = match[2] || "d";
197
+ const size = unit.startsWith("w") ? 7 : unit.startsWith("m") ? 30 : 1;
198
+ const days = Number(match[1]) * size;
199
+ if (days > MAX_PLAN_DAYS) return reject(`Plans can be up to ${MAX_PLAN_DAYS} days long.`);
200
+ if (days < MIN_PLAN_DAYS) return accept(MIN_PLAN_DAYS, `Plans start at ${MIN_PLAN_DAYS} days, so Kordexa will use ${MIN_PLAN_DAYS}.`);
201
+ return accept(days);
202
+ }
203
+
204
+ export function parseEmailTime(raw) {
205
+ const text = cleanText(raw).toLowerCase();
206
+ const invalid = reject("Please enter a time like 20:00 or 8pm.");
207
+ if (text === "noon") return accept("12:00");
208
+ if (text === "midnight") return accept("00:00");
209
+ const format = (hour, minute) => `${String(hour).padStart(2, "0")}:${String(minute).padStart(2, "0")}`;
210
+
211
+ const meridiem = /^(\d{1,2})(?:[:.](\d{2}))?\s*([ap])\.?m?\.?$/.exec(text);
212
+ if (meridiem) {
213
+ const hour = Number(meridiem[1]);
214
+ const minute = Number(meridiem[2] || 0);
215
+ if (hour < 1 || hour > 12 || minute > 59) return invalid;
216
+ return accept(format((hour % 12) + (meridiem[3] === "p" ? 12 : 0), minute));
217
+ }
218
+ const clock = /^(\d{1,2})(?:[:.](\d{2}))?$/.exec(text) || /^(\d{2})(\d{2})$/.exec(text);
219
+ if (!clock) return invalid;
220
+ const hour = Number(clock[1]);
221
+ const minute = Number(clock[2] || 0);
222
+ if (hour > 23 || minute > 59) return invalid;
223
+ return accept(format(hour, minute));
224
+ }
225
+
226
+ function canonicalTimezone(zone) {
227
+ return TIMEZONE_ALIASES[zone.toLowerCase()] || zone;
228
+ }
229
+
230
+ export function detectTimezone() {
231
+ try {
232
+ return canonicalTimezone(Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC");
233
+ } catch {
234
+ return "UTC";
235
+ }
236
+ }
237
+
238
+ export function parseTimezone(raw) {
239
+ const text = cleanText(raw);
240
+ const invalid = reject("Kordexa doesn't recognize that timezone. Try a city or code, like Chennai, London or IST.");
241
+ if (!text) return invalid;
242
+ const lowered = text.toLowerCase();
243
+ if (TIMEZONE_ALIASES[lowered]) return accept(TIMEZONE_ALIASES[lowered]);
244
+ const zones = typeof Intl.supportedValuesOf === "function" ? Intl.supportedValuesOf("timeZone") : [];
245
+ const city = zones.find((zone) => zone.split("/").at(-1).replace(/_/g, " ").toLowerCase() === lowered);
246
+ if (city) return accept(canonicalTimezone(city));
247
+ if (!text.includes("/")) return invalid;
248
+ try {
249
+ return accept(canonicalTimezone(new Intl.DateTimeFormat("en-US", { timeZone: text }).resolvedOptions().timeZone));
250
+ } catch {
251
+ return invalid;
252
+ }
253
+ }
254
+
255
+ export function parseSmtpHost(raw) {
256
+ const text = cleanText(raw).toLowerCase().replace(/^smtps?:\/\//, "").replace(/\/$/, "");
257
+ if (!/^(?=.{4,253}$)([a-z0-9]([a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}$/.test(text)) {
258
+ return reject("Please enter a mail server address, like smtp.zoho.com.");
259
+ }
260
+ return accept(text);
261
+ }
262
+
263
+ export function parseSmtpPort(raw) {
264
+ const text = cleanText(raw);
265
+ const port = Number(text);
266
+ if (!/^\d+$/.test(text) || port < 1 || port > 65535) return reject("Please enter a port number, usually 587 or 465.");
267
+ return accept(port);
268
+ }
269
+
270
+ export function parseSmtpUser(raw) {
271
+ const text = cleanText(raw);
272
+ if (!text || /\s/.test(text) || text.length > 254) return reject("Please enter your email login, usually your full email address.");
273
+ return accept(text);
274
+ }
275
+
276
+ export function parseGmailAppPassword(raw) {
277
+ const text = String(raw ?? "").replace(/\s/g, "");
278
+ if (!/^[a-zA-Z]{16}$/.test(text)) {
279
+ return reject("A Gmail app password has exactly 16 letters. Your normal Gmail password won't work here.");
280
+ }
281
+ return accept(text);
282
+ }
package/src/workflow.js CHANGED
@@ -79,6 +79,8 @@ export function workflowContent(config) {
79
79
  " SMTP_USER: ${{ secrets.SMTP_USER }}",
80
80
  " SMTP_PASS: ${{ secrets.SMTP_PASS }}",
81
81
  " SMTP_FROM: ${{ secrets.SMTP_FROM }}",
82
+ " RESEND_API_KEY: ${{ secrets.RESEND_API_KEY }}",
83
+ " RESEND_FROM: ${{ secrets.RESEND_FROM }}",
82
84
  ` run: npx --yes kordexa@${PACKAGE_VERSION} send-today`,
83
85
  ""
84
86
  ].join("\n");
@@ -128,6 +130,7 @@ function normalizeWorkflow(content) {
128
130
 
129
131
  const GENERATED_WORKFLOWS = new Set([
130
132
  workflowContent({}),
133
+ workflowContent({}).replace(/ {10}RESEND_API_KEY: .*\n {10}RESEND_FROM: .*\n/, ""),
131
134
  previousWorkflow("Kordexa", "node bin/kordexa.js send-today || node bin/eduorchestrate.js send-today"),
132
135
  previousWorkflow("EduOrchestrate", "node bin/eduorchestrate.js send-today")
133
136
  ].map(normalizeWorkflow));
@@ -0,0 +1,366 @@
1
+ import assert from "node:assert/strict";
2
+ import { spawnSync } from "node:child_process";
3
+ import fs from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import test from "node:test";
7
+ import { fileURLToPath } from "node:url";
8
+
9
+ import { generate30DayPlan } from "../../src/planner.js";
10
+ import { SetupCancelled, askEmailDelivery, collectOnboarding } from "../../src/prompts.js";
11
+ import {
12
+ ROLE_OPTIONS,
13
+ cleanText,
14
+ parseCurrentLearning,
15
+ parseEmail,
16
+ parseEmailTime,
17
+ parseGmailAppPassword,
18
+ parseName,
19
+ parsePlanDays,
20
+ parseRole,
21
+ parseSkill,
22
+ parseSmtpHost,
23
+ parseSmtpPort,
24
+ parseStage,
25
+ parseTimezone,
26
+ parseWeeklyHours,
27
+ skillSuggestions
28
+ } from "../../src/setup-answers.js";
29
+
30
+ const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
31
+ const CLI = path.join(repoRoot, "bin/kordexa.js");
32
+
33
+ function accepts(parse, cases) {
34
+ for (const [input, expected] of cases) {
35
+ const result = parse(input);
36
+ assert.equal(result.ok, true, `should accept ${JSON.stringify(input)}: ${result.error}`);
37
+ assert.equal(result.value, expected, JSON.stringify(input));
38
+ }
39
+ }
40
+
41
+ function rejects(parse, inputs) {
42
+ for (const input of inputs) {
43
+ const result = parse(input);
44
+ assert.equal(result.ok, false, `should reject ${JSON.stringify(input)}`);
45
+ assert.ok(result.error.length > 10, "gives a helpful message");
46
+ }
47
+ }
48
+
49
+ // Plays scripted answers and records everything shown to the learner.
50
+ function scriptedIO(answers) {
51
+ const queue = [...answers];
52
+ const shown = [];
53
+ const next = (label) => {
54
+ shown.push(label);
55
+ if (!queue.length) throw new SetupCancelled();
56
+ return Promise.resolve(queue.shift());
57
+ };
58
+ return { say: (text = "") => shown.push(text), ask: next, askHidden: next, shown, remaining: queue };
59
+ }
60
+
61
+ function runCli(args, { input = "", cwd, env = {} } = {}) {
62
+ return spawnSync(process.execPath, [CLI, ...args], {
63
+ cwd,
64
+ input,
65
+ encoding: "utf8",
66
+ env: { ...process.env, KORDEXA_OFFLINE: "1", ...env }
67
+ });
68
+ }
69
+
70
+ function withTempDir(fn) {
71
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "kordexa-guided-"));
72
+ try {
73
+ return fn(dir);
74
+ } finally {
75
+ fs.rmSync(dir, { recursive: true, force: true });
76
+ }
77
+ }
78
+
79
+ const GOOD_ANSWERS = ["Asha", "asha@gmail.com", "1", "", "", "1", "10", "30", "20:00", "IST", "", ""];
80
+
81
+ test("text cleaning removes arrow keys, control characters, quotes and extra spaces", () => {
82
+ assert.equal(cleanText(" Asha Rao \t"), "Asha Rao");
83
+ assert.equal(cleanText("\u001b[AAsha\u001b[D"), "Asha");
84
+ assert.equal(cleanText('"Asha"'), "Asha");
85
+ assert.equal(cleanText(undefined), "");
86
+ });
87
+
88
+ test("name accepts real names and rejects empty or meaningless answers", () => {
89
+ accepts(parseName, [["cibi", "cibi"], [" Asha Rao ", "Asha Rao"], ["சிபி", "சிபி"], ["O'Neil", "O'Neil"]]);
90
+ rejects(parseName, ["", " ", "no", "none", "N/A", "idk", "123", "!!!", "x".repeat(61)]);
91
+ });
92
+
93
+ test("email rejects bad formats, common typos and placeholders", () => {
94
+ accepts(parseEmail, [["name@gmail.com", "name@gmail.com"], ["a.b+c@mail.example.co.in", "a.b+c@mail.example.co.in"]]);
95
+ rejects(parseEmail, ["", "no", "name", "name@", "@gmail.com", "name@gmail", "a b@gmail.com", "a@@gmail.com", "name@gmail..com"]);
96
+ assert.match(parseEmail("name@gmial.com").error, /name@gmail\.com/);
97
+ assert.equal(parseEmail("you@example.com", { allowPlaceholder: false }).ok, false);
98
+ });
99
+
100
+ test("role accepts menu numbers and job titles", () => {
101
+ accepts(parseRole, [["1", ROLE_OPTIONS[0]], ["4", ROLE_OPTIONS[3]], ["data scientist", "Data Scientist"], ["ML Engineer", "ML Engineer"], ["no", ROLE_OPTIONS[0]], ["", ROLE_OPTIONS[0]]]);
102
+ rejects(parseRole, ["0", "5", "99", "!!!", "x", "y".repeat(81)]);
103
+ assert.match(parseRole("Product Designer").note, /no dedicated plan/);
104
+ assert.match(parseRole("ML Engineer").note, /Data Scientist plan/);
105
+ });
106
+
107
+ test("current learning treats no-style answers as not started", () => {
108
+ for (const input of ["", "no", "No.", "nope", "none", "nothing", "n/a", "not yet", "Not started yet", "idk", "I don't know", "-"]) {
109
+ assert.equal(parseCurrentLearning(input).value, "not started yet", input);
110
+ }
111
+ accepts(parseCurrentLearning, [["Python basics", "Python basics"]]);
112
+ rejects(parseCurrentLearning, ["???", "x".repeat(121)]);
113
+ });
114
+
115
+ test("skill recommends a choice when the learner is unsure", () => {
116
+ for (const input of ["", "no", "idk", "not sure", "skip"]) {
117
+ assert.equal(parseSkill(input, "Data Scientist").value, "pandas", input);
118
+ }
119
+ accepts((raw) => parseSkill(raw, "Cybersecurity Analyst"), [["1", "SIEM"], ["4", "Phishing"], ["log analysis", "log analysis"]]);
120
+ rejects((raw) => parseSkill(raw, "Data Scientist"), ["0", "5", "123456", "!!!"]);
121
+ });
122
+
123
+ test("every suggested skill matches real topics in its role's plan", () => {
124
+ for (const role of ROLE_OPTIONS) {
125
+ for (const focusSkill of skillSuggestions(role)) {
126
+ const plan = generate30DayPlan({ targetRole: role, focusSkill, planDays: 30 });
127
+ assert.doesNotMatch(plan.days[1].title, /^Primary skill focus/, `${role}: ${focusSkill}`);
128
+ }
129
+ }
130
+ });
131
+
132
+ test("stage accepts numbers and words and rejects anything else", () => {
133
+ accepts(parseStage, [["1", "beginner"], ["2", "intermediate"], ["3", "advanced"], ["Beginner", "beginner"], ["INTER", "intermediate"], ["expert", "advanced"], ["fresher", "beginner"], ["", "beginner"], ["no", "beginner"]]);
134
+ rejects(parseStage, ["0", "4", "banana", "-1"]);
135
+ });
136
+
137
+ test("weekly hours accepts natural answers and rejects impossible ones", () => {
138
+ accepts(parseWeeklyHours, [["10", 10], ["10 hours", 10], ["8h", 8], ["7.5", 8], ["10 hours per week", 10], ["80", 80]]);
139
+ rejects(parseWeeklyHours, ["", "abc", "0", "-5", "81", "1000", "ten", "no"]);
140
+ });
141
+
142
+ test("plan length enforces the 30-day minimum and a maximum", () => {
143
+ accepts(parsePlanDays, [["30", 30], ["45 days", 45], ["10", 30], ["1", 30], ["0", 30], ["6 weeks", 42], ["2 months", 60], ["365", 365]]);
144
+ assert.match(parsePlanDays("10").note, /start at 30 days/);
145
+ rejects(parsePlanDays, ["", "abc", "-30", "366", "99999", "4.5", "no"]);
146
+ });
147
+
148
+ test("email time understands common formats and rejects impossible times", () => {
149
+ accepts(parseEmailTime, [["20:00", "20:00"], ["8:30", "08:30"], ["8", "08:00"], ["8pm", "20:00"], ["8 PM", "20:00"], ["8:30 pm", "20:30"], ["12am", "00:00"], ["12pm", "12:00"], ["20.15", "20:15"], ["2000", "20:00"], ["noon", "12:00"], ["midnight", "00:00"]]);
150
+ rejects(parseEmailTime, ["", "abc", "24:00", "99:99", "13pm", "0pm", "8:60", "-1", "no"]);
151
+ });
152
+
153
+ test("timezone understands codes, cities and full names", () => {
154
+ accepts(parseTimezone, [["IST", "Asia/Kolkata"], ["ist", "Asia/Kolkata"], ["India", "Asia/Kolkata"], ["Chennai", "Asia/Kolkata"], ["Asia/Calcutta", "Asia/Kolkata"], ["Asia/Kolkata", "Asia/Kolkata"], ["UTC", "UTC"], ["GMT", "UTC"], ["London", "Europe/London"], ["new york", "America/New_York"], ["PST", "America/Los_Angeles"], ["UTC+5:30", "Asia/Kolkata"]]);
155
+ rejects(parseTimezone, ["", "abc", "Mars/Base", "no", "123", "XYZ"]);
156
+ });
157
+
158
+ test("mail settings reject invalid values", () => {
159
+ accepts(parseSmtpHost, [["smtp.zoho.com", "smtp.zoho.com"], ["SMTP.Gmail.com", "smtp.gmail.com"], ["smtp://smtp.zoho.com", "smtp.zoho.com"]]);
160
+ rejects(parseSmtpHost, ["", "no", "localhost", "smtp zoho com", "me@gmail.com"]);
161
+ accepts(parseSmtpPort, [["587", 587], ["465", 465]]);
162
+ rejects(parseSmtpPort, ["", "0", "70000", "abc", "-1"]);
163
+ accepts(parseGmailAppPassword, [["abcd efgh ijkl mnop", "abcdefghijklmnop"]]);
164
+ rejects(parseGmailAppPassword, ["", "short", "my-normal-password", "abcd1234abcd1234"]);
165
+ });
166
+
167
+ test("guided setup completes with simple answers and skips email by default", async () => {
168
+ const io = scriptedIO(GOOD_ANSWERS);
169
+ const answers = await collectOnboarding({ io });
170
+ assert.equal(answers.learner.name, "Asha");
171
+ assert.equal(answers.learner.targetRole, ROLE_OPTIONS[0]);
172
+ assert.equal(answers.learner.currentLearning, "not started yet");
173
+ assert.equal(answers.learner.focusSkill, "RAG");
174
+ assert.equal(answers.learner.weeklyHours, 10);
175
+ assert.equal(answers.schedule.timezone, "Asia/Kolkata");
176
+ assert.equal(answers.emailConnected, false);
177
+ assert.equal(io.remaining.length, 0);
178
+ });
179
+
180
+ test("guided setup never mentions SMTP unless the learner chooses another provider", async () => {
181
+ const io = scriptedIO(GOOD_ANSWERS);
182
+ await collectOnboarding({ io });
183
+ assert.doesNotMatch(io.shown.join("\n"), /SMTP/i);
184
+ });
185
+
186
+ test("pressing Enter on required questions asks again with a clear message", async () => {
187
+ const io = scriptedIO(["", " ", "Asha", "", "asha@gmail.com", ...GOOD_ANSWERS.slice(2)]);
188
+ const answers = await collectOnboarding({ io });
189
+ assert.equal(answers.learner.name, "Asha");
190
+ assert.equal(io.shown.filter((line) => /Please enter your name/.test(line)).length, 2);
191
+ assert.ok(io.shown.some((line) => /Please enter your email/.test(line)));
192
+ });
193
+
194
+ test("pressing Enter on every optional question uses safe defaults", async () => {
195
+ const io = scriptedIO(["Asha", "asha@gmail.com", "", "", "", "", "", "", "", "", "", ""]);
196
+ const answers = await collectOnboarding({ io });
197
+ assert.equal(answers.learner.targetRole, ROLE_OPTIONS[0]);
198
+ assert.equal(answers.learner.focusSkill, "RAG");
199
+ assert.equal(answers.learner.currentStage, "beginner");
200
+ assert.equal(answers.learner.weeklyHours, 8);
201
+ assert.equal(answers.learner.planDays, 30);
202
+ assert.equal(answers.schedule.dailyEmailTime, "08:00");
203
+ assert.ok(parseTimezone(answers.schedule.timezone).ok);
204
+ });
205
+
206
+ test("wrong answers are explained and asked again at every question", async () => {
207
+ const io = scriptedIO([
208
+ "no", "Asha",
209
+ "notanemail", "asha@gmail.com",
210
+ "9", "1",
211
+ "???", "Python",
212
+ "99", "RAG",
213
+ "banana", "2",
214
+ "abc", "12",
215
+ "9999", "45",
216
+ "25:00", "8pm",
217
+ "Mars", "Chennai",
218
+ "7", "3",
219
+ "99", ""
220
+ ]);
221
+ const answers = await collectOnboarding({ io });
222
+ assert.equal(answers.learner.currentStage, "intermediate");
223
+ assert.equal(answers.learner.planDays, 45);
224
+ assert.equal(answers.schedule.dailyEmailTime, "20:00");
225
+ assert.equal(io.shown.filter((line) => /^ {2}! /.test(line)).length, 12);
226
+ });
227
+
228
+ test("review step can change an answer before saving", async () => {
229
+ const io = scriptedIO([...GOOD_ANSWERS.slice(0, -1), "1", "Asha Rao", ""]);
230
+ assert.equal((await collectOnboarding({ io })).learner.name, "Asha Rao");
231
+ });
232
+
233
+ test("changing the role in review asks for a matching first skill", async () => {
234
+ const io = scriptedIO([...GOOD_ANSWERS.slice(0, -1), "3", "4", "", ""]);
235
+ const answers = await collectOnboarding({ io });
236
+ assert.equal(answers.learner.targetRole, "Data Scientist");
237
+ assert.equal(answers.learner.focusSkill, "pandas");
238
+ });
239
+
240
+ test("quit stops setup at any question", async () => {
241
+ await assert.rejects(collectOnboarding({ io: scriptedIO(["Asha", "quit"]) }), SetupCancelled);
242
+ });
243
+
244
+ test("Gmail setup asks only for an app password and retries a normal password", async () => {
245
+ const io = scriptedIO(["1", "my-normal-password", "abcd efgh ijkl mnop"]);
246
+ const email = await askEmailDelivery(io, { email: "asha@gmail.com" });
247
+ assert.deepEqual(email, { smtpHost: "smtp.gmail.com", smtpPort: 465, smtpUser: "asha@gmail.com", smtpPass: "abcdefghijklmnop", smtpFrom: "asha@gmail.com" });
248
+ assert.doesNotMatch(io.shown.join("\n"), /abcd efgh|my-normal-password/);
249
+ });
250
+
251
+ test("pressing Enter at any email login step skips email safely", async () => {
252
+ assert.deepEqual(await askEmailDelivery(scriptedIO(["1", ""]), { email: "asha@gmail.com" }), {});
253
+ assert.deepEqual(await askEmailDelivery(scriptedIO(["2", ""]), { email: "asha@gmail.com" }), {});
254
+ assert.deepEqual(await askEmailDelivery(scriptedIO(["2", "smtp.zoho.com", "", "", ""]), { email: "asha@zoho.com" }), {});
255
+ assert.deepEqual(await askEmailDelivery(scriptedIO([""]), { email: "asha@gmail.com" }), {});
256
+ });
257
+
258
+ test("another provider validates its settings", async () => {
259
+ const io = scriptedIO(["2", "not a server", "smtp.zoho.com", "abc", "587", "", "app-secret"]);
260
+ const email = await askEmailDelivery(io, { email: "asha@zoho.com" });
261
+ assert.deepEqual(email, { smtpHost: "smtp.zoho.com", smtpPort: 587, smtpUser: "asha@zoho.com", smtpPass: "app-secret", smtpFrom: "asha@zoho.com" });
262
+ });
263
+
264
+ test("a saved email login is kept by pressing Enter and never shown", async () => {
265
+ const io = scriptedIO([""]);
266
+ assert.deepEqual(await askEmailDelivery(io, { email: "a@gmail.com", smtpUser: "a@gmail.com", smtpPass: "saved-secret" }), {});
267
+ assert.doesNotMatch(io.shown.join("\n"), /saved-secret/);
268
+ });
269
+
270
+ test("non-interactive setup rejects every invalid option and writes nothing", () => {
271
+ withTempDir((dir) => {
272
+ const result = runCli(["--yes", "--offline", "--name", "123", "--email", "bad", "--stage", "banana", "--weekly-hours", "abc", "--days", "xyz", "--time", "99:99", "--timezone", "Mars"], { cwd: dir });
273
+ assert.equal(result.status, 1);
274
+ for (const flag of ["--name", "--email", "--stage", "--weekly-hours", "--days", "--time", "--timezone"]) {
275
+ assert.ok(result.stderr.includes(flag), flag);
276
+ }
277
+ assert.deepEqual(fs.readdirSync(dir), []);
278
+ });
279
+ });
280
+
281
+ test("unknown options and missing values are explained", () => {
282
+ withTempDir((dir) => {
283
+ assert.match(runCli(["--yes", "--emial", "a@gmail.com"], { cwd: dir }).stderr, /Unknown option "--emial"/);
284
+ assert.match(runCli(["--yes", "--email"], { cwd: dir }).stderr, /add a value after --email/);
285
+ assert.deepEqual(fs.readdirSync(dir), []);
286
+ });
287
+ });
288
+
289
+ test("a mistyped command suggests the right one instead of starting setup", () => {
290
+ withTempDir((dir) => {
291
+ const result = runCli(["stauts"], { cwd: dir });
292
+ assert.equal(result.status, 1);
293
+ assert.match(result.stderr, /Unknown command "stauts"\. Did you mean "status"\?/);
294
+ assert.deepEqual(fs.readdirSync(dir), []);
295
+ });
296
+ });
297
+
298
+ test("commands explain when setup has not run yet", () => {
299
+ withTempDir((dir) => {
300
+ const result = runCli(["status"], { cwd: dir });
301
+ assert.equal(result.status, 1);
302
+ assert.match(result.stderr, /Run npx kordexa first/);
303
+ });
304
+ });
305
+
306
+ test("guided setup works through piped answers and saves the result", () => {
307
+ withTempDir((dir) => {
308
+ const result = runCli(["--offline"], { cwd: dir, input: `${GOOD_ANSWERS.join("\n")}\n` });
309
+ assert.equal(result.status, 0, result.stderr);
310
+ assert.match(result.stdout, /You're all set, Asha\./);
311
+ assert.match(result.stdout, /npx kordexa setup-email/);
312
+ const config = JSON.parse(fs.readFileSync(path.join(dir, "kordexa.config.json"), "utf8"));
313
+ assert.equal(config.schedule.timezone, "Asia/Kolkata");
314
+ assert.match(fs.readFileSync(path.join(dir, ".github/workflows/kordexa-daily.yml"), "utf8"), /cron: "30 14 \* \* \*"/);
315
+ });
316
+ });
317
+
318
+ test("input ending early stops setup and saves nothing", () => {
319
+ withTempDir((dir) => {
320
+ const result = runCli(["--offline"], { cwd: dir, input: "Asha\n" });
321
+ assert.equal(result.status, 130);
322
+ assert.match(result.stdout, /Nothing was saved/);
323
+ assert.deepEqual(fs.readdirSync(dir), []);
324
+ });
325
+ });
326
+
327
+ test("setup protects the home folder unless the learner confirms", () => {
328
+ withTempDir((dir) => {
329
+ const env = { HOME: dir };
330
+ assert.equal(runCli(["--offline"], { cwd: dir, env, input: "\n" }).status, 130);
331
+ assert.deepEqual(fs.readdirSync(dir), []);
332
+
333
+ const scripted = runCli(["--yes", "--offline"], { cwd: dir, env });
334
+ assert.equal(scripted.status, 1);
335
+ assert.match(scripted.stderr, /home folder/);
336
+ assert.deepEqual(fs.readdirSync(dir), []);
337
+
338
+ assert.equal(runCli(["--yes", "--offline", "--allow-home"], { cwd: dir, env }).status, 0);
339
+ assert.equal(fs.existsSync(path.join(dir, "kordexa.config.json")), true);
340
+ });
341
+ });
342
+
343
+ test("daily commands reject invalid numbers with clear messages", () => {
344
+ withTempDir((dir) => {
345
+ assert.equal(runCli(["--yes", "--offline", "--role", "Data Scientist"], { cwd: dir }).status, 0);
346
+ const cases = [
347
+ [["research", "--day", "abc", "--offline"], /--day must be a whole number from 1 to 30/],
348
+ [["research", "--day", "99", "--offline"], /outside this 30-day plan/],
349
+ [["links", "--day", "0", "--offline"], /--day must be a whole number/],
350
+ [["log-progress", "--day", "1"], /what you finished/],
351
+ [["log-progress", "--day", "abc", "--completed", "x", "--evidence", "y"], /--day must be/],
352
+ [["log-progress", "--day", "1", "--completed", "x", "--evidence", "y", "--confidence", "9"], /--confidence must be/],
353
+ [["log-progress", "--day", "1", "--completed", "x", "--evidence", "y", "--minutes", "-5"], /--minutes must be/],
354
+ [["weekly-summary", "--week", "abc"], /--week must be/],
355
+ [["weekly-summary", "--week", "99"], /--week must be/],
356
+ [["plan", "--days", "abc"], /number of days/],
357
+ [["send-today", "--dry-run", "--day", "abc", "--offline"], /--day must be/]
358
+ ];
359
+ for (const [args, message] of cases) {
360
+ const result = runCli(args, { cwd: dir });
361
+ assert.equal(result.status, 1, args.join(" "));
362
+ assert.match(result.stderr, message, args.join(" "));
363
+ }
364
+ assert.equal(fs.existsSync(path.join(dir, "data/progress-log.json")), false);
365
+ });
366
+ });