recess-cli 3.10.0 → 3.12.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,647 @@
1
+ import { unwrap } from "./api.js";
2
+ import { CliError } from "./errors.js";
3
+ // ---------------------------------------------------------------------------
4
+ // Scaffold
5
+ // ---------------------------------------------------------------------------
6
+ /** Marks scaffold prose so the local validator can say which files are still unwritten. */
7
+ export const SCAFFOLD_MARKER = "<!-- recess-scaffold: rewrite this file -->";
8
+ const SCAFFOLD_MODULE_PREFIX = "W1-M";
9
+ function humanize(slug) {
10
+ const words = slug.replace(/[-_]+/g, " ").trim();
11
+ return words ? words[0].toUpperCase() + words.slice(1) : "Learning path";
12
+ }
13
+ /**
14
+ * A module-backed workspace tree that passes the server's
15
+ * `validateGoalBuilderWorkspaceFiles`: the files the runtime reads (`AGENTS.md`,
16
+ * `first-message.md`, `state/progress.json`) and complete module files
17
+ * (summary, estimated time, the five required `##` sections). Every prose file
18
+ * carries `SCAFFOLD_MARKER` so a push reports what is still generic.
19
+ */
20
+ export function buildGoalWorkspaceScaffold(input) {
21
+ const title = input.title?.trim() || humanize(input.draftSlug);
22
+ const modules = Array.from({ length: input.moduleCount }, (_, index) => ({
23
+ ref: `${SCAFFOLD_MODULE_PREFIX}${index + 1}`,
24
+ path: `modules/${SCAFFOLD_MODULE_PREFIX}${index + 1}-module-${index + 1}.md`,
25
+ title: `Module ${index + 1}`,
26
+ }));
27
+ const md = (body) => `${body.trim()}\n\n${SCAFFOLD_MARKER}\n`;
28
+ return [
29
+ {
30
+ path: "AGENTS.md",
31
+ content: md(`# Tutor Agent Instructions
32
+
33
+ You are Rocky, running **${title}** with one student.
34
+
35
+ ## Tutoring style
36
+
37
+ - Ask one focused question at a time; the student does the thinking.
38
+ - Look at real work before judging anything.
39
+ - When the student is stuck, drop one level: a smaller step or a worked half-example.
40
+
41
+ ## Coaching rules for this path
42
+
43
+ - Write the runtime rules Rocky must follow in every session here.
44
+
45
+ ## File discipline
46
+
47
+ - Keep durable progress in \`state/progress.json\`.
48
+ - Put student-facing work under \`resources/\`; student uploads arrive under \`uploads/\`.`),
49
+ },
50
+ {
51
+ path: "first-message.md",
52
+ content: md(`# First Message
53
+
54
+ Write Rocky's opening line for the first session. Keep it to the goal's first session and make it agree with ${modules[0].ref} and \`AGENTS.md\`.`),
55
+ },
56
+ {
57
+ path: "state/progress.json",
58
+ content: `${JSON.stringify({
59
+ currentModuleRef: modules[0].ref,
60
+ completedModuleRefs: [],
61
+ course_status: "ready",
62
+ lastTutorSummary: null,
63
+ }, null, 2)}\n`,
64
+ },
65
+ ...modules.map((module, index) => ({
66
+ path: module.path,
67
+ content: md(`# Module ${module.ref}: ${module.title}
68
+
69
+ Summary: One sentence on what the student makes or masters in this module.
70
+ Estimated time: 30 minutes
71
+
72
+ ## Student-facing launch
73
+
74
+ Where to start: name the exact page, app, file, or tab Rocky opens first, then the first three moves in order. Offer choices as spoken either/or questions.
75
+
76
+ ## Learning targets
77
+
78
+ - The skill this module builds, stated as something the student can do.
79
+
80
+ ## Tutor guidance
81
+
82
+ - How Rocky runs this module, what to watch for, and how to respond when the student stalls or rushes.
83
+
84
+ ## Resources and surfaces
85
+
86
+ - The exact links, apps, or workspace files this module uses.
87
+
88
+ ## Completion criteria
89
+
90
+ - The visible work that proves the learning target${index === modules.length - 1 ? " and finishes the path" : ""}.
91
+
92
+ ## State updates
93
+
94
+ - Keep the current step in \`state/progress.json\` current; \`complete_module\` records the completion.`),
95
+ })),
96
+ ];
97
+ }
98
+ // ---------------------------------------------------------------------------
99
+ // Local workspace validation (mirror of goal-builder-workspace-validation.ts)
100
+ // ---------------------------------------------------------------------------
101
+ // `state/progress.json` is optional: the server seeds it at create.
102
+ const REQUIRED_TOP_LEVEL_FILES = ["AGENTS.md", "first-message.md"];
103
+ const READY_MODULE_REQUIREMENTS = [
104
+ { label: "learning target", patterns: [/^Learning targets?\b/i] },
105
+ {
106
+ label: "tutor guidance or activity plan",
107
+ patterns: [
108
+ /^Tutor guidance\b/i,
109
+ /^Activity recipe\b/i,
110
+ /^Beat structure\b/i,
111
+ /^Sittings?\b/i,
112
+ /^Sitting plan\b/i,
113
+ ],
114
+ },
115
+ {
116
+ label: "resources and surfaces",
117
+ patterns: [/^Resources(?: and surfaces)?\b/i],
118
+ },
119
+ { label: "completion criteria", patterns: [/^Completion criteria\b/i] },
120
+ { label: "state updates", patterns: [/^State updates\b/i] },
121
+ ];
122
+ const SIMPLE_DAILY_TODO_GOAL_MODES = new Set([
123
+ "simple_daily_todos",
124
+ "legacy_daily_todos",
125
+ "simple_todo_goal",
126
+ ]);
127
+ /** `goal-module-sync.ts` `moduleRefFromPath`: `W2-M1-basic-physics.md` → `W2-M1`. */
128
+ export function moduleRefFromPath(workspacePath) {
129
+ const fileName = workspacePath.split("/").pop() ?? workspacePath;
130
+ const match = fileName.match(/^([A-Za-z]\d+-[A-Za-z]\d+|[A-Za-z]\d+|\d{2,4})[-_. ]/);
131
+ return match?.[1]?.toUpperCase() ?? null;
132
+ }
133
+ /** Prose lines: HTML comments and fenced code removed (approximation of `readModuleMarkdown`). */
134
+ function liveLines(content) {
135
+ const withoutComments = content.replace(/<!--[\s\S]*?-->/g, "");
136
+ const lines = [];
137
+ let fence = null;
138
+ for (const line of withoutComments.split(/\r?\n/)) {
139
+ const marker = line.match(/^\s{0,3}(`{3,}|~{3,})/)?.[1];
140
+ if (marker) {
141
+ if (!fence)
142
+ fence = marker[0];
143
+ else if (marker[0] === fence)
144
+ fence = null;
145
+ continue;
146
+ }
147
+ if (!fence)
148
+ lines.push(line);
149
+ }
150
+ return lines;
151
+ }
152
+ function headerLinePattern(label) {
153
+ const escaped = label.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
154
+ return new RegExp(`^(\\s*(?:[-*>]\\s+)*(#{1,6}\\s+)?(?:\\*\\*|__)?${escaped}(?:\\s*\\([^)]*\\))?\\s*(?::\\s*(?:\\*\\*|__)|(?:\\*\\*|__)\\s*:|:)\\s*)(.*?)\\s*$`, "i");
155
+ }
156
+ function headerField(lines, label) {
157
+ const pattern = headerLinePattern(label);
158
+ for (const line of lines) {
159
+ const match = line.match(pattern);
160
+ if (!match)
161
+ continue;
162
+ const raw = (match[2] ? match[3].replace(/\s+#+$/, "") : match[3])
163
+ .replace(/\s+/g, " ")
164
+ .trim();
165
+ if (!raw || /<[^<>\n]*>/.test(raw))
166
+ continue;
167
+ const value = raw.replace(/^`([^`]+)`$/, "$1").trim();
168
+ if (value)
169
+ return value;
170
+ }
171
+ return null;
172
+ }
173
+ function populatedSections(lines) {
174
+ const sections = [];
175
+ let current = null;
176
+ for (const line of lines) {
177
+ const heading = line.match(/^\s{0,3}(#{1,6})\s+(.*?)\s*#*\s*$/);
178
+ if (heading) {
179
+ const depth = heading[1].length;
180
+ if (depth <= 2) {
181
+ current = depth === 2 ? { text: heading[2], body: [] } : null;
182
+ if (current)
183
+ sections.push(current);
184
+ }
185
+ continue;
186
+ }
187
+ current?.body.push(line);
188
+ }
189
+ return sections
190
+ .filter((section) => section.body.some((line) => /\S/.test(line)))
191
+ .map((section) => section.text);
192
+ }
193
+ function moduleContentErrors(path, content) {
194
+ if (!content.trim())
195
+ return [`${path} is empty`];
196
+ const lines = liveLines(content);
197
+ const status = headerField(lines, "Materialization status") ??
198
+ headerField(lines, "Module status");
199
+ if (status && /^(planned-stub|planned|stub)$/i.test(status)) {
200
+ const missing = [];
201
+ const legacy = headerField(lines, "PDF/source");
202
+ if (!headerField(lines, "Mode"))
203
+ missing.push("Mode");
204
+ if (!headerField(lines, "Source PDF") && !legacy)
205
+ missing.push("Source PDF or PDF/source");
206
+ if (!headerField(lines, "Source pages") && !legacy)
207
+ missing.push("Source pages or PDF/source page range");
208
+ return missing.length
209
+ ? [
210
+ `${path} is a planned curriculum stub but is missing ${missing.join(", ")}`,
211
+ ]
212
+ : [];
213
+ }
214
+ const sections = populatedSections(lines);
215
+ const has = (patterns) => sections.some((text) => patterns.some((pattern) => pattern.test(text)));
216
+ const missing = [];
217
+ if (!headerField(lines, "Summary") && !has([/^Summary\b/i]))
218
+ missing.push("summary");
219
+ if (!(Number(headerField(lines, "Estimated time")?.match(/^\d+/)?.[0]) > 0))
220
+ missing.push("estimated time (`Estimated time: 30 minutes`)");
221
+ for (const requirement of READY_MODULE_REQUIREMENTS) {
222
+ if (!has(requirement.patterns))
223
+ missing.push(requirement.label);
224
+ }
225
+ const errors = missing.length
226
+ ? [
227
+ `${path} is not a complete runtime module; missing ${missing.join(", ")}. Required: a Summary line or ## Summary, an Estimated time line, and populated ## Learning targets, ## Tutor guidance, ## Resources and surfaces, ## Completion criteria, ## State updates.`,
228
+ ]
229
+ : [];
230
+ const itemKey = headerField(lines, "Item key");
231
+ if (itemKey && !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$/.test(itemKey)) {
232
+ errors.push(`Invalid lesson Item key in ${path}`);
233
+ }
234
+ return errors;
235
+ }
236
+ function hasUnresolvedPlaceholder(path, content) {
237
+ const lines = path.endsWith(".md")
238
+ ? liveLines(content).map((line) => line.replace(/`[^`]*`/g, ""))
239
+ : content.split(/\r?\n/);
240
+ return lines.some((line) => {
241
+ if (!/\{\{\s*[^{}\n]+\s*\}\}/.test(line))
242
+ return false;
243
+ const prose = line.replace(/\{\{\s*[^{}\n]+\s*\}\}/g, " ").toLowerCase();
244
+ return !/\b(example|syntax|literal|placeholder|template|token|mustache)\b/.test(prose);
245
+ });
246
+ }
247
+ /** Mirror of the server's `SIDE_FILE_REFERENCE`: files voice Rocky never sees. */
248
+ const SIDE_FILE_REFERENCE = /\btutor-toolkit\/[\w./-]+\.\w+|\b(?:README|goal-architecture|lesson-template|final-assessment|build-report)\.md\b/g;
249
+ const TEXT_EXTENSIONS = /\.(md|markdown|txt|json|html?|css|js|mjs|ts|csv|ya?ml|svg)$/i;
250
+ /**
251
+ * Mirrors the server's file, section, module and progress rules. File
252
+ * reference closure is not mirrored; the server checks it at create/capture.
253
+ */
254
+ export function validateGoalWorkspaceLocally(files) {
255
+ const errors = [];
256
+ const warnings = [];
257
+ const byPath = new Map(files.map((file) => [file.path, file]));
258
+ for (const required of REQUIRED_TOP_LEVEL_FILES) {
259
+ const file = byPath.get(required);
260
+ if (!file)
261
+ errors.push(`Missing required file: ${required}`);
262
+ else if (!file.content.trim())
263
+ errors.push(`Required file is empty: ${required}`);
264
+ }
265
+ const moduleRefs = new Map();
266
+ for (const file of files) {
267
+ if (!file.path.startsWith("modules/") || !file.path.endsWith(".md"))
268
+ continue;
269
+ const ref = moduleRefFromPath(file.path);
270
+ if (!ref) {
271
+ warnings.push(`${file.path} is not a module: its name does not start with a module ref (e.g. W1-M1-topic.md, M3-topic.md, 04-topic.md), so it will be silently ignored`);
272
+ continue;
273
+ }
274
+ moduleRefs.set(ref, [...(moduleRefs.get(ref) ?? []), file.path]);
275
+ errors.push(...moduleContentErrors(file.path, file.content));
276
+ }
277
+ for (const [ref, paths] of moduleRefs) {
278
+ if (paths.length > 1)
279
+ errors.push(`${paths.join(" and ")} both parse as module ${ref}; one would overwrite the other`);
280
+ }
281
+ let progress = null;
282
+ const progressFile = byPath.get("state/progress.json");
283
+ if (progressFile) {
284
+ try {
285
+ const parsed = JSON.parse(progressFile.content);
286
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
287
+ progress = parsed;
288
+ }
289
+ else {
290
+ errors.push("state/progress.json must contain a JSON object");
291
+ }
292
+ }
293
+ catch (error) {
294
+ errors.push(`state/progress.json is invalid JSON: ${error instanceof Error ? error.message : String(error)}`);
295
+ }
296
+ }
297
+ const mode = progress?.goalMode ?? progress?.goal_mode ?? progress?.mode;
298
+ const simpleDaily = typeof mode === "string" &&
299
+ SIMPLE_DAILY_TODO_GOAL_MODES.has(mode.trim().toLowerCase());
300
+ const rawCurrent = progress?.currentModuleRef ?? progress?.current_module;
301
+ const currentRef = typeof rawCurrent === "string" && rawCurrent.trim()
302
+ ? rawCurrent.trim().toUpperCase()
303
+ : null;
304
+ if (moduleRefs.size === 0) {
305
+ if (simpleDaily)
306
+ warnings.push("Simple daily todo workspace has no parseable modules; it will not create launch todos");
307
+ else
308
+ errors.push("Workspace must include at least one parseable modules/*.md file");
309
+ }
310
+ else if (progress) {
311
+ if (!currentRef)
312
+ warnings.push("state/progress.json has no currentModuleRef or current_module");
313
+ else if (!moduleRefs.has(currentRef))
314
+ errors.push(`state/progress.json current module ${currentRef} does not match a module file`);
315
+ }
316
+ for (const file of files) {
317
+ if (file.path !== "AGENTS.md" &&
318
+ !(file.path.startsWith("modules/") && file.path.endsWith(".md")))
319
+ continue;
320
+ const cited = new Set(liveLines(file.content).flatMap((line) => [...line.matchAll(SIDE_FILE_REFERENCE)].map((match) => match[0])));
321
+ if (cited.size > 0)
322
+ warnings.push(`${file.path} sends Rocky to ${[...cited].join(", ")}; voice Rocky never sees side files (he can only ask a helper to look one up), so put what he needs during the lesson in AGENTS.md or the module itself`);
323
+ }
324
+ const buildReport = byPath.get("build-report.md")?.content;
325
+ if (buildReport &&
326
+ !/\b(validation|self-coherence|checks?)\b/i.test(buildReport))
327
+ warnings.push("build-report.md does not clearly describe validation checks performed");
328
+ const scaffolded = [];
329
+ for (const file of files) {
330
+ if (!TEXT_EXTENSIONS.test(file.path))
331
+ continue;
332
+ if (hasUnresolvedPlaceholder(file.path, file.content))
333
+ errors.push(`Unresolved placeholder marker in ${file.path}`);
334
+ if (file.content.includes(SCAFFOLD_MARKER))
335
+ scaffolded.push(file.path);
336
+ }
337
+ if (scaffolded.length > 0)
338
+ warnings.push(`${scaffolded.length} file(s) still carry scaffold text (remove the recess-scaffold marker once rewritten): ${scaffolded.join(", ")}`);
339
+ return {
340
+ source: "local",
341
+ ok: errors.length === 0,
342
+ errors,
343
+ warnings,
344
+ note: "Local check of required files, module sections, module filenames, and progress state. The server also checks file references when the draft is created or captured.",
345
+ };
346
+ }
347
+ /**
348
+ * Reads the server's draft `validation` (`{ok, baseChangeId, fileCount,
349
+ * errors, warnings, issues}`) from a workspace-files dry run, write, or init.
350
+ */
351
+ export function serverWorkspaceValidation(response) {
352
+ const validation = response && typeof response === "object"
353
+ ? response.validation
354
+ : undefined;
355
+ if (!validation || typeof validation !== "object")
356
+ return null;
357
+ const value = validation;
358
+ const list = (raw) => Array.isArray(raw)
359
+ ? raw.map((entry) => typeof entry === "string" ? entry : JSON.stringify(entry))
360
+ : [];
361
+ const errors = list(value.errors);
362
+ const issues = Array.isArray(value.issues)
363
+ ? value.issues.flatMap((entry) => {
364
+ if (!entry || typeof entry !== "object")
365
+ return [];
366
+ const issue = entry;
367
+ if (typeof issue.message !== "string")
368
+ return [];
369
+ return [
370
+ {
371
+ path: typeof issue.path === "string" ? issue.path : null,
372
+ rule: typeof issue.rule === "string" ? issue.rule : "unknown",
373
+ message: issue.message,
374
+ fix: typeof issue.fix === "string" ? issue.fix : null,
375
+ },
376
+ ];
377
+ })
378
+ : undefined;
379
+ return {
380
+ source: "server",
381
+ ok: typeof value.ok === "boolean" ? value.ok : errors.length === 0,
382
+ errors,
383
+ warnings: list(value.warnings),
384
+ ...(issues ? { issues } : {}),
385
+ ...(typeof value.baseChangeId === "string"
386
+ ? { baseChangeId: value.baseChangeId }
387
+ : {}),
388
+ ...(typeof value.fileCount === "number"
389
+ ? { fileCount: value.fileCount }
390
+ : {}),
391
+ };
392
+ }
393
+ // ---------------------------------------------------------------------------
394
+ // validate-spec error formatting
395
+ // ---------------------------------------------------------------------------
396
+ function issuePath(prefix, path) {
397
+ const parts = Array.isArray(path) ? path : [];
398
+ return parts.reduce((joined, part) => typeof part === "number"
399
+ ? `${joined}[${part}]`
400
+ : `${joined}.${String(part)}`, prefix);
401
+ }
402
+ /**
403
+ * Turns a validate-spec failure into `path: message` lines. Reads a structured
404
+ * `errors`/`issues` array when the server sends one, and otherwise unpacks the
405
+ * Zod issue JSON embedded in the legacy `error` string.
406
+ */
407
+ export function specValidationErrorLines(validation) {
408
+ if (!validation || typeof validation !== "object")
409
+ return [];
410
+ const value = validation;
411
+ const structured = Array.isArray(value.errors)
412
+ ? value.errors
413
+ : Array.isArray(value.issues)
414
+ ? value.issues
415
+ : null;
416
+ if (structured) {
417
+ return structured.map((entry) => {
418
+ if (typeof entry === "string")
419
+ return entry;
420
+ const issue = entry;
421
+ const where = typeof issue.path === "string"
422
+ ? issue.path
423
+ : issuePath("", issue.path).replace(/^\./, "");
424
+ const message = typeof issue.message === "string" ? issue.message : "invalid";
425
+ return `${where || "(document)"}: ${message}`;
426
+ });
427
+ }
428
+ const error = typeof value.error === "string" ? value.error : null;
429
+ if (!error)
430
+ return [];
431
+ const start = error.indexOf("[");
432
+ if (start !== -1) {
433
+ try {
434
+ const issues = JSON.parse(error.slice(start));
435
+ if (Array.isArray(issues)) {
436
+ return issues.flatMap((issue) => {
437
+ const nested = issue.unionErrors?.flatMap((union) => union.issues ?? []);
438
+ const leaves = nested && nested.length > 0 ? nested : [issue];
439
+ return leaves.map((leaf) => `${issuePath("setupWorkflowSpec", leaf.path)}: ${leaf.message ?? "invalid"}`);
440
+ });
441
+ }
442
+ }
443
+ catch {
444
+ // Not Zod JSON; fall through to the message itself.
445
+ }
446
+ }
447
+ return [`setupWorkflowSpec: ${error}`];
448
+ }
449
+ function specSteps(spec) {
450
+ const steps = spec?.steps;
451
+ return Array.isArray(steps)
452
+ ? steps.filter((step) => step &&
453
+ typeof step === "object" &&
454
+ typeof step.key === "string" &&
455
+ typeof step.kind === "string")
456
+ : [];
457
+ }
458
+ /** `subjectMatrixOptions`: skill-queue subjects or bundle recipes. */
459
+ function subjectKeys(spec) {
460
+ const handler = spec
461
+ ?.handler;
462
+ const config = (handler?.config ?? {});
463
+ const entries = handler?.type === "EXTERNAL_SKILL_QUEUE_SETUP"
464
+ ? config.subjects
465
+ : handler?.type === "GOAL_BUNDLE_SETUP"
466
+ ? config.recipes
467
+ : undefined;
468
+ return (entries ?? [])
469
+ .map((entry) => entry.key)
470
+ .filter((key) => typeof key === "string");
471
+ }
472
+ export const STUDENT_PLACEHOLDER = "<kid-id>";
473
+ /**
474
+ * The answers JSON `apply-workflow` validates against `buildAnswersSchema`:
475
+ * `{ <student step>: [kidId], <select>: "value", <subject_matrix>: { kidId: [subjectKey] } }`.
476
+ * Required steps get a default or the first option; `placeholders` lists every
477
+ * value an author must still choose.
478
+ */
479
+ export function buildAnswersTemplate(spec, studentIds) {
480
+ const students = studentIds.length > 0 ? studentIds : [STUDENT_PLACEHOLDER];
481
+ const keys = subjectKeys(spec);
482
+ const answers = {};
483
+ const placeholders = [];
484
+ const steps = [];
485
+ for (const step of specSteps(spec)) {
486
+ const required = step.required !== false;
487
+ const options = (step.options ?? []).map((option) => option.value);
488
+ steps.push({
489
+ key: step.key,
490
+ kind: step.kind,
491
+ label: step.label ?? null,
492
+ required,
493
+ ...(step.availableWhen ? { availableWhen: step.availableWhen } : {}),
494
+ ...(options.length ? { options } : {}),
495
+ ...(step.kind === "subject_matrix" && keys.length
496
+ ? { subjectKeys: keys }
497
+ : {}),
498
+ ...(step.kind === "choice" && step.multi ? { multi: true } : {}),
499
+ ...(step.kind === "number"
500
+ ? { min: step.min ?? null, max: step.max ?? null }
501
+ : {}),
502
+ });
503
+ // Conditional steps depend on other answers; they are listed, not filled.
504
+ if (step.availableWhen)
505
+ continue;
506
+ let value;
507
+ switch (step.kind) {
508
+ case "student_multi_select":
509
+ value = students;
510
+ if (studentIds.length === 0)
511
+ placeholders.push(step.key);
512
+ break;
513
+ case "grade_select":
514
+ case "state_select":
515
+ case "schedule":
516
+ value = step.defaultValue ?? options[0];
517
+ if (step.defaultValue === undefined)
518
+ placeholders.push(step.key);
519
+ break;
520
+ case "choice":
521
+ value = step.multi ? options.slice(0, 1) : options[0];
522
+ placeholders.push(step.key);
523
+ break;
524
+ case "subject_matrix":
525
+ value = Object.fromEntries(students.map((student) => [student, keys.slice(0, 1)]));
526
+ placeholders.push(step.key);
527
+ break;
528
+ case "number":
529
+ value = step.policyField
530
+ ? { mode: "inherit" }
531
+ : (step.defaultValue ?? step.min ?? 1);
532
+ if (!step.policyField && step.defaultValue === undefined)
533
+ placeholders.push(step.key);
534
+ break;
535
+ case "boolean":
536
+ value = step.defaultValue ?? false;
537
+ if (step.defaultValue === undefined)
538
+ placeholders.push(step.key);
539
+ break;
540
+ case "url":
541
+ value = "https://example.com/replace-me";
542
+ placeholders.push(step.key);
543
+ break;
544
+ case "book_pick":
545
+ value = "00000000-0000-0000-0000-000000000000";
546
+ placeholders.push(step.key);
547
+ break;
548
+ default:
549
+ continue;
550
+ }
551
+ if (!required && step.defaultValue === undefined) {
552
+ // Optional steps without a default stay out of the file.
553
+ const index = placeholders.indexOf(step.key);
554
+ if (index !== -1)
555
+ placeholders.splice(index, 1);
556
+ continue;
557
+ }
558
+ if (value !== undefined)
559
+ answers[step.key] = value;
560
+ }
561
+ return { answers, placeholders, steps };
562
+ }
563
+ /**
564
+ * Put the chosen students into the student step and re-key every
565
+ * subject_matrix to them: a flat array or a single placeholder key becomes
566
+ * `{ kidId: keys }` per student.
567
+ */
568
+ export function applyStudentsToAnswers(spec, answers, studentIds) {
569
+ const next = { ...answers };
570
+ const steps = specSteps(spec);
571
+ const studentStep = steps.find((step) => step.kind === "student_multi_select");
572
+ if (studentIds.length > 0) {
573
+ if (!studentStep) {
574
+ throw new CliError("invalid_arguments", "This template's wizard has no student step, so --student cannot be applied. Use --answers-file only.");
575
+ }
576
+ next[studentStep.key] = studentIds;
577
+ for (const step of steps.filter((s) => s.kind === "subject_matrix")) {
578
+ const matrix = next[step.key];
579
+ if (matrix === undefined)
580
+ continue;
581
+ if (Array.isArray(matrix)) {
582
+ next[step.key] = Object.fromEntries(studentIds.map((student) => [student, matrix]));
583
+ continue;
584
+ }
585
+ if (matrix && typeof matrix === "object") {
586
+ const entries = Object.entries(matrix);
587
+ const keyed = entries.filter(([key]) => studentIds.includes(key));
588
+ if (keyed.length === 0 && entries.length === 1) {
589
+ next[step.key] = Object.fromEntries(studentIds.map((student) => [student, entries[0][1]]));
590
+ }
591
+ }
592
+ }
593
+ }
594
+ const missingRequired = steps
595
+ .filter((step) => step.required !== false &&
596
+ !step.availableWhen &&
597
+ !Object.prototype.hasOwnProperty.call(next, step.key))
598
+ .map((step) => step.key);
599
+ return { answers: next, missingRequired };
600
+ }
601
+ // ---------------------------------------------------------------------------
602
+ // Student resolution
603
+ // ---------------------------------------------------------------------------
604
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
605
+ /** `GET /tutor/students` row cap for a staff `search` (SEARCH_STUDENT_LIMIT in tutor/get.students.ts). */
606
+ const STAFF_SEARCH_LIMIT = 50;
607
+ const normalizeName = (name) => name.trim().replace(/\s+/g, " ").toLowerCase();
608
+ /**
609
+ * `--student` accepts a user ID or an exact (case/whitespace-insensitive)
610
+ * full name from the caller's roster. Several matches are an error that
611
+ * lists them; an ID is passed through without a request.
612
+ */
613
+ export async function resolveStudentReference(api, value) {
614
+ const reference = value.trim();
615
+ if (UUID_RE.test(reference))
616
+ return { id: reference, name: null };
617
+ const wanted = normalizeName(reference);
618
+ const roster = unwrap(await api.client.GET("/tutor/students", {
619
+ params: { query: { scope: "mine" } },
620
+ })).items;
621
+ let matches = roster.filter((item) => normalizeName(item.name) === wanted);
622
+ if (matches.length === 0) {
623
+ // A staff roster is "mine" by default; search widens it to every student
624
+ // the server lets this session see, then the full name must still match.
625
+ const token = reference.split(/\s+/)[0];
626
+ const searched = unwrap(await api.client.GET("/tutor/students", {
627
+ params: { query: { search: token } },
628
+ }));
629
+ matches = searched.items.filter((item) => normalizeName(item.name) === wanted);
630
+ // A staff "all" search is capped and activity-ranked; a full page may
631
+ // hide a same-named kid, so it can never prove a name unique.
632
+ if (searched.scopeApplied === "all" &&
633
+ searched.items.length >= STAFF_SEARCH_LIMIT)
634
+ throw new CliError("ambiguous_student", `Too many students match "${token}" to be sure "${reference}" is unique. Retry with the kid's ID (\`students list\` or \`users search\` finds it).`, 1, {
635
+ truncated: true,
636
+ matches: matches.map(({ userId, name }) => ({ userId, name })),
637
+ });
638
+ }
639
+ const unique = [...new Map(matches.map((m) => [m.userId, m])).values()];
640
+ if (unique.length !== 1) {
641
+ throw new CliError(unique.length ? "ambiguous_student" : "student_not_found", unique.length
642
+ ? `${unique.length} students are named "${reference}": ${unique.map((m) => `${m.name} (${m.userId})`).join(", ")}. Retry with the ID.`
643
+ : `No student named exactly "${reference}" is visible to this session. Use \`students list\` to find the ID.`, 1, { matches: unique.map(({ userId, name }) => ({ userId, name })) });
644
+ }
645
+ return { id: unique[0].userId, name: unique[0].name };
646
+ }
647
+ //# sourceMappingURL=goal-authoring.js.map