recess-cli 3.50.2 → 3.52.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/cli.js CHANGED
@@ -1,12 +1,12 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import { execFile } from "node:child_process";
3
- import fs from "node:fs/promises";
3
+ import { fs, inAppGit, inAppState, isInApp, runInApp, } from "./in-app.js";
4
4
  import path from "node:path";
5
5
  import { RecessAdminApi, unwrap, withIdempotencyContext } from "./api.js";
6
6
  import { flagList, flagNumber, flagString, hasFlag, parseArgs, } from "./args.js";
7
7
  import { login, pollDeviceAuth, requestDeviceAuth } from "./auth.js";
8
8
  import { clearStoredSession, withConfigLock, deleteProfile, listProfiles, resolveConfig, saveProfile, useProfile, } from "./config.js";
9
- import { agentContext, buildCommandSchema, findCommandSchema, remoteCommands, scopedHelp, validateInvocation, } from "./command-schema.js";
9
+ import { agentContext, buildCommandSchema, findCommandSchema, inAppCommands, remoteCommands, scopedHelp, validateInvocation, } from "./command-schema.js";
10
10
  import { runAdmissionsCommand } from "./commands/admissions.js";
11
11
  import { runApplicationsCommand } from "./commands/applications.js";
12
12
  import { runAppsCommand } from "./commands/apps.js";
