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.
package/dist/cli.js CHANGED
@@ -7,6 +7,7 @@ import { 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
9
  import { agentContext, buildCommandSchema, findCommandSchema, remoteCommands, scopedHelp, validateInvocation, } from "./command-schema.js";
10
+ import { runAdmissionsCommand } from "./commands/admissions.js";
10
11
  import { runApplicationsCommand } from "./commands/applications.js";
11
12
  import { runAppsCommand } from "./commands/apps.js";
12
13
  import { readAssignmentSelection, runGoalCurriculumCommand, } from "./commands/goal-curriculum.js";
@@ -18,6 +19,7 @@ import { runFeedCommand } from "./commands/feed.js";
18
19
  import { runFamiliesCommand } from "./commands/families.js";
19
20
  import { runStudentsTextsCommand, runUsersPhoneCommand, } from "./commands/phone-and-texts.js";
20
21
  import { runTuitionPlansCommand } from "./commands/tuition-plans.js";
22
+ import { runReportsCommand } from "./commands/reports.js";
21
23
  import { runMasteryCommand } from "./commands/mastery.js";
22
24
  import { runOnboardingCommand } from "./commands/onboarding.js";
23
25
  import { runScheduleCommand, runMemoryFilesCommand, } from "./commands/safe-staff-operations.js";
@@ -30,15 +32,99 @@ import { HELP } from "./help.js";
30
32
  export { HELP };
31
33
  import { cliRequestHeaders, noteServerCliVersions, requireCliRequestReason, } from "./http.js";
32
34
  import { runSelfUpdate, UPGRADE_COMMAND, updateNoticeText, updateStatus, } from "./update-notice.js";
33
- import { requireConfirmation } from "./safety.js";
35
+ import { requireConfirmation, resolveApprovalToken, } from "./safety.js";
34
36
  import { installSkill, isEphemeralInstall, readBundledSkillVersion, readCliVersion, } from "./setup.js";
35
37
  import { ensureFreshSession, revokeSession } from "./session-refresh.js";
36
38
  import { compareVersions, updateSkillFromServer } from "./skill-update.js";
37
39
  import { readSkillCache, writeSkillCache } from "./skills-cache.js";
38
40
  import { sanitizeWorkspaceUploadName } from "./upload-names.js";
39
41
  import { appendJobEvent, getJob, listJobs, pruneJobs } from "./jobs.js";
40
- function requiredRequestReason(parsed) {
41
- return requireCliRequestReason(flagString(parsed, "reason", { required: true }));
42
+ import { applyStudentsToAnswers, buildAnswersTemplate, buildGoalWorkspaceScaffold, resolveStudentReference, serverWorkspaceValidation, specValidationErrorLines, validateGoalWorkspaceLocally, } from "./goal-authoring.js";
43
+ const localInvocations = new WeakMap();
44
+ /** Never replayed from the ledger: they are what `recess confirm` supplies. */
45
+ const CONFIRMATION_FLAGS = new Set([
46
+ "confirm",
47
+ "operation-key",
48
+ "approval-token",
49
+ ]);
50
+ /** A stale approval is not an approval; preview again after this. */
51
+ const CONFIRM_REPLAY_TTL_MS = 24 * 60 * 60 * 1000;
52
+ function replayableArgv(argv) {
53
+ const kept = [];
54
+ for (let index = 0; index < argv.length; index += 1) {
55
+ const value = argv[index];
56
+ const name = value.startsWith("--") ? value.slice(2).split("=", 1)[0] : "";
57
+ if (!CONFIRMATION_FLAGS.has(name)) {
58
+ kept.push(value);
59
+ continue;
60
+ }
61
+ // `--name value` (not `--name=value`, not the boolean --confirm) also
62
+ // consumes the following token.
63
+ if (name !== "confirm" &&
64
+ !value.includes("=") &&
65
+ argv[index + 1] !== undefined &&
66
+ !argv[index + 1].startsWith("--")) {
67
+ index += 1;
68
+ }
69
+ }
70
+ return kept;
71
+ }
72
+ function replayFor(parsed) {
73
+ const invocation = localInvocations.get(parsed);
74
+ if (!invocation)
75
+ return undefined;
76
+ return {
77
+ argv: replayableArgv(invocation.argv),
78
+ cwd: process.cwd(),
79
+ ...(invocation.apiOrigin ? { apiOrigin: invocation.apiOrigin } : {}),
80
+ };
81
+ }
82
+ /**
83
+ * Server writes whose usage carries no --confirm (they execute directly), so
84
+ * the usage-based read classification below must not default their reason.
85
+ * `db query` is a read, but raw production SQL keeps a human-written purpose.
86
+ */
87
+ const EXPLICIT_REASON_COMMANDS = new Set([
88
+ "apps validate",
89
+ "apps publish",
90
+ "apps assign",
91
+ "apps primitives publish",
92
+ "db query",
93
+ ]);
94
+ function missingWriteReason(command) {
95
+ const path = command?.path.join(" ") ?? "<command>";
96
+ return new CliError("invalid_arguments", `Missing required --reason for \`recess ${path}\`. Writes record it in the audit log as the purpose a human approved (reads default it). Example: recess ${path} … --reason "<why, in one sentence>"`, 1, {
97
+ ...(command ? { usage: command.usage } : {}),
98
+ requiredFlag: "--reason",
99
+ example: `recess ${path} … --reason "<why, in one sentence>"`,
100
+ });
101
+ }
102
+ /**
103
+ * Every API call carries an audit reason. Reads (no --confirm in their usage)
104
+ * default it to `Read: <command path>`; writes must supply one, and fail here —
105
+ * before any network call — when they don't. Hosted transport keeps requiring
106
+ * it everywhere (recess-mcp audits it per call).
107
+ */
108
+ function resolveRequestReason(parsed, command, remote) {
109
+ const supplied = flagString(parsed, "reason", { required: remote });
110
+ if (supplied !== undefined)
111
+ return requireCliRequestReason(supplied);
112
+ const path = command?.path.join(" ");
113
+ const isWrite = !command ||
114
+ Boolean(command.flags.confirm) ||
115
+ EXPLICIT_REASON_COMMANDS.has(path);
116
+ if (isWrite)
117
+ throw missingWriteReason(command);
118
+ const invocation = localInvocations.get(parsed);
119
+ if (invocation)
120
+ invocation.reasonDefaulted = true;
121
+ return `Read: ${path}`;
122
+ }
123
+ /** Safety net for a write the usage-based classification read as a read. */
124
+ function assertExplicitWriteReason(parsed) {
125
+ if (localInvocations.get(parsed)?.reasonDefaulted) {
126
+ throw missingWriteReason(findCommandSchema(buildCommandSchema(HELP), parsed.positionals));
127
+ }
42
128
  }
43
129
  /**
44
130
  * Role of whoever this session belongs to.
@@ -252,17 +338,26 @@ async function skillStatus(config, reason) {
252
338
  };
253
339
  }
254
340
  }
255
- async function localWriteCommand(parsed, preview, execute) {
341
+ const CONFIRM_RETRY_HINT = "Rerun the unchanged command with --confirm --operation-key <operationKey>. Reuse that same key after an interrupted invocation. Previewing again is harmless: it mints another key that is equally valid, because keys are bound to the payload rather than to one preview run.";
342
+ function confirmNextHint(parsed, operationKey) {
343
+ return localInvocations.has(parsed)
344
+ ? { next: `recess confirm ${operationKey}` }
345
+ : {};
346
+ }
347
+ async function localWriteCommand(parsed, preview, execute, options = {}) {
348
+ assertExplicitWriteReason(parsed);
256
349
  const fingerprint = approvalTokenFor(preview);
257
- const suppliedOperationKey = flagString(parsed, "operation-key");
258
- if (!hasFlag(parsed, "confirm")) {
350
+ let suppliedOperationKey = flagString(parsed, "operation-key");
351
+ if (!hasFlag(parsed, "confirm") && !options.ungated) {
259
352
  const operationKey = operationKeyFor(fingerprint);
353
+ const replay = replayFor(parsed);
260
354
  const boundPreview = {
261
355
  ...preview,
262
356
  details: {
263
357
  ...preview.details,
264
358
  operationKey,
265
- retry: "Rerun the unchanged command with --confirm --operation-key <operationKey>. Reuse that same key after an interrupted invocation. Previewing again is harmless: it mints another key that is equally valid, because keys are bound to the payload rather than to one preview run.",
359
+ retry: CONFIRM_RETRY_HINT,
360
+ ...confirmNextHint(parsed, operationKey),
266
361
  },
267
362
  };
268
363
  await appendJobEvent({
@@ -277,9 +372,13 @@ async function localWriteCommand(parsed, preview, execute) {
277
372
  preview.request.zeroBalance === "true"
278
373
  ? { preview }
279
374
  : {}),
375
+ ...(replay ? { replay } : {}),
280
376
  });
281
377
  requireConfirmation(false, boundPreview);
282
378
  }
379
+ if (options.ungated && !suppliedOperationKey) {
380
+ suppliedOperationKey = operationKeyFor(fingerprint);
381
+ }
283
382
  if (!suppliedOperationKey) {
284
383
  throw new CliError("confirmation_required", "A confirmed write requires --operation-key. Run this exact command without --confirm, then pass the operationKey from the preview details. Any preview of this same payload yields a usable key.", 2, { preview, requiredFlag: "--operation-key" });
285
384
  }
@@ -523,6 +622,35 @@ async function readRemoteWorkspaceSnapshot(api, studentId, target) {
523
622
  },
524
623
  }));
525
624
  }
625
+ function draftNotEmptyError(input) {
626
+ return new CliError("draft_exists", `Draft ${input.draftSlug} already has ${input.fileCount} files. Check it out instead: recess goals files checkout --student ${input.studentId} --draft ${input.draftSlug} --output-dir ${input.outputDirectory}`, 1, { fileCount: input.fileCount });
627
+ }
628
+ /**
629
+ * `POST /workspace-files/init`: adopts an empty draft and, with `scaffold`,
630
+ * pushes the server's valid starter tree. Returns null when the server
631
+ * predates the route (a bare Fastify 404, no `code`) so the caller falls back
632
+ * to reading the draft and scaffolding locally.
633
+ */
634
+ async function initDraftWorkspace(api, input) {
635
+ const result = await api.client.POST("/tutor/browser/mesa/workspace-files/init", {
636
+ body: {
637
+ studentUserId: input.studentId,
638
+ draftSlug: input.draftSlug,
639
+ scaffold: input.scaffold,
640
+ ...(input.title === undefined ? {} : { title: input.title }),
641
+ },
642
+ });
643
+ const error = result.error;
644
+ if (result.response.status === 404 && error?.code !== "NOT_FOUND")
645
+ return null;
646
+ if (result.response.status === 409 && error?.code === "DRAFT_NOT_EMPTY") {
647
+ throw draftNotEmptyError({
648
+ ...input,
649
+ fileCount: typeof error.fileCount === "number" ? error.fileCount : 0,
650
+ });
651
+ }
652
+ return unwrap(result);
653
+ }
526
654
  async function assertCheckoutReadyForMaterialization(checkout) {
527
655
  const status = await runGit(checkout.root, ["status", "--porcelain=v1"]);
528
656
  if (status.trim()) {
@@ -636,20 +764,28 @@ function assertOperationKeyMatchesPreview(operationKey, fingerprint, preview) {
636
764
  });
637
765
  }
638
766
  }
639
- async function requirePreviewBoundConfirmation(parsed, preview, persistPreview = false) {
767
+ async function requirePreviewBoundConfirmation(parsed, preview, persistOrOptions = false) {
768
+ const options = typeof persistOrOptions === "boolean"
769
+ ? { persistPreview: persistOrOptions }
770
+ : persistOrOptions;
771
+ assertExplicitWriteReason(parsed);
640
772
  const approvalToken = approvalTokenFor(preview);
641
773
  const suppliedOperationKey = flagString(parsed, "operation-key");
774
+ const operationKey = suppliedOperationKey ?? operationKeyFor(approvalToken);
642
775
  const boundPreview = {
643
776
  ...preview,
644
777
  details: {
645
778
  ...preview.details,
646
779
  approvalToken,
647
- operationKey: suppliedOperationKey ?? operationKeyFor(approvalToken),
780
+ operationKey,
781
+ retry: CONFIRM_RETRY_HINT,
782
+ ...confirmNextHint(parsed, operationKey),
648
783
  },
649
784
  };
650
- if (!hasFlag(parsed, "confirm")) {
785
+ if (!hasFlag(parsed, "confirm") && !options.ungated) {
786
+ const replay = replayFor(parsed);
651
787
  await appendJobEvent({
652
- jobId: String(boundPreview.details.operationKey),
788
+ jobId: operationKey,
653
789
  status: "awaiting_confirmation",
654
790
  timestamp: new Date().toISOString(),
655
791
  action: preview.action,
@@ -657,27 +793,32 @@ async function requirePreviewBoundConfirmation(parsed, preview, persistPreview =
657
793
  target: preview.target,
658
794
  // Opted-in operations retain the approved receipt in the 0600 ledger so
659
795
  // retries can reach server idempotency after their own write changed state.
660
- ...(persistPreview ? { preview } : {}),
796
+ ...(options.persistPreview ? { preview } : {}),
797
+ ...(replay ? { replay } : {}),
661
798
  });
662
799
  requireConfirmation(false, boundPreview);
663
800
  }
664
- const supplied = flagString(parsed, "approval-token");
665
- if (supplied !== approvalToken) {
666
- throw new CliError("approval_mismatch", "The approved preview no longer matches this request. Review the current preview and rerun with --confirm --approval-token <token>.", 2, { preview: boundPreview, requiredFlag: "--approval-token" });
667
- }
668
- if (!suppliedOperationKey) {
801
+ if (!suppliedOperationKey && !options.ungated) {
669
802
  throw new CliError("confirmation_required", "A confirmed write requires --operation-key. Run this exact command without --confirm, then pass the operationKey from the preview details. Any preview of this same payload yields a usable key.", 2, { preview: boundPreview, requiredFlag: "--operation-key" });
670
803
  }
671
- assertOperationKeyMatchesPreview(suppliedOperationKey, approvalToken, boundPreview);
804
+ if (suppliedOperationKey) {
805
+ assertOperationKeyMatchesPreview(suppliedOperationKey, approvalToken, boundPreview);
806
+ }
807
+ // The approval token is the operation key's suffix; --approval-token is
808
+ // optional and, when given, must agree with the key.
809
+ const supplied = resolveApprovalToken(parsed);
810
+ if (!options.ungated && supplied !== approvalToken) {
811
+ throw new CliError("approval_mismatch", "The approved preview no longer matches this request. Review the current preview and rerun with --confirm --operation-key <operationKey>.", 2, { preview: boundPreview, requiredFlag: "--operation-key" });
812
+ }
672
813
  await appendJobEvent({
673
- jobId: suppliedOperationKey,
814
+ jobId: operationKey,
674
815
  status: "running",
675
816
  timestamp: new Date().toISOString(),
676
817
  action: preview.action,
677
818
  fingerprint: approvalToken,
678
819
  target: preview.target,
679
820
  });
680
- return { operationKey: suppliedOperationKey, fingerprint: approvalToken };
821
+ return { operationKey, fingerprint: approvalToken };
681
822
  }
682
823
  /**
683
824
  * A tutor template's `body` is the `## Subjects` block markdown (no `###`
@@ -717,8 +858,8 @@ async function readTutorTemplateLessons(directory) {
717
858
  }
718
859
  return lessons;
719
860
  }
720
- async function previewBoundWrite(parsed, preview, execute, persistPreview = false) {
721
- const context = await requirePreviewBoundConfirmation(parsed, preview, persistPreview);
861
+ async function previewBoundWrite(parsed, preview, execute, persistOrOptions = false) {
862
+ const context = await requirePreviewBoundConfirmation(parsed, preview, persistOrOptions);
722
863
  try {
723
864
  const result = await withIdempotencyContext(context, execute);
724
865
  await appendJobEvent({
@@ -767,12 +908,20 @@ async function readExecutedPreview(parsed) {
767
908
  const saved = receipt.preview;
768
909
  const fingerprint = approvalTokenFor(saved);
769
910
  if (receipt.fingerprint !== fingerprint ||
770
- flagString(parsed, "approval-token") !== fingerprint) {
911
+ resolveApprovalToken(parsed) !== fingerprint) {
771
912
  throw new CliError("approval_mismatch", "This operation key does not match the approved command. Retry the original command unchanged, or review a new preview.");
772
913
  }
773
914
  assertOperationKeyMatchesPreview(key, fingerprint, saved);
774
915
  return saved;
775
916
  }
917
+ /** `--confirm` names an operation key the local ledger shows already attempted. */
918
+ async function operationKeyAttempted(parsed) {
919
+ const key = flagString(parsed, "operation-key");
920
+ if (!hasFlag(parsed, "confirm") || !key)
921
+ return false;
922
+ const { history } = await getJob(key);
923
+ return history.some((event) => event.status !== "awaiting_confirmation");
924
+ }
776
925
  /** A retried write must retain its approved fence after changing its own source state. */
777
926
  async function recoverExecutedPreview(parsed, expected) {
778
927
  const saved = await readExecutedPreview(parsed);
@@ -785,6 +934,98 @@ async function recoverExecutedPreview(parsed, expected) {
785
934
  }
786
935
  return saved;
787
936
  }
937
+ function shellQuote(argv) {
938
+ return argv
939
+ .map((value) => /^[A-Za-z0-9_@%+=:,./-]+$/.test(value)
940
+ ? value
941
+ : `'${value.replaceAll("'", `'\\''`)}'`)
942
+ .join(" ");
943
+ }
944
+ /** Flags a confirmation may add on top of the stored command. */
945
+ const CONFIRM_PASSTHROUGH_FLAGS = [
946
+ "confirm-destructive-changes",
947
+ "destructive-change-token",
948
+ ];
949
+ /**
950
+ * `recess confirm <operation-key>`: replay the exact argv a preview stored in
951
+ * the local job ledger with `--confirm --operation-key <key>`. The replay
952
+ * rebuilds the preview and the write machinery refuses to execute unless its
953
+ * fingerprint still equals the key's suffix — the same guarantee as typing the
954
+ * full command again, without retyping it.
955
+ */
956
+ async function confirmStagedWrite(parsed, options) {
957
+ const operationKey = positional(parsed, 1, "operation key");
958
+ const fixed = ["reason", "profile", "operation-key", "approval-token"].find((name) => hasFlag(parsed, name));
959
+ if (fixed) {
960
+ throw new CliError("invalid_arguments", `recess confirm takes --${fixed} from the stored preview; pass only the operation key.`);
961
+ }
962
+ const { history } = await getJob(operationKey);
963
+ const staged = [...history]
964
+ .reverse()
965
+ .find((event) => event.status === "awaiting_confirmation" && event.replay);
966
+ if (!staged?.replay) {
967
+ throw new CliError("not_found", history.length === 0
968
+ ? `Unknown operation key ${operationKey}. Keys come from a write preview run on this machine: run the write without --confirm, then \`recess confirm\` the key it prints.`
969
+ : `Operation ${operationKey} has no stored command to replay (previewed by an older recess). Rerun the original command with --confirm --operation-key ${operationKey}.`, 1, { operationKey });
970
+ }
971
+ const command = `recess ${shellQuote(staged.replay.argv)}`;
972
+ const completed = [...history]
973
+ .reverse()
974
+ .find((event) => event.status === "completed");
975
+ if (completed) {
976
+ return {
977
+ operationKey,
978
+ alreadyCompleted: true,
979
+ completedAt: completed.timestamp,
980
+ result: completed.result,
981
+ };
982
+ }
983
+ if (Date.now() - Date.parse(staged.timestamp) > CONFIRM_REPLAY_TTL_MS) {
984
+ throw new CliError("confirmation_expired", `Operation ${operationKey} was previewed at ${staged.timestamp}, more than 24 hours ago. Preview it again, get approval on the fresh preview, then confirm the new key: ${command}`, 2, { operationKey, previewedAt: staged.timestamp, command });
985
+ }
986
+ if (!operationKey.endsWith(`_${staged.fingerprint}`)) {
987
+ throw new CliError("approval_mismatch", `Operation ${operationKey} was not minted for the payload stored under it. Preview again: ${command}`, 2, { operationKey, command });
988
+ }
989
+ const config = options.config ??
990
+ (await resolveConfig(flagString(parseArgs(staged.replay.argv), "profile")));
991
+ if (staged.replay.apiOrigin && staged.replay.apiOrigin !== config.apiOrigin) {
992
+ throw new CliError("confirmation_target_changed", `Operation ${operationKey} was previewed against ${staged.replay.apiOrigin}, but the active profile now points at ${config.apiOrigin}. Switch back (recess profile use …) or preview again against this API.`, 2, {
993
+ operationKey,
994
+ previewedApiOrigin: staged.replay.apiOrigin,
995
+ apiOrigin: config.apiOrigin,
996
+ });
997
+ }
998
+ if (process.cwd() !== staged.replay.cwd) {
999
+ try {
1000
+ // Relative --file/--source-dir paths resolve where the preview ran.
1001
+ process.chdir(staged.replay.cwd);
1002
+ }
1003
+ catch {
1004
+ throw new CliError("confirmation_target_changed", `Operation ${operationKey} was previewed in ${staged.replay.cwd}, which no longer exists. Preview again: ${command}`, 2, { operationKey, command });
1005
+ }
1006
+ }
1007
+ const passthrough = CONFIRM_PASSTHROUGH_FLAGS.flatMap((name) => {
1008
+ const value = parsed.flags.get(name);
1009
+ if (value === undefined)
1010
+ return [];
1011
+ return value === true ? [`--${name}`] : [`--${name}`, value];
1012
+ });
1013
+ try {
1014
+ return await executeRecessCommand([
1015
+ ...staged.replay.argv,
1016
+ ...passthrough,
1017
+ "--confirm",
1018
+ "--operation-key",
1019
+ operationKey,
1020
+ ], { ...options, config });
1021
+ }
1022
+ catch (error) {
1023
+ if (error instanceof CliError && error.code === "approval_mismatch") {
1024
+ throw new CliError("approval_mismatch", `Nothing was written: the command no longer produces the preview approved under ${operationKey} (a source file, a resolved value, or server state changed). Review a fresh preview: ${command}`, 2, error.details);
1025
+ }
1026
+ throw error;
1027
+ }
1028
+ }
788
1029
  async function cleanupPlannerUpload(api, conversationId, signed, includeDelete) {
789
1030
  if (signed.kind === "multipart") {
790
1031
  await api.client
@@ -1453,6 +1694,122 @@ function parseGoalTemplateDocument(doc) {
1453
1694
  : { outputTemplate: optionalDocString(doc, "outputTemplate") }),
1454
1695
  };
1455
1696
  }
1697
+ /**
1698
+ * Validate the WHOLE template document, not just its spec, so slug clashes and
1699
+ * title/emoji/coin limits surface here instead of after approval on create. A
1700
+ * server that predates whole-document checks strips the extra fields (its body
1701
+ * schema is non-strict) and still validates the spec. The server's structured
1702
+ * `{path, message}` errors and warnings print as `path: message` lines.
1703
+ * `specOnly` skips the document checks (slug availability included).
1704
+ */
1705
+ async function validateGoalTemplateDocument(api, document, options = {}) {
1706
+ const result = unwrap(await api.client.POST("/ai/goal-templates/validate-spec", {
1707
+ body: options.specOnly
1708
+ ? { setupWorkflowSpec: document.setupWorkflowSpec, kind: document.kind }
1709
+ : { ...document },
1710
+ }));
1711
+ // Older servers omit the warnings array; the line formatter tolerates that.
1712
+ const warnings = specValidationErrorLines({
1713
+ errors: result.warnings ?? [],
1714
+ });
1715
+ if (result.valid) {
1716
+ return { ...result, errors: specValidationErrorLines(result), warnings };
1717
+ }
1718
+ const errors = specValidationErrorLines(result);
1719
+ return {
1720
+ ...result,
1721
+ errors: errors.length ? errors : [result.error],
1722
+ warnings,
1723
+ };
1724
+ }
1725
+ /**
1726
+ * Bring a clean, fully pushed checkout up to the remote workspace tip as one
1727
+ * local commit, then advance its metadata. Capture writes lesson `Item key`
1728
+ * lines back into the source workspace; without this the next push from the
1729
+ * same checkout is refused as STALE_WORKSPACE.
1730
+ */
1731
+ async function syncCheckoutFromRemote(api, checkout) {
1732
+ const root = checkout.root;
1733
+ if ((await runGit(root, ["status", "--porcelain=v1"])).trim()) {
1734
+ throw new CliError("uncommitted_changes", "The checkout gained local changes during capture; its metadata was left unchanged.");
1735
+ }
1736
+ const { snapshot } = await readRemoteWorkspaceSnapshot(api, checkout.metadata.studentId, checkout.metadata.target);
1737
+ const remotePaths = new Set(snapshot.files.map((file) => file.path));
1738
+ const changedFiles = [];
1739
+ for (const file of snapshot.files) {
1740
+ const destination = resolveWorkspaceCheckoutPath(root, file.path);
1741
+ const bytes = Buffer.from(file.content, file.contentEncoding === "base64" ? "base64" : "utf8");
1742
+ if (createHash("sha256").update(bytes).digest("hex") !== file.sha256) {
1743
+ throw new CliError("invalid_workspace", `Mesa snapshot integrity check failed for ${file.path}.`);
1744
+ }
1745
+ const local = await fs.readFile(destination).catch(() => null);
1746
+ if (local && local.equals(bytes))
1747
+ continue;
1748
+ await fs.mkdir(path.dirname(destination), { recursive: true });
1749
+ await fs.writeFile(destination, bytes);
1750
+ changedFiles.push(file.path);
1751
+ }
1752
+ const tracked = (await runGit(root, ["ls-files", "-z"]))
1753
+ .split("\0")
1754
+ .filter(Boolean);
1755
+ const deletedFiles = tracked.filter((file) => !remotePaths.has(file));
1756
+ for (const file of deletedFiles) {
1757
+ await fs.rm(resolveWorkspaceCheckoutPath(root, file), { force: true });
1758
+ }
1759
+ if (changedFiles.length > 0 || deletedFiles.length > 0) {
1760
+ await runGit(root, ["add", "-A"]);
1761
+ await runGit(root, [
1762
+ "commit",
1763
+ "--quiet",
1764
+ "-m",
1765
+ `Sync Recess ${checkout.metadata.target.kind} workspace at ${snapshot.changeId}`,
1766
+ ], { identity: true });
1767
+ }
1768
+ const upstreamCommit = (await runGit(root, ["rev-parse", "HEAD"])).trim();
1769
+ await writeRecessGitMetadata(root, {
1770
+ ...checkout.metadata,
1771
+ changeId: snapshot.changeId,
1772
+ upstreamCommit,
1773
+ });
1774
+ return {
1775
+ directory: root,
1776
+ changeId: snapshot.changeId,
1777
+ upstreamCommit,
1778
+ changedFiles,
1779
+ deletedFiles,
1780
+ };
1781
+ }
1782
+ /** Every tracked file of a clean checkout, as text, for local validation. */
1783
+ async function readCheckoutTree(root) {
1784
+ const tracked = (await runGit(root, ["ls-files", "-z"]))
1785
+ .split("\0")
1786
+ .filter(Boolean);
1787
+ return Promise.all(tracked.map(async (file) => ({
1788
+ path: file,
1789
+ content: await fs.readFile(resolveWorkspaceCheckoutPath(root, file), "utf8"),
1790
+ })));
1791
+ }
1792
+ /**
1793
+ * The draft's validation verdict after this change: the server's when its dry
1794
+ * run reports one, else the local mirror over the resulting tree. Reported,
1795
+ * never enforced — a draft is work in progress; create/capture enforce.
1796
+ */
1797
+ async function draftWorkspaceValidation(preflight, resultingTree) {
1798
+ return (serverWorkspaceValidation(preflight) ??
1799
+ validateGoalWorkspaceLocally(await resultingTree()));
1800
+ }
1801
+ async function studentFlag(api, parsed, options = {}) {
1802
+ const value = flagString(parsed, "student", {
1803
+ required: options.required ?? false,
1804
+ });
1805
+ return value === undefined ? undefined : resolveStudentReference(api, value);
1806
+ }
1807
+ /** Preview details naming a student that was resolved from a name. */
1808
+ function resolvedStudentDetails(student) {
1809
+ return student?.name
1810
+ ? { resolvedStudent: { id: student.id, name: student.name } }
1811
+ : {};
1812
+ }
1456
1813
  /**
1457
1814
  * Resolve a template reference that may be a UUID or a slug. Slugs are what an
1458
1815
  * author types and what the skill's prose uses; the routes take a UUID only.
@@ -1482,16 +1839,29 @@ async function resolveGoalTemplateId(api, reference) {
1482
1839
  }
1483
1840
  return match.id;
1484
1841
  }
1485
- function requiredExpectedVersion(parsed) {
1842
+ /**
1843
+ * `--expected-version` is optional. When omitted, the template's current
1844
+ * version is read now and pinned into the preview, so the approval fingerprint
1845
+ * changes (and the confirm refuses) if the template moves between preview and
1846
+ * confirm. The flag still pins an older read explicitly.
1847
+ */
1848
+ async function resolveExpectedTemplateVersion(api, parsed, templateId, recovered) {
1486
1849
  const value = flagNumber(parsed, "expected-version");
1487
- if (value === undefined) {
1488
- throw new CliError("invalid_arguments", "Missing required --expected-version. Read it from `goal-templates get <id>` (the `version` field); a stale value 409s without writing.");
1850
+ if (value !== undefined) {
1851
+ if (!Number.isInteger(value) || value < 1) {
1852
+ throw new CliError("invalid_arguments", "--expected-version must be a positive integer.");
1853
+ }
1854
+ return { expectedVersion: value, pinnedFrom: "flag" };
1489
1855
  }
1490
- if (!Number.isInteger(value) || value < 1) {
1491
- throw new CliError("invalid_arguments", "--expected-version must be a positive integer.");
1856
+ if (recovered !== undefined) {
1857
+ return { expectedVersion: recovered, pinnedFrom: "current" };
1492
1858
  }
1493
- return value;
1859
+ const current = unwrap(await api.client.GET("/ai/goal-templates/{id}", {
1860
+ params: { path: { id: templateId } },
1861
+ }));
1862
+ return { expectedVersion: current.version, pinnedFrom: "current" };
1494
1863
  }
1864
+ const PINNED_VERSION_NOTE = "--expected-version was omitted, so the version read at preview is pinned: a template change before confirm changes this preview and the confirm is refused. Retrying after a landed write needs --expected-version <the previewed version>.";
1495
1865
  async function readMapScorePdf(filePath) {
1496
1866
  const absolutePath = path.resolve(filePath);
1497
1867
  if (path.extname(absolutePath).toLowerCase() !== ".pdf") {
@@ -1687,7 +2057,9 @@ function cliErrorShape(error) {
1687
2057
  };
1688
2058
  }
1689
2059
  function remoteWriteCommand(argv, structuredInput, store) {
1690
- return async (parsed, preview, execute) => {
2060
+ // Hosted writes stay gated even for WriteOptions.ungated: the hosted
2061
+ // operation store is the only replay channel there.
2062
+ return async (parsed, preview, execute, _options) => {
1691
2063
  const fingerprint = approvalTokenFor({
1692
2064
  ...preview,
1693
2065
  details: {
@@ -1737,6 +2109,9 @@ export async function executeRecessCommand(argv, options = {}) {
1737
2109
  const [noun, verb] = parsed.positionals;
1738
2110
  const commands = buildCommandSchema(HELP);
1739
2111
  const isRemote = options.transport === "remote";
2112
+ if (!isRemote && !options.operationStore) {
2113
+ localInvocations.set(parsed, { argv: [...argv] });
2114
+ }
1740
2115
  if (isRemote &&
1741
2116
  (!options.api || !options.config || !options.operationStore)) {
1742
2117
  throw new CliError("remote_context_required", "Hosted execution requires injected API, configuration, and operation-store adapters.");
@@ -1756,7 +2131,7 @@ export async function executeRecessCommand(argv, options = {}) {
1756
2131
  if (isRemote) {
1757
2132
  throw new CliError("remote_command_unavailable", "The version command is not exposed by the hosted Recess CLI.");
1758
2133
  }
1759
- const unknown = Array.from(parsed.flags.keys()).filter((name) => !["deliver", "json", "version"].includes(name));
2134
+ const unknown = Array.from(parsed.flags.keys()).filter((name) => !["deliver", "json", "no-json", "pretty", "version"].includes(name));
1760
2135
  if (unknown.length > 0) {
1761
2136
  throw new CliError("unknown_flag", `Unknown flag${unknown.length === 1 ? "" : "s"}: ${unknown
1762
2137
  .map((name) => `--${name}`)
@@ -1768,7 +2143,15 @@ export async function executeRecessCommand(argv, options = {}) {
1768
2143
  };
1769
2144
  }
1770
2145
  if (!noun) {
1771
- const unknown = Array.from(parsed.flags.keys()).filter((name) => !["deliver", "help", "json", "profile"].includes(name));
2146
+ const unknown = Array.from(parsed.flags.keys()).filter((name) => ![
2147
+ "all",
2148
+ "deliver",
2149
+ "help",
2150
+ "json",
2151
+ "no-json",
2152
+ "pretty",
2153
+ "profile",
2154
+ ].includes(name));
1772
2155
  if (unknown.length > 0) {
1773
2156
  throw new CliError("unknown_flag", `Unknown flag${unknown.length === 1 ? "" : "s"}: ${unknown
1774
2157
  .map((name) => `--${name}`)
@@ -1780,6 +2163,7 @@ export async function executeRecessCommand(argv, options = {}) {
1780
2163
  return {
1781
2164
  help: scopedHelp(HELP, visibleCommands, [], discovery, {
1782
2165
  remoteOnly: isRemote,
2166
+ all: hasFlag(parsed, "all"),
1783
2167
  }),
1784
2168
  };
1785
2169
  }
@@ -1791,6 +2175,7 @@ export async function executeRecessCommand(argv, options = {}) {
1791
2175
  return {
1792
2176
  help: scopedHelp(HELP, visibleCommands, scope, discovery, {
1793
2177
  remoteOnly: isRemote,
2178
+ all: hasFlag(parsed, "all"),
1794
2179
  }),
1795
2180
  };
1796
2181
  }
@@ -1838,6 +2223,9 @@ export async function executeRecessCommand(argv, options = {}) {
1838
2223
  feedbackUpstreamConfigured: Boolean(process.env.RECESS_CLI_FEEDBACK_ENDPOINT),
1839
2224
  discovery,
1840
2225
  remoteOnly: isRemote,
2226
+ scope: parsed.positionals.slice(1),
2227
+ full: hasFlag(parsed, "full"),
2228
+ help: HELP,
1841
2229
  });
1842
2230
  }
1843
2231
  if (noun === "profile") {
@@ -1912,6 +2300,12 @@ export async function executeRecessCommand(argv, options = {}) {
1912
2300
  return pruneJobs(olderThanDays);
1913
2301
  }
1914
2302
  }
2303
+ if (noun === "confirm") {
2304
+ if (isRemote) {
2305
+ throw new CliError("remote_command_unavailable", "Hosted writes confirm with the same command plus --confirm --operation-key.");
2306
+ }
2307
+ return confirmStagedWrite(parsed, options);
2308
+ }
1915
2309
  if (noun === "feedback") {
1916
2310
  if (verb === "list") {
1917
2311
  const limit = flagNumber(parsed, "limit") ?? 20;
@@ -1941,7 +2335,17 @@ export async function executeRecessCommand(argv, options = {}) {
1941
2335
  }));
1942
2336
  }
1943
2337
  }
2338
+ // Resolved before anything touches the network, so a write missing its
2339
+ // --reason fails without a session refresh or preview read.
2340
+ const requestReason = noun === "auth"
2341
+ ? undefined
2342
+ : noun === "update"
2343
+ ? requireCliRequestReason(flagString(parsed, "reason") ?? "check for a recess CLI update")
2344
+ : resolveRequestReason(parsed, findCommandSchema(commands, parsed.positionals), isRemote);
1944
2345
  const config = options.config ?? (await resolveConfig(flagString(parsed, "profile")));
2346
+ const invocation = localInvocations.get(parsed);
2347
+ if (invocation)
2348
+ invocation.apiOrigin = config.apiOrigin;
1945
2349
  // Renew a refreshable session's 15-minute access cookie before any command
1946
2350
  // that uses it. Sign-in/out commands manage the session themselves. Not
1947
2351
  // fatal here: an offline local command must still run, and an API call
@@ -1951,11 +2355,6 @@ export async function executeRecessCommand(argv, options = {}) {
1951
2355
  noun !== "setup") {
1952
2356
  await ensureFreshSession(config).catch(() => undefined);
1953
2357
  }
1954
- const requestReason = noun === "auth"
1955
- ? undefined
1956
- : noun === "update"
1957
- ? requireCliRequestReason(flagString(parsed, "reason") ?? "check for a recess CLI update")
1958
- : requiredRequestReason(parsed);
1959
2358
  if (noun === "doctor" && isRemote) {
1960
2359
  return {
1961
2360
  transport: "streamable-http-mcp",
@@ -2504,9 +2903,9 @@ export async function executeRecessCommand(argv, options = {}) {
2504
2903
  }
2505
2904
  const tierId = assertChoice(flagString(parsed, "tier", { required: true }), SCHOOL_TIER_IDS, "--tier");
2506
2905
  const proposedSlots = tierSlots(parsed);
2507
- const expectedUpdatedAt = action === "set"
2508
- ? flagString(parsed, "expected-updated-at", { required: true })
2509
- : undefined;
2906
+ // Optional: without it, the updatedAt read for this preview is pinned
2907
+ // into it, so a change before confirm alters the preview and is refused.
2908
+ const expectedUpdatedAt = action === "set" ? flagString(parsed, "expected-updated-at") : undefined;
2510
2909
  if (expectedUpdatedAt !== undefined &&
2511
2910
  Number.isNaN(Date.parse(expectedUpdatedAt))) {
2512
2911
  throw new CliError("invalid_arguments", "--expected-updated-at must be an ISO-8601 timestamp from users tier get.");
@@ -2544,7 +2943,7 @@ export async function executeRecessCommand(argv, options = {}) {
2544
2943
  const body = {
2545
2944
  tierId,
2546
2945
  ...(proposedSlots === undefined ? {} : { slotsPerKid: proposedSlots }),
2547
- expectedUpdatedAt: expectedUpdatedAt,
2946
+ expectedUpdatedAt: expectedUpdatedAt ?? state.updatedAt,
2548
2947
  allowStrand,
2549
2948
  };
2550
2949
  return writeCommand(parsed, {
@@ -2933,6 +3332,24 @@ export async function executeRecessCommand(argv, options = {}) {
2933
3332
  params: { path: { userId } },
2934
3333
  })));
2935
3334
  }
3335
+ if (noun === "students" && verb === "notes") {
3336
+ if (parsed.positionals[2] !== "add") {
3337
+ throw new CliError("invalid_arguments", "Use students notes add.");
3338
+ }
3339
+ const studentId = flagString(parsed, "student", { required: true });
3340
+ const content = flagString(parsed, "text", { required: true }).trim();
3341
+ if (!content) {
3342
+ throw new CliError("invalid_arguments", "--text must not be empty.");
3343
+ }
3344
+ return writeCommand(parsed, {
3345
+ action: "add a guide note to the kid's profile (staff-visible; Rocky reads it as guide context)",
3346
+ target: { studentUserId: studentId },
3347
+ request: { content },
3348
+ }, async () => unwrap(await api.client.POST("/tutor/students/{studentId}/notes", {
3349
+ params: { path: { studentId } },
3350
+ body: { content },
3351
+ })));
3352
+ }
2936
3353
  if (noun === "students" && verb === "upload-map-scores") {
2937
3354
  const studentId = flagString(parsed, "student", { required: true });
2938
3355
  const pdf = await readMapScorePdf(flagString(parsed, "file", { required: true }));
@@ -2979,6 +3396,9 @@ export async function executeRecessCommand(argv, options = {}) {
2979
3396
  if (noun === "applications" || noun === "quotes") {
2980
3397
  return runApplicationsCommand({ parsed, api, writeCommand });
2981
3398
  }
3399
+ if (noun === "admissions") {
3400
+ return runAdmissionsCommand({ parsed, api, writeCommand });
3401
+ }
2982
3402
  if (noun === "apps") {
2983
3403
  return runAppsCommand({
2984
3404
  parsed,
@@ -3041,7 +3461,9 @@ export async function executeRecessCommand(argv, options = {}) {
3041
3461
  const lineItem = flagString(parsed, "line-item", { required: true });
3042
3462
  const method = assertChoice(flagString(parsed, "method", { required: true }), ["refund", "credit", "tokens"], "--method");
3043
3463
  const whoPays = assertChoice(flagString(parsed, "who-pays") ?? "guide", ["guide", "recess"], "--who-pays");
3044
- const reason = flagString(parsed, "reason");
3464
+ // --refund-reason feeds the refund record; --reason (audit) is the
3465
+ // fallback only for older invocations.
3466
+ const reason = flagString(parsed, "refund-reason") ?? flagString(parsed, "reason");
3045
3467
  const amount = flagNumber(parsed, "amount-cents");
3046
3468
  const fullRefund = hasFlag(parsed, "full");
3047
3469
  if (method === "tokens" && (!amount || fullRefund)) {
@@ -3195,7 +3617,9 @@ export async function executeRecessCommand(argv, options = {}) {
3195
3617
  });
3196
3618
  const immediate = hasFlag(parsed, "immediate");
3197
3619
  const restore = hasFlag(parsed, "restore");
3198
- const reason = flagString(parsed, "reason");
3620
+ // --cancel-reason feeds the subscription record; --reason (audit) is the
3621
+ // fallback only for older invocations.
3622
+ const reason = flagString(parsed, "cancel-reason") ?? flagString(parsed, "reason");
3199
3623
  const body = {
3200
3624
  immediate,
3201
3625
  subscriptionId,
@@ -3279,7 +3703,10 @@ export async function executeRecessCommand(argv, options = {}) {
3279
3703
  const removalQuery = zeroBalance
3280
3704
  ? {
3281
3705
  zeroBalance: "true",
3282
- reason: flagString(parsed, "reason", { required: true }),
3706
+ // --zero-balance-reason feeds the payout record; --reason (audit)
3707
+ // is the fallback only for older invocations.
3708
+ reason: flagString(parsed, "zero-balance-reason") ??
3709
+ flagString(parsed, "reason", { required: true }),
3283
3710
  expectedBalanceCents,
3284
3711
  }
3285
3712
  : {};
@@ -3609,11 +4036,14 @@ export async function executeRecessCommand(argv, options = {}) {
3609
4036
  }
3610
4037
  if (noun === "events" && verb === "cancel") {
3611
4038
  const eventId = positional(parsed, 2, "event ID");
3612
- const reason = flagString(parsed, "reason", { required: true }).trim();
3613
- if (!reason) {
3614
- throw new CliError("invalid_arguments", "--reason must not be empty.");
3615
- }
3616
- const body = { reason };
4039
+ // Family-facing: the server posts this verbatim to the kids' and parents'
4040
+ // class chats, the class announcement, parent emails, and Slack. --reason
4041
+ // is only the audit-log note, so it is never reused here.
4042
+ const message = flagString(parsed, "message")?.trim();
4043
+ if (!message) {
4044
+ throw new CliError("invalid_arguments", 'events cancel requires --message TEXT: it is posted verbatim to kids, parents (chat + email), the class announcement, and Slack. --reason is only the audit-log note and is never sent to families. Example: recess events cancel <event-id> --message "Ms. Lee is out sick today; we will make this class up next week." --reason "Guide sick; ops approved cancel"', 1, { requiredFlag: "--message" });
4045
+ }
4046
+ const body = { reason: message };
3617
4047
  return writeCommand(parsed, {
3618
4048
  action: "cancel event AND NOTIFY: messages kid + parent channels, emails every registered parent, files credit-owed notes, posts to Slack",
3619
4049
  target: { eventId },
@@ -3978,15 +4408,16 @@ export async function executeRecessCommand(argv, options = {}) {
3978
4408
  if (verb === "validate-spec") {
3979
4409
  const document = parseGoalTemplateDocument(await readTemplateDocument());
3980
4410
  // A read-only validation: no gate, and iterating on it is the whole point.
4411
+ const validation = await validateGoalTemplateDocument(api, document);
3981
4412
  return {
3982
4413
  slug: document.slug,
3983
4414
  kind: document.kind,
3984
- ...unwrap(await api.client.POST("/ai/goal-templates/validate-spec", {
3985
- body: {
3986
- setupWorkflowSpec: document.setupWorkflowSpec,
3987
- kind: document.kind,
3988
- },
3989
- })),
4415
+ ...validation,
4416
+ ...(validation.valid && !("answersTemplate" in validation)
4417
+ ? {
4418
+ answersTemplate: buildAnswersTemplate(document.setupWorkflowSpec, []).answers,
4419
+ }
4420
+ : {}),
3990
4421
  };
3991
4422
  }
3992
4423
  if (verb === "create") {
@@ -4011,14 +4442,21 @@ export async function executeRecessCommand(argv, options = {}) {
4011
4442
  // answer keys `apply` will demand all come out of the spec's own
4012
4443
  // validation — a locally guessed preview could name a different handler
4013
4444
  // than the one that lands. Validation writes nothing.
4014
- const validation = unwrap(await api.client.POST("/ai/goal-templates/validate-spec", {
4015
- body: {
4016
- setupWorkflowSpec: document.setupWorkflowSpec,
4017
- kind: document.kind,
4018
- },
4019
- }));
4445
+ // A confirmed retry of a key that already ran may have created this very
4446
+ // template, and the document check would then call its own slug taken.
4447
+ // It validates the spec alone (the same preview details), so the keyed
4448
+ // create reaches server idempotency; the approval fingerprint still
4449
+ // refuses any changed input.
4450
+ const validation = await validateGoalTemplateDocument(api, document, {
4451
+ specOnly: await operationKeyAttempted(parsed),
4452
+ });
4020
4453
  if (!validation.valid) {
4021
- throw new CliError("invalid_spec", `The setupWorkflowSpec is invalid, so nothing was created: ${validation.error}`, 1, filePath ? { file: path.resolve(filePath) } : { input: "template" });
4454
+ throw new CliError("invalid_spec", `The template is invalid, so nothing was created:\n${validation.errors.join("\n")}`, 1, {
4455
+ ...(filePath
4456
+ ? { file: path.resolve(filePath) }
4457
+ : { input: "template" }),
4458
+ errors: validation.errors,
4459
+ });
4022
4460
  }
4023
4461
  return writeCommand(parsed, {
4024
4462
  action: "create a NEW global goal template (DETERMINISTIC_WORKFLOW — this cannot be converted back)",
@@ -4041,6 +4479,9 @@ export async function executeRecessCommand(argv, options = {}) {
4041
4479
  wizardStepKeys: validation.stepKeys,
4042
4480
  specSha256: validation.sha256,
4043
4481
  specInventory: validation.totals,
4482
+ answersTemplate: "answersTemplate" in validation
4483
+ ? validation.answersTemplate
4484
+ : buildAnswersTemplate(document.setupWorkflowSpec, []).answers,
4044
4485
  note: "Setup mode is DETERMINISTIC_WORKFLOW and is one-way: this template can never be converted back to a chat-driven setup.",
4045
4486
  },
4046
4487
  }, async () => {
@@ -4079,6 +4520,15 @@ export async function executeRecessCommand(argv, options = {}) {
4079
4520
  }
4080
4521
  if (target === undefined && minimum === undefined)
4081
4522
  throw new CliError("invalid_arguments", "Provide --target-modules or --required-modules N|all");
4523
+ // A retry after the policy write landed must reuse the approved
4524
+ // version, not the one that write just bumped it to.
4525
+ const executed = await readExecutedPreview(parsed);
4526
+ const executedVersion = executed?.action ===
4527
+ "edit shared goal-template assigned target or completion minimum" &&
4528
+ typeof executed.request.expectedVersion === "number"
4529
+ ? executed.request.expectedVersion
4530
+ : undefined;
4531
+ const { expectedVersion } = await resolveExpectedTemplateVersion(api, parsed, id, executedVersion);
4082
4532
  const body = {
4083
4533
  recipeKey: flagString(parsed, "recipe", { required: true }),
4084
4534
  ...(target === undefined ? {} : { targetModuleCount: Number(target) }),
@@ -4087,7 +4537,7 @@ export async function executeRecessCommand(argv, options = {}) {
4087
4537
  : {
4088
4538
  requiredModuleCount: minimum === "all" ? null : Number(minimum),
4089
4539
  }),
4090
- expectedVersion: requiredExpectedVersion(parsed),
4540
+ expectedVersion,
4091
4541
  };
4092
4542
  const requestPreview = {
4093
4543
  action: "edit shared goal-template assigned target or completion minimum",
@@ -4226,7 +4676,7 @@ export async function executeRecessCommand(argv, options = {}) {
4226
4676
  }
4227
4677
  if (verb === "patch-spec") {
4228
4678
  const id = await resolveGoalTemplateId(api, positional(parsed, 2, "template ID or slug"));
4229
- const expectedVersion = requiredExpectedVersion(parsed);
4679
+ const { expectedVersion, pinnedFrom } = await resolveExpectedTemplateVersion(api, parsed, id);
4230
4680
  const patchFile = await readGoalTemplateSpecPatches(flagString(parsed, "patches-file", { required: true }));
4231
4681
  // The server owns JSON Pointer semantics, strict final-spec validation,
4232
4682
  // protected-inventory counting, and the token binding the approved loss
@@ -4261,6 +4711,9 @@ export async function executeRecessCommand(argv, options = {}) {
4261
4711
  patches: patchFile.patches,
4262
4712
  },
4263
4713
  details: {
4714
+ ...(pinnedFrom === "current"
4715
+ ? { expectedVersionNote: PINNED_VERSION_NOTE }
4716
+ : {}),
4264
4717
  patchesApplied: preflight.patchesApplied,
4265
4718
  safety: preflight.preview,
4266
4719
  ...(preflight.preview.destructiveChanges
@@ -4301,7 +4754,7 @@ export async function executeRecessCommand(argv, options = {}) {
4301
4754
  }
4302
4755
  if (verb === "set-metadata") {
4303
4756
  const id = await resolveGoalTemplateId(api, positional(parsed, 2, "template ID or slug"));
4304
- const expectedVersion = requiredExpectedVersion(parsed);
4757
+ const { expectedVersion, pinnedFrom } = await resolveExpectedTemplateVersion(api, parsed, id);
4305
4758
  const agentInstructionsFile = flagString(parsed, "agent-instructions-file");
4306
4759
  const outputTemplateFile = flagString(parsed, "output-template-file");
4307
4760
  const tags = flagString(parsed, "tags");
@@ -4387,6 +4840,9 @@ export async function executeRecessCommand(argv, options = {}) {
4387
4840
  action: "update goal template metadata (never its setupWorkflowSpec)",
4388
4841
  target: { templateId: id, expectedVersion },
4389
4842
  request: body,
4843
+ ...(pinnedFrom === "current"
4844
+ ? { details: { expectedVersionNote: PINNED_VERSION_NOTE } }
4845
+ : {}),
4390
4846
  }, async () => unwrap(await api.client.PUT("/ai/goal-templates/{id}", {
4391
4847
  params: { path: { id } },
4392
4848
  body,
@@ -4416,13 +4872,14 @@ export async function executeRecessCommand(argv, options = {}) {
4416
4872
  }
4417
4873
  if (verb === "delete") {
4418
4874
  const id = await resolveGoalTemplateId(api, positional(parsed, 2, "template ID or slug"));
4419
- const expectedVersion = requiredExpectedVersion(parsed);
4420
4875
  // Read the current version so the gate refuses a stale delete locally,
4421
4876
  // and so the preview names the template a human is being asked to approve
4422
- // rather than only its UUID.
4877
+ // rather than only its UUID. Without --expected-version the version read
4878
+ // here is pinned into the preview instead.
4423
4879
  const current = unwrap(await api.client.GET("/ai/goal-templates/{id}", {
4424
4880
  params: { path: { id } },
4425
4881
  }));
4882
+ const { expectedVersion } = await resolveExpectedTemplateVersion(api, parsed, id, current.version);
4426
4883
  if (current.version !== expectedVersion) {
4427
4884
  throw new CliError("stale_write", `Goal template is at version ${current.version}, not ${expectedVersion}. Re-read it before deleting; nothing was deleted.`, 1, { templateId: id, currentVersion: current.version });
4428
4885
  }
@@ -4469,14 +4926,17 @@ export async function executeRecessCommand(argv, options = {}) {
4469
4926
  const checkoutHead = checkout
4470
4927
  ? await assertCheckoutReadyForMaterialization(checkout)
4471
4928
  : null;
4472
- const requestedSourceStudentId = flagString(parsed, "student");
4929
+ const requestedSourceStudent = await studentFlag(api, parsed, {
4930
+ required: Boolean(sourceDraft),
4931
+ });
4932
+ const requestedSourceStudentId = requestedSourceStudent?.id;
4473
4933
  if (checkout &&
4474
4934
  requestedSourceStudentId &&
4475
4935
  requestedSourceStudentId !== checkout.metadata.studentId) {
4476
4936
  throw new CliError("invalid_arguments", `--student ${requestedSourceStudentId} does not match checkout owner ${checkout.metadata.studentId}.`);
4477
4937
  }
4478
4938
  const sourceStudentUserId = sourceDraft
4479
- ? flagString(parsed, "student", { required: true })
4939
+ ? requestedSourceStudentId
4480
4940
  : checkout?.metadata.studentId;
4481
4941
  let source;
4482
4942
  if (sourceGoalId) {
@@ -4537,19 +4997,95 @@ export async function executeRecessCommand(argv, options = {}) {
4537
4997
  note: "The confirmed request is fenced to both this template version and this exact source revision. Capturing bumps the template version unless the snapshot is unchanged.",
4538
4998
  },
4539
4999
  };
4540
- return previewBoundWrite(parsed, preview, async () => unwrap(await api.client.POST("/ai/goal-templates/{id}/snapshot/capture", {
4541
- params: { path: { id } },
4542
- body: {
4543
- ...source,
4544
- dryRun: false,
4545
- expectedTemplateVersion: preflight.template.version,
4546
- expectedSourceChangeId: preflight.source.changeId,
4547
- },
4548
- })));
5000
+ return previewBoundWrite(parsed, preview, async () => {
5001
+ const result = unwrap(await api.client.POST("/ai/goal-templates/{id}/snapshot/capture", {
5002
+ params: { path: { id } },
5003
+ body: {
5004
+ ...source,
5005
+ dryRun: false,
5006
+ expectedTemplateVersion: preflight.template.version,
5007
+ expectedSourceChangeId: preflight.source.changeId,
5008
+ },
5009
+ }));
5010
+ const sourceChangeId = "sourceChangeId" in result &&
5011
+ typeof result.sourceChangeId === "string"
5012
+ ? result.sourceChangeId
5013
+ : null;
5014
+ if (!checkout ||
5015
+ !sourceChangeId ||
5016
+ sourceChangeId === checkout.metadata.changeId) {
5017
+ return result;
5018
+ }
5019
+ // Capture committed lesson identities back to the source workspace.
5020
+ // Pull them so the checkout can keep pushing.
5021
+ try {
5022
+ return {
5023
+ ...result,
5024
+ local: {
5025
+ synced: true,
5026
+ ...(await syncCheckoutFromRemote(api, checkout)),
5027
+ },
5028
+ };
5029
+ }
5030
+ catch (error) {
5031
+ return {
5032
+ ...result,
5033
+ local: {
5034
+ synced: false,
5035
+ directory: checkout.root,
5036
+ error: error instanceof Error ? error.message : String(error),
5037
+ next: "Capture changed the source workspace. Check it out again (goals files checkout) before the next push.",
5038
+ },
5039
+ };
5040
+ }
5041
+ });
5042
+ }
5043
+ // `--student` takes IDs or exact roster names, comma-separated.
5044
+ const resolveStudentList = async () => Promise.all((flagString(parsed, "student") ?? "")
5045
+ .split(",")
5046
+ .map((value) => value.trim())
5047
+ .filter(Boolean)
5048
+ .map((value) => resolveStudentReference(api, value)));
5049
+ if (verb === "answers-template") {
5050
+ const id = await resolveGoalTemplateId(api, positional(parsed, 2, "template ID or slug"));
5051
+ const [template, students] = await Promise.all([
5052
+ api.client.GET("/ai/goal-templates/{id}", { params: { path: { id } } }),
5053
+ resolveStudentList(),
5054
+ ]);
5055
+ const current = unwrap(template);
5056
+ const skeleton = buildAnswersTemplate(current.setupWorkflowSpec, students.map((student) => student.id));
5057
+ return {
5058
+ templateId: current.id,
5059
+ slug: current.slug,
5060
+ version: current.version,
5061
+ answers: skeleton.answers,
5062
+ placeholders: skeleton.placeholders,
5063
+ steps: skeleton.steps,
5064
+ next: skeleton.placeholders.length > 0
5065
+ ? `Choose real values for ${skeleton.placeholders.join(", ")} (see steps[].options), save the answers to a file, then run goal-templates apply ${current.slug} --answers-file <file> --dry-run.`
5066
+ : `Save the answers to a file, or run goal-templates apply ${current.slug} --student <kid> --dry-run directly.`,
5067
+ };
4549
5068
  }
4550
5069
  if (verb === "apply") {
4551
5070
  const id = await resolveGoalTemplateId(api, positional(parsed, 2, "template ID or slug"));
4552
- const answers = await readJsonFile(flagString(parsed, "answers-file", { required: true }), "Answers file");
5071
+ const answersFile = flagString(parsed, "answers-file");
5072
+ const students = await resolveStudentList();
5073
+ if (!answersFile && students.length === 0) {
5074
+ 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.");
5075
+ }
5076
+ let answers = answersFile
5077
+ ? await readJsonFile(answersFile, "Answers file")
5078
+ : {};
5079
+ if (students.length > 0) {
5080
+ const template = unwrap(await api.client.GET("/ai/goal-templates/{id}", {
5081
+ params: { path: { id } },
5082
+ }));
5083
+ const filled = applyStudentsToAnswers(template.setupWorkflowSpec, answers, students.map((student) => student.id));
5084
+ if (filled.missingRequired.length > 0) {
5085
+ throw new CliError("invalid_arguments", `The template's wizard also requires ${filled.missingRequired.join(", ")}. Run \`recess goal-templates answers-template ${id} --student <kid>\`, fill those values in a file, and pass it with --answers-file.`, 1, { missingAnswers: filled.missingRequired });
5086
+ }
5087
+ answers = filled.answers;
5088
+ }
4553
5089
  // `--dry-run` is a read: it resolves the whole plan and writes nothing,
4554
5090
  // so it does not gate. Run it, read the per-student results, then confirm.
4555
5091
  if (hasFlag(parsed, "dry-run")) {
@@ -4575,6 +5111,14 @@ export async function executeRecessCommand(argv, options = {}) {
4575
5111
  target: { templateId: id, students: preflight.results.length },
4576
5112
  request: { answers },
4577
5113
  details: {
5114
+ ...(students.some((student) => student.name)
5115
+ ? {
5116
+ resolvedStudents: students.map(({ id, name }) => ({
5117
+ id,
5118
+ name,
5119
+ })),
5120
+ }
5121
+ : {}),
4578
5122
  counts,
4579
5123
  results: preflight.results.map((result) => ({
4580
5124
  student: result.studentName,
@@ -4600,7 +5144,8 @@ export async function executeRecessCommand(argv, options = {}) {
4600
5144
  }
4601
5145
  if (verb === "apply-starter") {
4602
5146
  const id = await resolveGoalTemplateId(api, positional(parsed, 2, "template ID or slug"));
4603
- const studentUserId = flagString(parsed, "student", { required: true });
5147
+ const student = await studentFlag(api, parsed, { required: true });
5148
+ const studentUserId = student.id;
4604
5149
  const answersFile = flagString(parsed, "answers-file");
4605
5150
  const answers = answersFile
4606
5151
  ? await readJsonFile(answersFile, "Answers file")
@@ -4613,6 +5158,7 @@ export async function executeRecessCommand(argv, options = {}) {
4613
5158
  target: { templateId: id, studentUserId },
4614
5159
  request: { answers },
4615
5160
  details: {
5161
+ ...resolvedStudentDetails(student),
4616
5162
  note: "Gated behind the school-onboarding-v1 flag for the acting admin; a 404 means the flag is off, not that the template is missing. Prefer `goal-templates apply --dry-run` when the template supports it.",
4617
5163
  },
4618
5164
  }, async () => unwrap(await api.client.POST("/ai/goal-templates/{id}/apply-starter", {
@@ -4620,11 +5166,12 @@ export async function executeRecessCommand(argv, options = {}) {
4620
5166
  body: { studentUserId, answers },
4621
5167
  })));
4622
5168
  }
4623
- throw new CliError("invalid_arguments", "Use goal-templates list|get|versions|validate-spec|create|patch-spec|set-metadata|generate-image|delete|snapshot-files|capture-snapshot|apply|apply-starter.");
5169
+ throw new CliError("invalid_arguments", "Use goal-templates list|get|versions|validate-spec|create|patch-spec|set-metadata|generate-image|delete|snapshot-files|capture-snapshot|answers-template|apply|apply-starter.");
4624
5170
  }
4625
5171
  if (noun === "goals" && verb === "adaptations") {
4626
5172
  const action = positional(parsed, 2, "goals adaptations action");
4627
- const studentId = flagString(parsed, "student", { required: true });
5173
+ const student = await studentFlag(api, parsed, { required: true });
5174
+ const studentId = student.id;
4628
5175
  const goalId = flagString(parsed, "goal", { required: true });
4629
5176
  if (action === "list") {
4630
5177
  return unwrap(await api.client.GET("/tutor/students/{studentId}/goals/{goalId}/adaptations", { params: { path: { studentId, goalId } } }));
@@ -4669,7 +5216,8 @@ export async function executeRecessCommand(argv, options = {}) {
4669
5216
  }
4670
5217
  if (verb === "archive" || verb === "unarchive") {
4671
5218
  const goalId = positional(parsed, 2, "goal ID");
4672
- const studentId = flagString(parsed, "student", { required: true });
5219
+ const student = await studentFlag(api, parsed, { required: true });
5220
+ const studentId = student.id;
4673
5221
  const reopen = verb === "unarchive";
4674
5222
  const current = unwrap(await api.client.GET("/tutor/browser/students/{userId}/goals/", {
4675
5223
  params: { path: { userId: studentId } },
@@ -4699,6 +5247,7 @@ export async function executeRecessCommand(argv, options = {}) {
4699
5247
  },
4700
5248
  request: { goalId },
4701
5249
  details: {
5250
+ ...resolvedStudentDetails(student),
4702
5251
  note: reopen
4703
5252
  ? "Returns the goal to ACTIVE so it generates daily todos again. Refused with GOAL_LIMIT_REACHED if the kid is already at the open-goal cap, and refused for goals completed through the staff reward path (those need `goals undo-completion`, which reverses the coins)."
4704
5253
  : "Sets the terminal COMPLETED status. Grants no coins and posts no activity — use `goals complete` (staff only) when the kid should receive the goal's reward. The goal, its history, and its past todos all stay; only the open-goal slot is released. Any already-scheduled future todos on this goal are left alone, matching `goals complete`.",
@@ -4713,7 +5262,8 @@ export async function executeRecessCommand(argv, options = {}) {
4713
5262
  })));
4714
5263
  }
4715
5264
  if (verb === "list") {
4716
- const userId = flagString(parsed, "student", { required: true });
5265
+ const student = await studentFlag(api, parsed, { required: true });
5266
+ const userId = student.id;
4717
5267
  const result = unwrap(await api.client.GET("/tutor/browser/students/{userId}/goals/", {
4718
5268
  params: { path: { userId } },
4719
5269
  }));
@@ -4736,7 +5286,8 @@ export async function executeRecessCommand(argv, options = {}) {
4736
5286
  // no retiring the work they have already done, nobody else's goal touched.
4737
5287
  if (verb === "move-module") {
4738
5288
  const moduleRef = positional(parsed, 2, "module ref (e.g. Q006)");
4739
- const studentId = flagString(parsed, "student", { required: true });
5289
+ const student = await studentFlag(api, parsed, { required: true });
5290
+ const studentId = student.id;
4740
5291
  const goalId = flagString(parsed, "goal", { required: true });
4741
5292
  const toEnd = hasFlag(parsed, "to-end");
4742
5293
  const position = flagNumber(parsed, "position");
@@ -4774,6 +5325,7 @@ export async function executeRecessCommand(argv, options = {}) {
4774
5325
  },
4775
5326
  request: { moduleId: target.id, ordinal },
4776
5327
  details: {
5328
+ ...resolvedStudentDetails(student),
4777
5329
  note: "Affects only this student's copy of the curriculum — the goal template and every other kid on it are untouched. Completion state is preserved: an unfinished lesson stays unfinished and is simply served later.",
4778
5330
  ...(collision
4779
5331
  ? {
@@ -4789,8 +5341,45 @@ export async function executeRecessCommand(argv, options = {}) {
4789
5341
  body: { ordinal },
4790
5342
  })));
4791
5343
  }
5344
+ // A module added to a live goal otherwise waits for the next daily run:
5345
+ // that run reuses any launch todo already dated today for the goal.
5346
+ if (verb === "launch-todo") {
5347
+ const goalId = positional(parsed, 2, "goal id");
5348
+ const student = await studentFlag(api, parsed, { required: true });
5349
+ const studentId = student.id;
5350
+ const moduleRef = flagString(parsed, "module");
5351
+ const dueDate = flagString(parsed, "due-date");
5352
+ if (dueDate && !/^\d{4}-\d{2}-\d{2}$/.test(dueDate)) {
5353
+ throw new CliError("invalid_arguments", "--due-date must be YYYY-MM-DD (the kid's local date).");
5354
+ }
5355
+ const preview = {
5356
+ action: "create a goal module's todo now",
5357
+ target: {
5358
+ studentUserId: studentId,
5359
+ goalId,
5360
+ moduleRef: moduleRef ?? "current module (first unfinished)",
5361
+ dueDate: dueDate ?? "today in the kid's timezone",
5362
+ },
5363
+ request: {
5364
+ ...(moduleRef ? { moduleRef } : {}),
5365
+ ...(dueDate ? { dueDate } : {}),
5366
+ },
5367
+ details: {
5368
+ ...resolvedStudentDetails(student),
5369
+ note: "Idempotent: if this module already has a todo for that date, it is returned instead of a second one.",
5370
+ },
5371
+ };
5372
+ return previewBoundWrite(parsed, preview, async () => unwrap(await api.client.POST("/tutor/students/{studentId}/goals/{goalId}/launch-todo", {
5373
+ params: { path: { studentId, goalId } },
5374
+ body: {
5375
+ ...(moduleRef ? { moduleRef } : {}),
5376
+ ...(dueDate ? { dueDate } : {}),
5377
+ },
5378
+ })));
5379
+ }
4792
5380
  if (verb === "create") {
4793
- const requestedStudentId = flagString(parsed, "student");
5381
+ const requestedStudent = await studentFlag(api, parsed);
5382
+ const requestedStudentId = requestedStudent?.id;
4794
5383
  const sourceDirectory = flagString(parsed, "source-dir");
4795
5384
  const explicitDraftSlug = flagString(parsed, "draft");
4796
5385
  if (sourceDirectory && explicitDraftSlug) {
@@ -4882,6 +5471,7 @@ export async function executeRecessCommand(argv, options = {}) {
4882
5471
  : {}),
4883
5472
  },
4884
5473
  details: {
5474
+ ...resolvedStudentDetails(requestedStudent),
4885
5475
  currentChangeId: preflight.currentChangeId,
4886
5476
  workspaceSha256: preflight.workspaceSha256,
4887
5477
  fileCount: preflight.fileCount,
@@ -4939,6 +5529,7 @@ export async function executeRecessCommand(argv, options = {}) {
4939
5529
  schedule: schedule ?? null,
4940
5530
  },
4941
5531
  details: {
5532
+ ...resolvedStudentDetails(requestedStudent),
4942
5533
  note: "Creates a description-only goal with no modules or course workspace. Pass a draft checkout with --source-dir to create a personal module-backed goal. A 409 GOAL_LIMIT_REACHED means the kid is at capacity and nothing was created.",
4943
5534
  },
4944
5535
  }, async () => unwrap(await api.client.POST("/tutor/browser/students/{userId}/goals/", {
@@ -4948,7 +5539,8 @@ export async function executeRecessCommand(argv, options = {}) {
4948
5539
  }
4949
5540
  if (verb === "edit") {
4950
5541
  const goalId = positional(parsed, 2, "goal ID");
4951
- const studentId = flagString(parsed, "student", { required: true });
5542
+ const student = await studentFlag(api, parsed, { required: true });
5543
+ const studentId = student.id;
4952
5544
  const patchFile = flagString(parsed, "patch-file", { required: true });
4953
5545
  const patch = (await readJsonFile(patchFile, "Goal patch file"));
4954
5546
  assertGoalPatchValues(patch, patchFile);
@@ -4968,6 +5560,7 @@ export async function executeRecessCommand(argv, options = {}) {
4968
5560
  expectedUpdatedAt: current.updatedAt,
4969
5561
  patch,
4970
5562
  },
5563
+ details: resolvedStudentDetails(student),
4971
5564
  };
4972
5565
  return previewBoundWrite(parsed, preview, async () => unwrap(await api.client.PATCH("/tutor/browser/students/goals/{goalId}/", {
4973
5566
  params: { path: { goalId } },
@@ -4976,7 +5569,8 @@ export async function executeRecessCommand(argv, options = {}) {
4976
5569
  }
4977
5570
  if (verb === "delete") {
4978
5571
  const goalId = positional(parsed, 2, "goal ID");
4979
- const studentId = flagString(parsed, "student", { required: true });
5572
+ const student = await studentFlag(api, parsed, { required: true });
5573
+ const studentId = student.id;
4980
5574
  // Deletion is an /admin/* route, so a guardian or guide session can never
4981
5575
  // complete it. Refuse here, before the preview, rather than rendering a
4982
5576
  // full and entirely plausible preview — resolved goal, named title,
@@ -5002,6 +5596,7 @@ export async function executeRecessCommand(argv, options = {}) {
5002
5596
  },
5003
5597
  request: { expectedUpdatedAt: current.updatedAt },
5004
5598
  details: {
5599
+ ...resolvedStudentDetails(student),
5005
5600
  note: "Soft-deletes the goal and its current/future dated todos. Historical todos, the deletion audit, and any Mesa workspace remain available; `goals restore` reverses this tombstone.",
5006
5601
  },
5007
5602
  };
@@ -5014,7 +5609,8 @@ export async function executeRecessCommand(argv, options = {}) {
5014
5609
  }
5015
5610
  if (verb === "restore") {
5016
5611
  const goalId = positional(parsed, 2, "goal ID");
5017
- const studentId = flagString(parsed, "student", { required: true });
5612
+ const student = await studentFlag(api, parsed, { required: true });
5613
+ const studentId = student.id;
5018
5614
  const sessionRole = await resolveSessionRole(api);
5019
5615
  if (sessionRole && sessionRole !== "ADMIN") {
5020
5616
  throw new CliError("forbidden", "Restoring a deleted goal is admin-only.", 1, { sessionRole, requiredRole: "ADMIN" });
@@ -5040,6 +5636,7 @@ export async function executeRecessCommand(argv, options = {}) {
5040
5636
  },
5041
5637
  request: body,
5042
5638
  details: {
5639
+ ...resolvedStudentDetails(student),
5043
5640
  note: "Clears the goal tombstone and restores only linked todos that were tombstoned by the same goal deletion. Restoring an ACTIVE or PAUSED goal rechecks the student's open-goal capacity.",
5044
5641
  },
5045
5642
  };
@@ -5048,7 +5645,8 @@ export async function executeRecessCommand(argv, options = {}) {
5048
5645
  if (verb === "queue") {
5049
5646
  const subverb = positional(parsed, 2, "queue action (get|set)");
5050
5647
  const goalId = positional(parsed, 3, "goal ID");
5051
- const studentId = flagString(parsed, "student", { required: true });
5648
+ const student = await studentFlag(api, parsed, { required: true });
5649
+ const studentId = student.id;
5052
5650
  if (subverb === "get") {
5053
5651
  return unwrap(await api.client.GET("/tutor/browser/students/goals/{goalId}/queue/", { params: { path: { goalId } } }));
5054
5652
  }
@@ -5101,6 +5699,7 @@ export async function executeRecessCommand(argv, options = {}) {
5101
5699
  unchangedTitleForConcurrencyFence: goal.title,
5102
5700
  },
5103
5701
  details: {
5702
+ ...resolvedStudentDetails(student),
5104
5703
  currentQueue: current.queue.map((item) => ({
5105
5704
  moduleRef: item.moduleRef,
5106
5705
  url: item.url,
@@ -5136,7 +5735,7 @@ export async function executeRecessCommand(argv, options = {}) {
5136
5735
  }
5137
5736
  throw new CliError("invalid_arguments", "Use goals queue get|set.");
5138
5737
  }
5139
- throw new CliError("invalid_arguments", "Use goals list|create|edit|delete|restore|archive|unarchive|complete|undo-completion|move-module|queue|files|pdf|video.");
5738
+ throw new CliError("invalid_arguments", "Use goals list|create|edit|delete|restore|archive|unarchive|complete|undo-completion|move-module|launch-todo|queue|files|pdf|video.");
5140
5739
  }
5141
5740
  if (noun === "channels") {
5142
5741
  return runChannelsCommand({ parsed, api, writeCommand });
@@ -5162,6 +5761,9 @@ export async function executeRecessCommand(argv, options = {}) {
5162
5761
  if (noun === "tuition-plans") {
5163
5762
  return runTuitionPlansCommand({ parsed, api, writeCommand });
5164
5763
  }
5764
+ if (noun === "reports") {
5765
+ return runReportsCommand({ parsed, api, writeCommand });
5766
+ }
5165
5767
  if (noun === "students") {
5166
5768
  if (verb === "list") {
5167
5769
  const requestedScope = flagString(parsed, "scope");
@@ -5231,20 +5833,7 @@ export async function executeRecessCommand(argv, options = {}) {
5231
5833
  }
5232
5834
  const cursor = flagString(parsed, "cursor");
5233
5835
  const limit = flagNumber(parsed, "limit");
5234
- let studentId = student;
5235
- if (!/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i.test(student)) {
5236
- const roster = unwrap(await api.client.GET("/tutor/students", {
5237
- params: { query: { scope: "mine" } },
5238
- }));
5239
- const normalize = (name) => name.trim().replace(/\s+/g, " ").toLowerCase();
5240
- const matches = roster.items.filter((item) => normalize(item.name) === normalize(student));
5241
- if (matches.length !== 1) {
5242
- throw new CliError(matches.length ? "ambiguous_student" : "student_not_found", matches.length
5243
- ? "Multiple students have that name. Ask which student, then retry with their ID."
5244
- : "No exact name match in your roster. Use students list to find the student's ID.", 1, { matches: matches.map(({ userId, name }) => ({ userId, name })) });
5245
- }
5246
- studentId = matches[0].userId;
5247
- }
5836
+ const studentId = (await resolveStudentReference(api, student)).id;
5248
5837
  return unwrap(await api.client.GET("/studio/students/{studentId}/todos", {
5249
5838
  params: {
5250
5839
  path: { studentId },
@@ -5288,7 +5877,8 @@ export async function executeRecessCommand(argv, options = {}) {
5288
5877
  }
5289
5878
  if (noun === "todos") {
5290
5879
  if (verb === "create") {
5291
- const studentId = flagString(parsed, "student", { required: true });
5880
+ const student = await studentFlag(api, parsed, { required: true });
5881
+ const studentId = student.id;
5292
5882
  const title = flagString(parsed, "title", { required: true });
5293
5883
  const targetDurationInMins = flagNumber(parsed, "target-minutes");
5294
5884
  const body = {
@@ -5306,6 +5896,7 @@ export async function executeRecessCommand(argv, options = {}) {
5306
5896
  action: "create a todo for a managed student",
5307
5897
  target: { studentUserId: studentId },
5308
5898
  request: body,
5899
+ details: resolvedStudentDetails(student),
5309
5900
  }, async () => unwrap(await api.client.POST("/tutor/browser/todos/", { body })));
5310
5901
  }
5311
5902
  if (verb === "edit") {
@@ -5503,7 +6094,8 @@ export async function executeRecessCommand(argv, options = {}) {
5503
6094
  }
5504
6095
  if (verb === "generate-applet") {
5505
6096
  const todoId = positional(parsed, 2, "todo ID");
5506
- const studentId = flagString(parsed, "student", { required: true });
6097
+ const student = await studentFlag(api, parsed, { required: true });
6098
+ const studentId = student.id;
5507
6099
  const targetDueDateISO = flagDateOnly(parsed, "due-date");
5508
6100
  const [todo, learningAnalysis] = await Promise.all([
5509
6101
  api.client.GET("/tutor/browser/todos/{id}/", {
@@ -5545,7 +6137,8 @@ export async function executeRecessCommand(argv, options = {}) {
5545
6137
  throw new CliError("invalid_arguments", "Use todos create|edit|complete|delete|restore|generate-learning-analysis|generate-applet.");
5546
6138
  }
5547
6139
  if (noun === "memories") {
5548
- const studentId = flagString(parsed, "student", { required: true });
6140
+ const student = await studentFlag(api, parsed, { required: true });
6141
+ const studentId = student.id;
5549
6142
  if (verb === "context") {
5550
6143
  return unwrap(await api.client.GET("/tutor/students/{studentId}/prompt-memory", {
5551
6144
  params: { path: { studentId } },
@@ -5569,10 +6162,17 @@ export async function executeRecessCommand(argv, options = {}) {
5569
6162
  if (verb === "set") {
5570
6163
  const patchFile = flagString(parsed, "patch-file", { required: true });
5571
6164
  const patch = (await readJsonFile(patchFile, "Rocky config patch file"));
5572
- const expected = flagString(parsed, "expected-updated-at", {
5573
- required: true,
5574
- });
5575
- const expectedUpdatedAt = expected === "none" ? null : expected;
6165
+ // Optional: without it, the config's current updatedAt (null when the
6166
+ // student has none yet) is read now and pinned into the preview, so a
6167
+ // change before confirm alters the preview and the confirm is refused.
6168
+ const expected = flagString(parsed, "expected-updated-at");
6169
+ const expectedUpdatedAt = expected === undefined
6170
+ ? unwrap(await api.client.GET("/tutor/students/{studentId}/rocky-config", {
6171
+ params: { path: { studentId } },
6172
+ })).updatedAt
6173
+ : expected === "none"
6174
+ ? null
6175
+ : expected;
5576
6176
  if (expectedUpdatedAt !== null &&
5577
6177
  Number.isNaN(Date.parse(expectedUpdatedAt))) {
5578
6178
  throw new CliError("invalid_arguments", "--expected-updated-at must be an ISO datetime from `rocky get`, or `none`.");
@@ -5805,7 +6405,8 @@ export async function executeRecessCommand(argv, options = {}) {
5805
6405
  if (action !== "upload") {
5806
6406
  throw new CliError("invalid_arguments", "Use goals pdf upload.");
5807
6407
  }
5808
- const studentId = flagString(parsed, "student", { required: true });
6408
+ const student = await studentFlag(api, parsed, { required: true });
6409
+ const studentId = student.id;
5809
6410
  const goalId = flagString(parsed, "goal");
5810
6411
  const draftSlug = flagString(parsed, "draft");
5811
6412
  if (Boolean(goalId) === Boolean(draftSlug)) {
@@ -5870,6 +6471,7 @@ export async function executeRecessCommand(argv, options = {}) {
5870
6471
  message,
5871
6472
  },
5872
6473
  details: {
6474
+ ...resolvedStudentDetails(student),
5873
6475
  currentChangeId: preflight.currentChangeId,
5874
6476
  note: "The PDF is stored separately and the goal workspace receives a small verified reference, matching planner-authored textbook goals.",
5875
6477
  },
@@ -5970,17 +6572,21 @@ export async function executeRecessCommand(argv, options = {}) {
5970
6572
  workspacePath,
5971
6573
  workspace,
5972
6574
  };
5973
- });
6575
+ },
6576
+ // A draft workspace is never served to a kid: no confirm round trip.
6577
+ { ungated: !goalId });
5974
6578
  }
5975
6579
  if (noun === "goals" && verb === "files") {
5976
6580
  const action = positional(parsed, 2, "goals files action");
5977
6581
  if (action === "list") {
5978
- const studentId = flagString(parsed, "student", { required: true });
6582
+ const student = await studentFlag(api, parsed, { required: true });
6583
+ const studentId = student.id;
5979
6584
  const goalId = flagString(parsed, "goal", { required: true });
5980
6585
  return unwrap(await api.client.GET("/tutor/students/{studentId}/goals/{goalId}/workspace/files", { params: { path: { studentId, goalId } } }));
5981
6586
  }
5982
6587
  if (action === "read") {
5983
- const studentId = flagString(parsed, "student", { required: true });
6588
+ const student = await studentFlag(api, parsed, { required: true });
6589
+ const studentId = student.id;
5984
6590
  const goalId = flagString(parsed, "goal", { required: true });
5985
6591
  return unwrap(await api.client.GET("/tutor/students/{studentId}/goals/{goalId}/workspace/file", {
5986
6592
  params: {
@@ -5990,7 +6596,8 @@ export async function executeRecessCommand(argv, options = {}) {
5990
6596
  }));
5991
6597
  }
5992
6598
  if (action === "init" || action === "checkout") {
5993
- const studentId = flagString(parsed, "student", { required: true });
6599
+ const student = await studentFlag(api, parsed, { required: true });
6600
+ const studentId = student.id;
5994
6601
  const goalId = flagString(parsed, "goal");
5995
6602
  const draftSlug = flagString(parsed, "draft");
5996
6603
  if (action === "init" && (goalId || !draftSlug)) {
@@ -6005,16 +6612,112 @@ export async function executeRecessCommand(argv, options = {}) {
6005
6612
  const target = goalId
6006
6613
  ? { kind: "goal", goalId }
6007
6614
  : { kind: "draft", draftSlug: draftSlug };
6008
- const response = await readRemoteWorkspaceSnapshot(api, studentId, target);
6009
- if (action === "init" && response.snapshot.fileCount > 0) {
6010
- throw new CliError("draft_exists", `Draft ${draftSlug} already has files. Use goals files checkout --draft to preserve them.`);
6615
+ const scaffold = hasFlag(parsed, "scaffold");
6616
+ const modulesFlag = flagString(parsed, "modules");
6617
+ const title = flagString(parsed, "title");
6618
+ if (!scaffold && (modulesFlag !== undefined || title !== undefined)) {
6619
+ throw new CliError("invalid_arguments", "--modules and --title are used with goals files init --scaffold.");
6620
+ }
6621
+ const moduleCount = flagNumber(parsed, "modules") ?? 3;
6622
+ if (scaffold &&
6623
+ (!Number.isInteger(moduleCount) || moduleCount < 1 || moduleCount > 20)) {
6624
+ throw new CliError("invalid_arguments", "--modules must be an integer from 1 through 20.");
6625
+ }
6626
+ if (title !== undefined && (!title.trim() || title.length > 200)) {
6627
+ throw new CliError("invalid_arguments", "--title must be 1 to 200 characters.");
6628
+ }
6629
+ if (scaffold && action !== "init") {
6630
+ throw new CliError("invalid_arguments", "--scaffold is only for goals files init on an empty draft.");
6631
+ }
6632
+ if (action === "checkout") {
6633
+ const response = await readRemoteWorkspaceSnapshot(api, studentId, target);
6634
+ return checkoutGoalWorkspace({
6635
+ outputDirectory,
6636
+ studentId,
6637
+ target,
6638
+ snapshot: response.snapshot,
6639
+ });
6640
+ }
6641
+ // The server scaffold is a fixed two-lesson tree; an explicit --modules
6642
+ // count keeps the local scaffold, as does a server without the init route.
6643
+ const serverScaffold = scaffold && modulesFlag === undefined;
6644
+ const initialized = await initDraftWorkspace(api, {
6645
+ studentId,
6646
+ draftSlug: draftSlug,
6647
+ outputDirectory,
6648
+ scaffold: serverScaffold,
6649
+ title,
6650
+ });
6651
+ let snapshot = initialized?.snapshot;
6652
+ if (!initialized) {
6653
+ const response = await readRemoteWorkspaceSnapshot(api, studentId, target);
6654
+ // An existing but empty draft is adopted as-is; one with files is only
6655
+ // ever checked out, so init can never shadow authored content.
6656
+ if (response.snapshot.fileCount > 0) {
6657
+ throw draftNotEmptyError({
6658
+ draftSlug: draftSlug,
6659
+ studentId,
6660
+ outputDirectory,
6661
+ fileCount: response.snapshot.fileCount,
6662
+ });
6663
+ }
6664
+ snapshot = response.snapshot;
6011
6665
  }
6012
- return checkoutGoalWorkspace({
6666
+ const checkedOut = await checkoutGoalWorkspace({
6013
6667
  outputDirectory,
6014
6668
  studentId,
6015
6669
  target,
6016
- snapshot: response.snapshot,
6670
+ snapshot: snapshot,
6017
6671
  });
6672
+ const initDetails = initialized
6673
+ ? {
6674
+ adopted: initialized.adopted,
6675
+ previousChangeId: initialized.previousChangeId,
6676
+ }
6677
+ : {};
6678
+ if (initialized?.scaffolded) {
6679
+ const files = initialized.snapshot.files.map((file) => file.path);
6680
+ return {
6681
+ ...checkedOut,
6682
+ ...initDetails,
6683
+ scaffold: {
6684
+ source: "server",
6685
+ files,
6686
+ modules: files.filter((file) => file.startsWith("modules/")),
6687
+ validation: serverWorkspaceValidation(initialized),
6688
+ },
6689
+ next: `The scaffold is already pushed to draft ${draftSlug} (change ${initialized.changeId}). Rewrite its generic lesson prose for this child, add or rename modules as W1-M<n>-<topic>.md, keep state/progress.json currentModuleRef on the first module, commit, then run recess --json goals files push --source-dir ${JSON.stringify(checkedOut.directory)} --reason <purpose>. Draft pushes report workspace validation and do not need --confirm.`,
6690
+ };
6691
+ }
6692
+ if (!scaffold)
6693
+ return { ...checkedOut, ...initDetails };
6694
+ // The local scaffold is a LOCAL commit on top of the empty draft:
6695
+ // nothing is published until the author rewrites it and pushes.
6696
+ const files = buildGoalWorkspaceScaffold({
6697
+ draftSlug: draftSlug,
6698
+ moduleCount,
6699
+ title,
6700
+ });
6701
+ for (const file of files) {
6702
+ const destination = resolveWorkspaceCheckoutPath(checkedOut.directory, file.path);
6703
+ await fs.mkdir(path.dirname(destination), { recursive: true });
6704
+ await fs.writeFile(destination, file.content);
6705
+ }
6706
+ await runGit(checkedOut.directory, ["add", "-A"]);
6707
+ await runGit(checkedOut.directory, ["commit", "--quiet", "-m", "Scaffold module-backed goal workspace"], { identity: true });
6708
+ return {
6709
+ ...checkedOut,
6710
+ ...initDetails,
6711
+ scaffold: {
6712
+ source: "local",
6713
+ files: files.map((file) => file.path),
6714
+ modules: files
6715
+ .map((file) => file.path)
6716
+ .filter((file) => file.startsWith("modules/")),
6717
+ validation: validateGoalWorkspaceLocally(files),
6718
+ },
6719
+ next: `Rewrite every scaffold file for this child (each carries a recess-scaffold marker; delete the marker once rewritten), add or rename modules as W1-M<n>-<topic>.md, keep state/progress.json currentModuleRef on the first module, commit, then run recess --json goals files push --source-dir ${JSON.stringify(checkedOut.directory)} --reason <purpose>. Draft pushes report workspace validation and do not need --confirm.`,
6720
+ };
6018
6721
  }
6019
6722
  if (action === "push") {
6020
6723
  const sourceDirectory = flagString(parsed, "source-dir", {
@@ -6116,11 +6819,15 @@ export async function executeRecessCommand(argv, options = {}) {
6116
6819
  JSON.stringify(receipt.request) !== JSON.stringify(request)) {
6117
6820
  throw new CliError("approval_mismatch", "The command or committed file bytes differ from the approved push.");
6118
6821
  }
6822
+ const workspaceValidation = isGoal
6823
+ ? undefined
6824
+ : await draftWorkspaceValidation(preflight, () => readCheckoutTree(checkout.root));
6119
6825
  const preview = receipt ?? {
6120
6826
  action: actionDescription,
6121
6827
  target: boundTarget ?? preflight.target,
6122
6828
  request,
6123
6829
  details: {
6830
+ ...(workspaceValidation ? { workspaceValidation } : {}),
6124
6831
  stateModificationPaths: preflight.stateModificationPaths ?? [],
6125
6832
  warnings: preflight.warnings ?? [],
6126
6833
  currentChangeId: preflight.currentChangeId,
@@ -6145,17 +6852,24 @@ export async function executeRecessCommand(argv, options = {}) {
6145
6852
  changeId: result.changeId,
6146
6853
  upstreamCommit: local.head,
6147
6854
  });
6855
+ const writtenValidation = serverWorkspaceValidation(result) ?? workspaceValidation;
6148
6856
  return {
6149
6857
  ...result,
6858
+ ...(writtenValidation
6859
+ ? { workspaceValidation: writtenValidation }
6860
+ : {}),
6150
6861
  local: {
6151
6862
  directory: checkout.root,
6152
6863
  upstreamCommit: local.head,
6153
6864
  },
6154
6865
  };
6155
- }, isGoal);
6866
+ },
6867
+ // A draft workspace is never served to a kid: no confirm round trip.
6868
+ { persistPreview: isGoal, ungated: !isGoal });
6156
6869
  }
6157
6870
  if (action === "write") {
6158
- const studentId = flagString(parsed, "student", { required: true });
6871
+ const student = await studentFlag(api, parsed, { required: true });
6872
+ const studentId = student.id;
6159
6873
  const goalId = flagString(parsed, "goal");
6160
6874
  const draftSlug = flagString(parsed, "draft");
6161
6875
  if (Boolean(goalId) === Boolean(draftSlug)) {
@@ -6216,11 +6930,32 @@ export async function executeRecessCommand(argv, options = {}) {
6216
6930
  if (preflight && preflight.action !== "preview_workspace_files_write") {
6217
6931
  throw new CliError("unexpected_response", "Goal workspace write did not return a preview; nothing was written.");
6218
6932
  }
6933
+ // The draft after this upsert: its current files overlaid with these.
6934
+ const workspaceValidation = target.kind === "draft"
6935
+ ? await draftWorkspaceValidation(preflight, async () => {
6936
+ const tree = new Map();
6937
+ const { snapshot } = await readRemoteWorkspaceSnapshot(api, studentId, target);
6938
+ for (const file of snapshot.files) {
6939
+ tree.set(file.path, file.contentEncoding === "base64"
6940
+ ? Buffer.from(file.content, "base64").toString("utf8")
6941
+ : file.content);
6942
+ }
6943
+ for (const file of input.files) {
6944
+ tree.set(file.path, Buffer.from(file.content, "base64").toString("utf8"));
6945
+ }
6946
+ return [...tree].map(([filePath, content]) => ({
6947
+ path: filePath,
6948
+ content,
6949
+ }));
6950
+ })
6951
+ : undefined;
6219
6952
  const preview = receipt ?? {
6220
6953
  action: "batch-upsert files in a student's goal workspace",
6221
6954
  target: boundTarget ?? preflight.target,
6222
6955
  request,
6223
6956
  details: {
6957
+ ...resolvedStudentDetails(student),
6958
+ ...(workspaceValidation ? { workspaceValidation } : {}),
6224
6959
  stateModificationPaths: preflight.stateModificationPaths ?? [],
6225
6960
  warnings: preflight.warnings ?? [],
6226
6961
  currentChangeId: preflight.currentChangeId,
@@ -6231,13 +6966,21 @@ export async function executeRecessCommand(argv, options = {}) {
6231
6966
  : "This directly edits the live goal workspace, including modules/ and state/. The write remains bound to the previewed workspace revision.",
6232
6967
  },
6233
6968
  };
6234
- return previewBoundWrite(parsed, preview, async () => unwrap(await api.client.POST("/tutor/browser/mesa/workspace-files", {
6235
- body: {
6236
- ...body,
6237
- dryRun: false,
6238
- expectedChangeId: String(preview.details.currentChangeId),
6239
- },
6240
- })), Boolean(goalId));
6969
+ return previewBoundWrite(parsed, preview, async () => {
6970
+ const result = unwrap(await api.client.POST("/tutor/browser/mesa/workspace-files", {
6971
+ body: {
6972
+ ...body,
6973
+ dryRun: false,
6974
+ expectedChangeId: String(preview.details.currentChangeId),
6975
+ },
6976
+ }));
6977
+ const writtenValidation = serverWorkspaceValidation(result) ?? workspaceValidation;
6978
+ return writtenValidation
6979
+ ? { ...result, workspaceValidation: writtenValidation }
6980
+ : result;
6981
+ },
6982
+ // A draft workspace is never served to a kid: no confirm round trip.
6983
+ { persistPreview: Boolean(goalId), ungated: !goalId });
6241
6984
  }
6242
6985
  throw new CliError("invalid_arguments", "Use goals files list|read|init|checkout|push|write.");
6243
6986
  }