@@ -157,6 +157,196 @@ async function resolveSessionRole(api) {
157
157
  * `goals archive`, which frees an open-goal slot and writes a different audit
158
158
  * row. */
159
159
  const EDITABLE_GOAL_STATUSES = ["ACTIVE", "PAUSED"];
160
+ /**
161
+ * A goal's place on the kid's day (`Goal.required`), keyed by `--value`. The
162
+ * deltas are the history lines the staff page's Core toggle writes, so a goal's
163
+ * change log reads the same from either surface.
164
+ */
165
+ const GOAL_PLACEMENTS = {
166
+ on: {
167
+ required: true,
168
+ label: "Core",
169
+ delta: "Moved to Core",
170
+ consequence: (kid) => `Core: part of ${kid}'s day; ${kid} can't leave it.`,
171
+ },
172
+ off: {
173
+ required: false,
174
+ label: "optional",
175
+ delta: "Locked until core is done",
176
+ consequence: (kid) => `Optional: its to-dos open after core work and never count as behind; ${kid} can leave it, and the parent can pause it but not remove it.`,
177
+ },
178
+ };
179
+ function setRequiredCommand(studentUserId, goalId, placement) {
180
+ return `recess goals set-required --student ${studentUserId} --goal ${goalId} --value ${placement} --reason "<why>"`;
181
+ }
182
+ /** The staff page's Core toggle (an /admin route). */
183
+ async function patchGoalPlacement(api, goalId, placement, expectedUpdatedAt) {
184
+ const { required, delta } = GOAL_PLACEMENTS[placement];
185
+ return unwrap(await api.client.PATCH("/admin/browser/students/goals/{goalId}/", {
186
+ params: { path: { goalId } },
187
+ body: {
188
+ required,
189
+ delta,
190
+ ...(expectedUpdatedAt ? { expectedUpdatedAt } : {}),
191
+ },
192
+ }));
193
+ }
194
+ /**
195
+ * Refuse before the preview, so nobody approves a write that a session other
196
+ * than full-admin cannot complete.
197
+ */
198
+ async function assertFullAdminSession(api, command) {
199
+ const session = unwrap(await api.client.GET("/auth/admin-cli/session/"));
200
+ if (session.user.role !== "ADMIN" || session.cliScope !== "full_admin") {
201
+ throw new CliError("forbidden", session.user.role === "GUARDIAN"
202
+ ? `\`${command}\` needs a full-admin session. A parent makes their own kid's challenge optional with \`recess kid set-goal-required\`.`
203
+ : `Only a full-admin CLI session can run \`${command}\`.`, 1, { sessionRole: session.user.role, cliScope: session.cliScope });
204
+ }
205
+ }
206
+ /** The server's apply runs four units at a time; the follow-up matches it. */
207
+ const APPLY_FAN_OUT = 4;
208
+ async function mapWithLimit(items, limit, task) {
209
+ const results = [];
210
+ let next = 0;
211
+ const worker = async () => {
212
+ while (next < items.length) {
213
+ const index = next++;
214
+ results[index] = await task(items[index]);
215
+ }
216
+ };
217
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
218
+ return results;
219
+ }
220
+ /** Each kid's first name and goal places (`required` reads null as Core). */
221
+ async function readKidGoals(api, studentIds) {
222
+ const ids = [...new Set(studentIds)];
223
+ const kids = await mapWithLimit(ids, APPLY_FAN_OUT, async (studentId) => {
224
+ try {
225
+ const [list, detail] = await Promise.all([
226
+ api.client
227
+ .GET("/tutor/browser/students/{userId}/goals/", {
228
+ params: { path: { userId: studentId } },
229
+ })
230
+ .then(unwrap),
231
+ api.client
232
+ .GET("/tutor/students/{studentId}", {
233
+ params: { path: { studentId } },
234
+ })
235
+ .then(unwrap),
236
+ ]);
237
+ return {
238
+ firstName: detail.student.firstName,
239
+ goals: new Map(list.goals.map((goal) => [
240
+ goal.id,
241
+ { required: goal.required, status: goal.status },
242
+ ])),
243
+ };
244
+ }
245
+ catch (error) {
246
+ return { error: error instanceof Error ? error.message : String(error) };
247
+ }
248
+ });
249
+ return new Map(ids.map((id, index) => [id, kids[index]]));
250
+ }
251
+ function kidFirstName(unit, kids) {
252
+ const kid = kids.get(unit.studentUserId);
253
+ return (kid && "firstName" in kid && kid.firstName) || unit.studentName;
254
+ }
255
+ /**
256
+ * Where a goal this apply did not create stands. Under `--optional` such a
257
+ * goal is reported, never patched: it may be a guide's deliberate Core goal.
258
+ */
259
+ function existingGoalPlace(goalId, kid) {
260
+ if (!kid)
261
+ return { error: "The kid's goals were not read." };
262
+ if ("error" in kid)
263
+ return { error: kid.error };
264
+ const goal = kid.goals.get(goalId);
265
+ if (!goal || goal.status === "COMPLETED")
266
+ return "closed";
267
+ return goal.required ? "core" : "optional";
268
+ }
269
+ /** The `--optional` line each preview row shows. */
270
+ function optionalPreviewPlacement(unit, kids) {
271
+ const kid = kidFirstName(unit, kids);
272
+ if (unit.action === "created")
273
+ return GOAL_PLACEMENTS.off.consequence(kid);
274
+ if (!unit.goalId)
275
+ return undefined;
276
+ const place = existingGoalPlace(unit.goalId, kids.get(unit.studentUserId));
277
+ if (place === "core")
278
+ return `Already on ${kid} and Core. This apply leaves it Core and reports it as not optional.`;
279
+ if (place === "optional")
280
+ return `Already on ${kid} and optional.`;
281
+ return undefined;
282
+ }
283
+ /**
284
+ * `goal-templates apply --optional`: set each goal the apply created to
285
+ * optional, then check every other goal the results name. Nothing throws
286
+ * here; each row says where its goal stands and, when it is not optional,
287
+ * the command that fixes it.
288
+ */
289
+ async function makeAppliedGoalsOptional(api, results) {
290
+ const notCreated = results.filter((unit) => unit.action !== "created" && unit.goalId);
291
+ const kids = await readKidGoals(api, notCreated.map((unit) => unit.studentUserId));
292
+ return mapWithLimit(results, APPLY_FAN_OUT, async (unit) => {
293
+ if (!unit.goalId) {
294
+ return {
295
+ ...unit,
296
+ optional: {
297
+ status: "unchanged",
298
+ reason: "No goal was created.",
299
+ },
300
+ };
301
+ }
302
+ const goalId = unit.goalId;
303
+ const fix = setRequiredCommand(unit.studentUserId, goalId, "off");
304
+ const failed = (error) => ({
305
+ ...unit,
306
+ optional: { status: "failed", error, fix },
307
+ });
308
+ if (unit.action !== "created") {
309
+ const place = existingGoalPlace(goalId, kids.get(unit.studentUserId));
310
+ if (typeof place === "object")
311
+ return failed(`Could not read this goal's place: ${place.error}`);
312
+ if (place === "core")
313
+ return {
314
+ ...unit,
315
+ required: true,
316
+ optional: {
317
+ status: "still_core",
318
+ reason: unit.action === "skipped_existing"
319
+ ? "It was already on the kid, so this apply did not change it."
320
+ : "The apply reported an error but left this goal in place.",
321
+ fix,
322
+ },
323
+ };
324
+ return {
325
+ ...unit,
326
+ ...(place === "optional" ? { required: false } : {}),
327
+ optional: {
328
+ status: "unchanged",
329
+ reason: place === "optional"
330
+ ? "It was already optional."
331
+ : "It is archived or no longer on the kid's list.",
332
+ },
333
+ };
334
+ }
335
+ try {
336
+ const goal = await patchGoalPlacement(api, goalId, "off");
337
+ return goal.required
338
+ ? failed("The server still reports this goal as Core.")
339
+ : {
340
+ ...unit,
341
+ required: goal.required,
342
+ optional: { status: "set" },
343
+ };
344
+ }
345
+ catch (error) {
346
+ return failed(error instanceof Error ? error.message : String(error));
347
+ }
348
+ });
349
+ }
160
350
  /**
161
351
  * Reject bad enum values in a goal patch file *before* the preview is built.
162
352
  *
@@ -464,6 +654,8 @@ const GOAL_QUEUE_MAX_ENTRIES = 500;
464
654
  const URL_QUEUE_DESCRIPTION_POINTER = "Skill queue managed by the system.";
465
655
  const RECESS_GIT_METADATA = "recess-workspace.json";
466
656
  async function runGit(cwd, args, options = {}) {
657
+ if (isInApp())
658
+ return inAppGit(cwd, args);
467
659
  return new Promise((resolve, reject) => {
468
660
  execFile("git", ["-C", cwd, ...args], {
469
661
  encoding: "utf8",
@@ -898,6 +1090,10 @@ async function readTutorTemplateLessons(directory) {
898
1090
  return lessons;
899
1091
  }
900
1092
  async function previewBoundWrite(parsed, preview, execute, persistOrOptions = false) {
1093
+ // In the app chat the operation store is the approval ledger, not ~/.recess-cli.
1094
+ const hostedWrite = inAppState()?.write;
1095
+ if (hostedWrite)
1096
+ return hostedWrite(parsed, preview, execute);
901
1097
  const context = await requirePreviewBoundConfirmation(parsed, preview, persistOrOptions);
902
1098
  try {
903
1099
  const result = await withIdempotencyContext(context, execute);
@@ -2181,7 +2377,9 @@ function remoteWriteCommand(argv, structuredInput, store) {
2181
2377
  details: {
2182
2378
  ...preview.details,
2183
2379
  operationKey,
2184
- retry: "Confirm with the same command path plus --confirm --operation-key <operationKey>. The hosted service will execute the stored exact payload; do not retransmit structured input.",
2380
+ retry: isInApp()
2381
+ ? "After the person approves in a later message, rerun the identical command plus --confirm --operation-key <operationKey>."
2382
+ : "Confirm with the same command path plus --confirm --operation-key <operationKey>. The hosted service will execute the stored exact payload; do not retransmit structured input.",
2185
2383
  },
2186
2384
  });
2187
2385
  }
@@ -2238,6 +2436,12 @@ async function readAssignmentSelection(filePath) {
2238
2436
  },
2239
2437
  };
2240
2438
  }
2439
+ /** The only commands that take a JSON document in place of a local file. */
2440
+ const STRUCTURED_INPUT_COMMANDS = [
2441
+ "apps validate",
2442
+ "goal-templates validate-spec",
2443
+ "goal-templates create",
2444
+ ];
2241
2445
  /** Hosted goal-template authoring and skills are guide/admin only (see below). */
2242
2446
  const HOSTED_STAFF_NOUNS = new Set(["goal-templates", "skills"]);
2243
2447
  /**
@@ -2259,26 +2463,41 @@ export async function executeRecessCommand(argv, options = {}) {
2259
2463
  const [noun, verb] = parsed.positionals;
2260
2464
  const commands = buildCommandSchema(HELP);
2261
2465
  const isRemote = options.transport === "remote";
2262
- if (!isRemote && !options.operationStore) {
2466
+ const inApp = options.transport === "in-app";
2467
+ if (inApp && !isInApp()) {
2468
+ return runInApp(() => executeRecessCommand(argv, options), {
2469
+ files: options.files,
2470
+ store: options.fileStore,
2471
+ });
2472
+ }
2473
+ // No local machine: hosted MCP's small catalog, or the app chat's full one.
2474
+ const isHosted = isRemote || inApp;
2475
+ if (!isHosted && !options.operationStore) {
2263
2476
  localInvocations.set(parsed, { argv: [...argv] });
2264
2477
  }
2265
- if (isRemote &&
2266
- (!options.api || !options.config || !options.operationStore)) {
2478
+ if (isHosted &&
2479
+ (!options.api ||
2480
+ !options.config ||
2481
+ !options.operationStore ||
2482
+ (inApp && !options.discovery))) {
2267
2483
  throw new CliError("remote_context_required", "Hosted execution requires injected API, configuration, and operation-store adapters.");
2268
2484
  }
2269
- if (isRemote) {
2485
+ if (isHosted) {
2270
2486
  const forbiddenTransportFlag = ["deliver", "profile", "json"].find((name) => hasFlag(parsed, name));
2271
2487
  if (forbiddenTransportFlag) {
2272
- throw new CliError("remote_flag_unavailable", `--${forbiddenTransportFlag} is not available over hosted MCP.`);
2488
+ throw new CliError("remote_flag_unavailable", `--${forbiddenTransportFlag} is not available ${inApp ? "in the Recess app chat" : "over hosted MCP"}.`);
2273
2489
  }
2274
2490
  }
2275
2491
  const writeCommand = options.operationStore
2276
2492
  ? remoteWriteCommand(argv, options.structuredInput, options.operationStore)
2277
2493
  : localWriteCommand;
2494
+ const inAppRun = inAppState();
2495
+ if (inAppRun)
2496
+ inAppRun.write = writeCommand;
2278
2497
  // Before the help branch: `--version` parses as a FLAG, so `noun` is
2279
2498
  // undefined and `!noun` would return help instead. (Found by running it.)
2280
2499
  if (noun === "version" || (!noun && hasFlag(parsed, "version"))) {
2281
- if (isRemote) {
2500
+ if (isHosted) {
2282
2501
  throw new CliError("remote_command_unavailable", "The version command is not exposed by the hosted Recess CLI.");
2283
2502
  }
2284
2503
  const unknown = Array.from(parsed.flags.keys()).filter((name) => !["deliver", "json", "no-json", "pretty", "version"].includes(name));
@@ -2311,10 +2530,13 @@ export async function executeRecessCommand(argv, options = {}) {
2311
2530
  const discovery = options.discovery ?? resolveCommandDiscovery(config);
2312
2531
  const visibleCommands = isRemote
2313
2532
  ? hostedCommands(commands, discovery)
2314
- : commands;
2533
+ : inApp
2534
+ ? inAppCommands(commands, discovery)
2535
+ : commands;
2315
2536
  return {
2316
2537
  help: scopedHelp(HELP, visibleCommands, [], discovery, {
2317
2538
  remoteOnly: isRemote,
2539
+ inApp,
2318
2540
  all: hasFlag(parsed, "all"),
2319
2541
  }),
2320
2542
  };
@@ -2325,26 +2547,34 @@ export async function executeRecessCommand(argv, options = {}) {
2325
2547
  const discovery = options.discovery ?? resolveCommandDiscovery(config);
2326
2548
  const visibleCommands = isRemote
2327
2549
  ? hostedCommands(commands, discovery)
2328
- : commands;
2550
+ : inApp
2551
+ ? inAppCommands(commands, discovery)
2552
+ : commands;
2329
2553
  return {
2330
2554
  help: scopedHelp(HELP, visibleCommands, scope, discovery, {
2331
2555
  remoteOnly: isRemote,
2556
+ inApp,
2332
2557
  all: hasFlag(parsed, "all"),
2333
2558
  }),
2334
2559
  };
2335
2560
  }
2336
2561
  validateInvocation(parsed, commands, { remote: isRemote });
2562
+ if (inApp) {
2563
+ if (noun === "confirm") {
2564
+ throw new CliError("command_unavailable", "Confirm with the same command plus --confirm --operation-key <operationKey>.");
2565
+ }
2566
+ const command = findCommandSchema(commands, parsed.positionals);
2567
+ if (!command || inAppCommands([command], options.discovery).length === 0) {
2568
+ throw new CliError("command_unavailable", `\`${parsed.positionals.join(" ")}\` is not available in the Recess app chat for this account. Run \`help\` for the catalog.`);
2569
+ }
2570
+ }
2337
2571
  if (isRemote) {
2338
2572
  const command = findCommandSchema(commands, parsed.positionals);
2339
2573
  if (!command?.remoteCapable) {
2340
2574
  throw new CliError("remote_command_unavailable", `\`${parsed.positionals.join(" ")}\` is not exposed by the hosted Recess CLI. Use help or agent-context to discover the remote catalog.`);
2341
2575
  }
2342
2576
  if (options.structuredInput !== undefined &&
2343
- ![
2344
- "apps validate",
2345
- "goal-templates validate-spec",
2346
- "goal-templates create",
2347
- ].includes(command.path.join(" "))) {
2577
+ !STRUCTURED_INPUT_COMMANDS.includes(command.path.join(" "))) {
2348
2578
  throw new CliError("invalid_arguments", "Structured input is accepted only by hosted apps validate and goal-templates validate-spec/create.");
2349
2579
  }
2350
2580
  if (!hostedNounAllowed(noun, options.session?.user.role, options.discovery?.scope)) {
@@ -2361,16 +2591,20 @@ export async function executeRecessCommand(argv, options = {}) {
2361
2591
  }
2362
2592
  }
2363
2593
  if (noun === "agent-context") {
2364
- const [profiles, config] = isRemote
2594
+ const [profiles, config] = isHosted
2365
2595
  ? [{ profiles: [] }, options.config ?? (await resolveConfig(undefined))]
2366
2596
  : await Promise.all([
2367
2597
  listProfiles(),
2368
2598
  options.config ?? resolveConfig(flagString(parsed, "profile")),
2369
2599
  ]);
2370
2600
  const discovery = options.discovery ?? resolveCommandDiscovery(config);
2371
- return agentContext(isRemote ? hostedCommands(commands, discovery) : commands, {
2601
+ return agentContext(isRemote
2602
+ ? hostedCommands(commands, discovery)
2603
+ : inApp
2604
+ ? inAppCommands(commands, discovery)
2605
+ : commands, {
2372
2606
  cliVersion: options.versions?.cliVersion ??
2373
- (isRemote ? "hosted" : await readCliVersion()),
2607
+ (isHosted ? "hosted" : await readCliVersion()),
2374
2608
  availableProfiles: profiles.profiles.map((profile) => profile.name),
2375
2609
  feedbackUpstreamConfigured: Boolean(process.env.RECESS_CLI_FEEDBACK_ENDPOINT),
2376
2610
  discovery,
@@ -2502,11 +2736,19 @@ export async function executeRecessCommand(argv, options = {}) {
2502
2736
  // that uses it. Sign-in/out commands manage the session themselves. Not
2503
2737
  // fatal here: an offline local command must still run, and an API call
2504
2738
  // that needs auth refreshes on its 401 and reports the real error.
2505
- if (!isRemote &&
2739
+ if (!isHosted &&
2506
2740
  !(noun === "auth" && verb !== "status") &&
2507
2741
  noun !== "setup") {
2508
2742
  await ensureFreshSession(config).catch(() => undefined);
2509
2743
  }
2744
+ if (noun === "doctor" && inApp) {
2745
+ return {
2746
+ transport: "in-app",
2747
+ authenticated: true,
2748
+ session: options.session ?? null,
2749
+ scope: options.discovery?.scope ?? null,
2750
+ };
2751
+ }
2510
2752
  if (noun === "doctor" && isRemote) {
2511
2753
  return {
2512
2754
  transport: "streamable-http-mcp",
@@ -3034,6 +3276,23 @@ export async function executeRecessCommand(argv, options = {}) {
3034
3276
  params: { query: { search: query, limit } },
3035
3277
  }));
3036
3278
  }
3279
+ if (noun === "users" && verb === "roster") {
3280
+ const role = assertChoice(flagString(parsed, "role") ?? "kid", ["kid", "guardian", "guide", "admin", "program", "moderator"], "--role");
3281
+ const limit = flagNumber(parsed, "limit") ?? 100;
3282
+ if (!Number.isInteger(limit) || limit < 1 || limit > 500) {
3283
+ throw new CliError("invalid_arguments", "--limit must be an integer from 1 through 500.");
3284
+ }
3285
+ const cursor = flagString(parsed, "cursor");
3286
+ return unwrap(await api.client.GET("/admin/users/roster", {
3287
+ params: {
3288
+ query: {
3289
+ role: role.toUpperCase(),
3290
+ limit,
3291
+ ...(cursor ? { cursor } : {}),
3292
+ },
3293
+ },
3294
+ }));
3295
+ }
3037
3296
  if (noun === "users" && verb === "tier") {
3038
3297
  const action = positional(parsed, 2, "users tier action");
3039
3298
  if (action === "list-tiers") {
@@ -3675,7 +3934,7 @@ export async function executeRecessCommand(argv, options = {}) {
3675
3934
  parsed,
3676
3935
  api,
3677
3936
  writeCommand,
3678
- transport: options.transport,
3937
+ transport: isRemote ? "remote" : "local",
3679
3938
  structuredInput: options.structuredInput,
3680
3939
  });
3681
3940
  }
@@ -4513,7 +4772,7 @@ export async function executeRecessCommand(argv, options = {}) {
4513
4772
  // infers whether `get` means guardian guidance or staff-only operations.
4514
4773
  const audience = assertChoice(verb, ["admin", "guardian"], "skill audience");
4515
4774
  const action = positional(parsed, 2, "skills action");
4516
- const refresh = isRemote || hasFlag(parsed, "refresh");
4775
+ const refresh = isHosted || hasFlag(parsed, "refresh");
4517
4776
  if (action === "list") {
4518
4777
  const query = flagString(parsed, "query");
4519
4778
  const category = flagString(parsed, "category");
@@ -4532,7 +4791,7 @@ export async function executeRecessCommand(argv, options = {}) {
4532
4791
  },
4533
4792
  },
4534
4793
  }));
4535
- if (!isRemote)
4794
+ if (!isHosted)
4536
4795
  await writeSkillCache(config.apiOrigin, cacheKey, data);
4537
4796
  return { ...data, cached: false };
4538
4797
  }
@@ -4558,7 +4817,7 @@ export async function executeRecessCommand(argv, options = {}) {
4558
4817
  },
4559
4818
  },
4560
4819
  }));
4561
- if (!isRemote)
4820
+ if (!isHosted)
4562
4821
  await writeSkillCache(config.apiOrigin, cacheKey, data);
4563
4822
  return { ...data, cached: false };
4564
4823
  }
@@ -5461,6 +5720,12 @@ export async function executeRecessCommand(argv, options = {}) {
5461
5720
  const answersFile = flagString(parsed, "answers-file");
5462
5721
  if (isRemote && answersFile)
5463
5722
  throw new CliError("remote_flag_unavailable", "--answers-file is not available over the hosted CLI; pass --student.");
5723
+ const optional = hasFlag(parsed, "optional");
5724
+ if (isRemote && optional)
5725
+ throw new CliError("remote_flag_unavailable", "--optional is not available over the hosted CLI.");
5726
+ if (optional) {
5727
+ await assertFullAdminSession(api, "goal-templates apply --optional");
5728
+ }
5464
5729
  const students = await resolveStudentList();
5465
5730
  if (!answersFile && students.length === 0) {
5466
5731
  throw new CliError("invalid_arguments", "Pass --student <kid-id-or-name> and/or --answers-file <path>. `goal-templates answers-template <id>` prints the answers shape.");
@@ -5481,10 +5746,16 @@ export async function executeRecessCommand(argv, options = {}) {
5481
5746
  // `--dry-run` is a read: it resolves the whole plan and writes nothing,
5482
5747
  // so it does not gate. Run it, read the per-student results, then confirm.
5483
5748
  if (hasFlag(parsed, "dry-run")) {
5484
- return unwrap(await api.client.POST("/ai/goal-templates/{id}/apply-workflow", {
5749
+ const planned = unwrap(await api.client.POST("/ai/goal-templates/{id}/apply-workflow", {
5485
5750
  params: { path: { id } },
5486
5751
  body: { answers, dryRun: true },
5487
5752
  }));
5753
+ return optional
5754
+ ? {
5755
+ ...planned,
5756
+ optional: "The real run makes each goal it creates optional, and reports any goal it names that is still Core.",
5757
+ }
5758
+ : planned;
5488
5759
  }
5489
5760
  // The real consequence — which students get which goals, which are
5490
5761
  // skipped as already-existing, and what coverage is missing — is only
@@ -5498,10 +5769,15 @@ export async function executeRecessCommand(argv, options = {}) {
5498
5769
  ...totals,
5499
5770
  [result.action]: (totals[result.action] ?? 0) + 1,
5500
5771
  }), {});
5772
+ const kids = optional
5773
+ ? await readKidGoals(api, preflight.results.map((result) => result.studentUserId))
5774
+ : new Map();
5501
5775
  const preview = {
5502
- action: "apply a goal template to students (creates goals and todos)",
5776
+ action: optional
5777
+ ? "apply a goal template to students as optional challenges (creates goals and todos)"
5778
+ : "apply a goal template to students (creates goals and todos)",
5503
5779
  target: { templateId: id, students: preflight.results.length },
5504
- request: { answers },
5780
+ request: { answers, ...(optional ? { optional: true } : {}) },
5505
5781
  details: {
5506
5782
  ...(students.some((student) => student.name)
5507
5783
  ? {
@@ -5519,20 +5795,45 @@ export async function executeRecessCommand(argv, options = {}) {
5519
5795
  goalTitle: result.goalTitle,
5520
5796
  todoTitle: result.todoTitle,
5521
5797
  warnings: result.warnings,
5798
+ ...(optional
5799
+ ? { placement: optionalPreviewPlacement(result, kids) }
5800
+ : {}),
5522
5801
  })),
5523
5802
  missingCoverage: preflight.missingCoverage,
5524
5803
  templateVersion: preflight.templateVersion,
5525
5804
  note: "Counts come from the backend's own dry run. `skipped_existing` items are idempotent — re-applying does not duplicate them.",
5805
+ ...(optional
5806
+ ? {
5807
+ optional: "Each goal this creates is set optional right after it is created, in this same operation. A goal already on the kid keeps its place; if it is Core, the run reports it with the command that makes it optional.",
5808
+ }
5809
+ : {}),
5526
5810
  },
5527
5811
  };
5528
- const apply = async () => unwrap(await api.client.POST("/ai/goal-templates/{id}/apply-workflow", {
5529
- params: { path: { id } },
5530
- body: {
5531
- answers,
5532
- dryRun: false,
5533
- expectedTemplateVersion: preflight.templateVersion,
5534
- },
5535
- }));
5812
+ const apply = async () => {
5813
+ const applied = unwrap(await api.client.POST("/ai/goal-templates/{id}/apply-workflow", {
5814
+ params: { path: { id } },
5815
+ body: {
5816
+ answers,
5817
+ dryRun: false,
5818
+ expectedTemplateVersion: preflight.templateVersion,
5819
+ },
5820
+ }));
5821
+ if (!optional)
5822
+ return applied;
5823
+ const results = await makeAppliedGoalsOptional(api, applied.results);
5824
+ const notOptional = results.flatMap((unit) => unit.optional.status === "failed"
5825
+ ? [{ unit, why: unit.optional.error, fix: unit.optional.fix }]
5826
+ : unit.optional.status === "still_core"
5827
+ ? [{ unit, why: unit.optional.reason, fix: unit.optional.fix }]
5828
+ : []);
5829
+ if (notOptional.length > 0) {
5830
+ throw new CliError("optional_not_set", `The apply finished, but ${notOptional.length} goal(s) are still Core, not optional. Do not apply again. Run each fix below; for a goal that was already on the kid, check first that it is not a guide's deliberate Core goal:\n${notOptional.map(({ unit, why, fix }) => `- ${fix} (${unit.studentName}, goal ${unit.goalId}: ${why})`).join("\n")}`, 1, {
5831
+ applied: { ...applied, results },
5832
+ notOptional: notOptional.map(({ unit }) => unit),
5833
+ });
5834
+ }
5835
+ return { ...applied, results };
5836
+ };
5536
5837
  // Hosted (Parent Rocky's power-parent lane): the operation store's
5537
5838
  // preview → confirm, not the local approval ledger.
5538
5839
  return isRemote
@@ -5777,6 +6078,67 @@ export async function executeRecessCommand(argv, options = {}) {
5777
6078
  params: { path: { goalId } },
5778
6079
  })));
5779
6080
  }
6081
+ if (verb === "set-required") {
6082
+ const student = await studentFlag(api, parsed, { required: true });
6083
+ const studentId = student.id;
6084
+ const goalId = flagString(parsed, "goal", { required: true });
6085
+ const placement = assertChoice(flagString(parsed, "value", { required: true }).trim().toLowerCase(), ["on", "off"], "--value");
6086
+ await assertFullAdminSession(api, "goals set-required");
6087
+ const [goals, detail] = await Promise.all([
6088
+ api.client
6089
+ .GET("/tutor/browser/students/{userId}/goals/", {
6090
+ params: { path: { userId: studentId } },
6091
+ })
6092
+ .then(unwrap),
6093
+ api.client
6094
+ .GET("/tutor/students/{studentId}", {
6095
+ params: { path: { studentId } },
6096
+ })
6097
+ .then(unwrap),
6098
+ ]);
6099
+ const current = goals.goals.find((goal) => goal.id === goalId);
6100
+ if (!current) {
6101
+ throw new CliError("not_found", `Goal ${goalId} was not found for student ${studentId}.`);
6102
+ }
6103
+ if (current.status === "COMPLETED") {
6104
+ throw new CliError("goal_not_open", `Goal ${goalId} ("${current.title}") is archived, so it has no place on the kid's day to change.`);
6105
+ }
6106
+ const target = GOAL_PLACEMENTS[placement];
6107
+ if (current.required === target.required) {
6108
+ throw new CliError(placement === "on" ? "already_core" : "already_optional", `Goal ${goalId} ("${current.title}") is already ${target.label}.`);
6109
+ }
6110
+ const kid = detail.student.firstName ?? student.name ?? "the kid";
6111
+ const preview = {
6112
+ action: `make ${kid}'s challenge "${current.title}" ${target.label}`,
6113
+ target: {
6114
+ goalId,
6115
+ studentUserId: studentId,
6116
+ title: current.title,
6117
+ status: current.status,
6118
+ required: current.required,
6119
+ },
6120
+ request: {
6121
+ required: target.required,
6122
+ delta: target.delta,
6123
+ expectedUpdatedAt: current.updatedAt,
6124
+ },
6125
+ details: {
6126
+ ...resolvedStudentDetails(student),
6127
+ consequence: target.consequence(kid),
6128
+ undo: setRequiredCommand(studentId, goalId, placement === "on" ? "off" : "on"),
6129
+ },
6130
+ };
6131
+ return previewBoundWrite(parsed, preview, async () => {
6132
+ const goal = await patchGoalPlacement(api, goalId, placement, current.updatedAt);
6133
+ return {
6134
+ goalId: goal.id,
6135
+ studentUserId: studentId,
6136
+ title: goal.title,
6137
+ required: goal.required,
6138
+ updatedAt: goal.updatedAt,
6139
+ };
6140
+ });
6141
+ }
5780
6142
  if (verb === "list") {
5781
6143
  const student = await studentFlag(api, parsed, { required: true });
5782
6144
  const userId = student.id;
@@ -6302,7 +6664,7 @@ export async function executeRecessCommand(argv, options = {}) {
6302
6664
  }
6303
6665
  throw new CliError("invalid_arguments", "Use goals queue get|set.");
6304
6666
  }
6305
- throw new CliError("invalid_arguments", "Use goals list|create|edit|delete|restore|archive|unarchive|complete|undo-completion|move-module|complete-module|launch-todo|queue|files|pdf|video.");
6667
+ throw new CliError("invalid_arguments", "Use goals list|create|edit|delete|restore|archive|unarchive|set-required|complete|undo-completion|move-module|complete-module|launch-todo|queue|files|pdf|video.");
6306
6668
  }
6307
6669
  if (noun === "channels") {
6308
6670
  return runChannelsCommand({ parsed, api, writeCommand });
@@ -6512,6 +6874,91 @@ export async function executeRecessCommand(argv, options = {}) {
6512
6874
  request: {},
6513
6875
  }, async () => unwrap(await api.client.POST("/admin/browser/students/{userId}/issued-email/", { params: { path: { userId: studentId } } })));
6514
6876
  }
6877
+ if (verb === "main-book") {
6878
+ const file = flagString(parsed, "file");
6879
+ if (file) {
6880
+ const { absolutePath, parsed: rows } = await readJsonValue(file, "Books file");
6881
+ if (!Array.isArray(rows) || rows.length === 0) {
6882
+ throw new CliError("invalid_arguments", `Books file must be a JSON array of { student, title, author?, libraryBookId?, goalId? } (${absolutePath}).`);
6883
+ }
6884
+ const books = [];
6885
+ for (const [index, row] of rows.entries()) {
6886
+ const entry = row && typeof row === "object" && !Array.isArray(row)
6887
+ ? row
6888
+ : {};
6889
+ const text = (key) => {
6890
+ const value = entry[key];
6891
+ return typeof value === "string" && value.trim()
6892
+ ? value.trim()
6893
+ : undefined;
6894
+ };
6895
+ const student = text("student");
6896
+ if (!student ||
6897
+ !(text("title") || text("libraryBookId") || text("goalId"))) {
6898
+ throw new CliError("invalid_arguments", `Row ${index + 1} needs a student and a title, libraryBookId or goalId (${absolutePath}).`);
6899
+ }
6900
+ books.push({
6901
+ kidId: (await resolveStudentReference(api, student)).id,
6902
+ student,
6903
+ title: text("title"),
6904
+ author: text("author"),
6905
+ libraryBookId: text("libraryBookId"),
6906
+ goalId: text("goalId"),
6907
+ });
6908
+ }
6909
+ return writeCommand(parsed, {
6910
+ action: "set the main book for several kids (each kid's current main book is marked finished)",
6911
+ target: { students: books.length },
6912
+ request: { books },
6913
+ details: {
6914
+ consequence: "Each kid's writing prompts draw on their new book from now on.",
6915
+ },
6916
+ }, async () => {
6917
+ const results = [];
6918
+ for (const { student, ...body } of books) {
6919
+ const res = await api.client.PUT("/ela/book", { body });
6920
+ results.push(res.data
6921
+ ? { student, ok: true, title: res.data.title }
6922
+ : {
6923
+ student,
6924
+ ok: false,
6925
+ error: res.error
6926
+ ?.message ?? `HTTP ${res.response.status}`,
6927
+ });
6928
+ }
6929
+ return {
6930
+ set: results.filter((result) => result.ok).length,
6931
+ failed: results.filter((result) => !result.ok).length,
6932
+ results,
6933
+ };
6934
+ });
6935
+ }
6936
+ const student = await studentFlag(api, parsed, { required: true });
6937
+ const title = flagString(parsed, "title");
6938
+ const author = flagString(parsed, "author");
6939
+ const libraryBookId = flagString(parsed, "library-book");
6940
+ const goalId = flagString(parsed, "goal");
6941
+ if (!title && !libraryBookId && !goalId) {
6942
+ return unwrap(await api.client.GET("/ela/book", {
6943
+ params: { query: { kidId: student.id } },
6944
+ }));
6945
+ }
6946
+ const body = {
6947
+ kidId: student.id,
6948
+ ...(title ? { title } : {}),
6949
+ ...(author ? { author } : {}),
6950
+ ...(libraryBookId ? { libraryBookId } : {}),
6951
+ ...(goalId ? { goalId } : {}),
6952
+ };
6953
+ return writeCommand(parsed, {
6954
+ action: "set a kid's main book (their current main book is marked finished)",
6955
+ target: { studentUserId: student.id },
6956
+ request: body,
6957
+ details: {
6958
+ consequence: "The kid's writing prompts draw on this book from now on.",
6959
+ },
6960
+ }, async () => unwrap(await api.client.PUT("/ela/book", { body })));
6961
+ }
6515
6962
  if (verb === "goblins") {
6516
6963
  const studentId = flagString(parsed, "student", { required: true });
6517
6964
  const search = flagString(parsed, "search");
@@ -6593,7 +7040,7 @@ export async function executeRecessCommand(argv, options = {}) {
6593
7040
  return { studentId, flashcardReviewEnabled: on };
6594
7041
  });
6595
7042
  }
6596
- throw new CliError("invalid_arguments", "Use students list|today|schedule|todos|analysis|xp-history|mastery|upload-map-scores|map-reports|issue-email|goblins|web-todos|flashcards.");
7043
+ throw new CliError("invalid_arguments", "Use students list|today|schedule|todos|analysis|xp-history|mastery|upload-map-scores|map-reports|issue-email|main-book|goblins|web-todos|flashcards.");
6597
7044
  }
6598
7045
  if (noun === "todos") {
6599
7046
  if (verb === "create") {