recess-cli 3.9.0 → 3.11.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
@@ -14,6 +14,7 @@ import { runChannelsCommand } from "./commands/channels.js";
14
14
  import { runChatLogsCommand } from "./commands/chat-logs.js";
15
15
  import { runDbCommand } from "./commands/db.js";
16
16
  import { runRoomsCommand } from "./commands/rooms.js";
17
+ import { runFeedCommand } from "./commands/feed.js";
17
18
  import { runFamiliesCommand } from "./commands/families.js";
18
19
  import { runStudentsTextsCommand, runUsersPhoneCommand, } from "./commands/phone-and-texts.js";
19
20
  import { runTuitionPlansCommand } from "./commands/tuition-plans.js";
@@ -29,15 +30,99 @@ import { HELP } from "./help.js";
29
30
  export { HELP };
30
31
  import { cliRequestHeaders, noteServerCliVersions, requireCliRequestReason, } from "./http.js";
31
32
  import { runSelfUpdate, UPGRADE_COMMAND, updateNoticeText, updateStatus, } from "./update-notice.js";
32
- import { requireConfirmation } from "./safety.js";
33
+ import { requireConfirmation, resolveApprovalToken, } from "./safety.js";
33
34
  import { installSkill, isEphemeralInstall, readBundledSkillVersion, readCliVersion, } from "./setup.js";
34
35
  import { ensureFreshSession, revokeSession } from "./session-refresh.js";
35
36
  import { compareVersions, updateSkillFromServer } from "./skill-update.js";
36
37
  import { readSkillCache, writeSkillCache } from "./skills-cache.js";
37
38
  import { sanitizeWorkspaceUploadName } from "./upload-names.js";
38
39
  import { appendJobEvent, getJob, listJobs, pruneJobs } from "./jobs.js";
39
- function requiredRequestReason(parsed) {
40
- return requireCliRequestReason(flagString(parsed, "reason", { required: true }));
40
+ import { applyStudentsToAnswers, buildAnswersTemplate, buildGoalWorkspaceScaffold, resolveStudentReference, serverWorkspaceValidation, specValidationErrorLines, validateGoalWorkspaceLocally, } from "./goal-authoring.js";
41
+ const localInvocations = new WeakMap();
42
+ /** Never replayed from the ledger: they are what `recess confirm` supplies. */
43
+ const CONFIRMATION_FLAGS = new Set([
44
+ "confirm",
45
+ "operation-key",
46
+ "approval-token",
47
+ ]);
48
+ /** A stale approval is not an approval; preview again after this. */
49
+ const CONFIRM_REPLAY_TTL_MS = 24 * 60 * 60 * 1000;
50
+ function replayableArgv(argv) {
51
+ const kept = [];
52
+ for (let index = 0; index < argv.length; index += 1) {
53
+ const value = argv[index];
54
+ const name = value.startsWith("--") ? value.slice(2).split("=", 1)[0] : "";
55
+ if (!CONFIRMATION_FLAGS.has(name)) {
56
+ kept.push(value);
57
+ continue;
58
+ }
59
+ // `--name value` (not `--name=value`, not the boolean --confirm) also
60
+ // consumes the following token.
61
+ if (name !== "confirm" &&
62
+ !value.includes("=") &&
63
+ argv[index + 1] !== undefined &&
64
+ !argv[index + 1].startsWith("--")) {
65
+ index += 1;
66
+ }
67
+ }
68
+ return kept;
69
+ }
70
+ function replayFor(parsed) {
71
+ const invocation = localInvocations.get(parsed);
72
+ if (!invocation)
73
+ return undefined;
74
+ return {
75
+ argv: replayableArgv(invocation.argv),
76
+ cwd: process.cwd(),
77
+ ...(invocation.apiOrigin ? { apiOrigin: invocation.apiOrigin } : {}),
78
+ };
79
+ }
80
+ /**
81
+ * Server writes whose usage carries no --confirm (they execute directly), so
82
+ * the usage-based read classification below must not default their reason.
83
+ * `db query` is a read, but raw production SQL keeps a human-written purpose.
84
+ */
85
+ const EXPLICIT_REASON_COMMANDS = new Set([
86
+ "apps validate",
87
+ "apps publish",
88
+ "apps assign",
89
+ "apps primitives publish",
90
+ "db query",
91
+ ]);
92
+ function missingWriteReason(command) {
93
+ const path = command?.path.join(" ") ?? "<command>";
94
+ 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, {
95
+ ...(command ? { usage: command.usage } : {}),
96
+ requiredFlag: "--reason",
97
+ example: `recess ${path} … --reason "<why, in one sentence>"`,
98
+ });
99
+ }
100
+ /**
101
+ * Every API call carries an audit reason. Reads (no --confirm in their usage)
102
+ * default it to `Read: <command path>`; writes must supply one, and fail here —
103
+ * before any network call — when they don't. Hosted transport keeps requiring
104
+ * it everywhere (recess-mcp audits it per call).
105
+ */
106
+ function resolveRequestReason(parsed, command, remote) {
107
+ const supplied = flagString(parsed, "reason", { required: remote });
108
+ if (supplied !== undefined)
109
+ return requireCliRequestReason(supplied);
110
+ const path = command?.path.join(" ");
111
+ const isWrite = !command ||
112
+ Boolean(command.flags.confirm) ||
113
+ EXPLICIT_REASON_COMMANDS.has(path);
114
+ if (isWrite)
115
+ throw missingWriteReason(command);
116
+ const invocation = localInvocations.get(parsed);
117
+ if (invocation)
118
+ invocation.reasonDefaulted = true;
119
+ return `Read: ${path}`;
120
+ }
121
+ /** Safety net for a write the usage-based classification read as a read. */
122
+ function assertExplicitWriteReason(parsed) {
123
+ if (localInvocations.get(parsed)?.reasonDefaulted) {
124
+ throw missingWriteReason(findCommandSchema(buildCommandSchema(HELP), parsed.positionals));
125
+ }
41
126
  }
42
127
  /**
43
128
  * Role of whoever this session belongs to.
@@ -251,17 +336,26 @@ async function skillStatus(config, reason) {
251
336
  };
252
337
  }
253
338
  }
254
- async function localWriteCommand(parsed, preview, execute) {
339
+ 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.";
340
+ function confirmNextHint(parsed, operationKey) {
341
+ return localInvocations.has(parsed)
342
+ ? { next: `recess confirm ${operationKey}` }
343
+ : {};
344
+ }
345
+ async function localWriteCommand(parsed, preview, execute, options = {}) {
346
+ assertExplicitWriteReason(parsed);
255
347
  const fingerprint = approvalTokenFor(preview);
256
- const suppliedOperationKey = flagString(parsed, "operation-key");
257
- if (!hasFlag(parsed, "confirm")) {
348
+ let suppliedOperationKey = flagString(parsed, "operation-key");
349
+ if (!hasFlag(parsed, "confirm") && !options.ungated) {
258
350
  const operationKey = operationKeyFor(fingerprint);
351
+ const replay = replayFor(parsed);
259
352
  const boundPreview = {
260
353
  ...preview,
261
354
  details: {
262
355
  ...preview.details,
263
356
  operationKey,
264
- 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.",
357
+ retry: CONFIRM_RETRY_HINT,
358
+ ...confirmNextHint(parsed, operationKey),
265
359
  },
266
360
  };
267
361
  await appendJobEvent({
@@ -276,9 +370,13 @@ async function localWriteCommand(parsed, preview, execute) {
276
370
  preview.request.zeroBalance === "true"
277
371
  ? { preview }
278
372
  : {}),
373
+ ...(replay ? { replay } : {}),
279
374
  });
280
375
  requireConfirmation(false, boundPreview);
281
376
  }
377
+ if (options.ungated && !suppliedOperationKey) {
378
+ suppliedOperationKey = operationKeyFor(fingerprint);
379
+ }
282
380
  if (!suppliedOperationKey) {
283
381
  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" });
284
382
  }
@@ -522,6 +620,35 @@ async function readRemoteWorkspaceSnapshot(api, studentId, target) {
522
620
  },
523
621
  }));
524
622
  }
623
+ function draftNotEmptyError(input) {
624
+ 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 });
625
+ }
626
+ /**
627
+ * `POST /workspace-files/init`: adopts an empty draft and, with `scaffold`,
628
+ * pushes the server's valid starter tree. Returns null when the server
629
+ * predates the route (a bare Fastify 404, no `code`) so the caller falls back
630
+ * to reading the draft and scaffolding locally.
631
+ */
632
+ async function initDraftWorkspace(api, input) {
633
+ const result = await api.client.POST("/tutor/browser/mesa/workspace-files/init", {
634
+ body: {
635
+ studentUserId: input.studentId,
636
+ draftSlug: input.draftSlug,
637
+ scaffold: input.scaffold,
638
+ ...(input.title === undefined ? {} : { title: input.title }),
639
+ },
640
+ });
641
+ const error = result.error;
642
+ if (result.response.status === 404 && error?.code !== "NOT_FOUND")
643
+ return null;
644
+ if (result.response.status === 409 && error?.code === "DRAFT_NOT_EMPTY") {
645
+ throw draftNotEmptyError({
646
+ ...input,
647
+ fileCount: typeof error.fileCount === "number" ? error.fileCount : 0,
648
+ });
649
+ }
650
+ return unwrap(result);
651
+ }
525
652
  async function assertCheckoutReadyForMaterialization(checkout) {
526
653
  const status = await runGit(checkout.root, ["status", "--porcelain=v1"]);
527
654
  if (status.trim()) {
@@ -635,20 +762,28 @@ function assertOperationKeyMatchesPreview(operationKey, fingerprint, preview) {
635
762
  });
636
763
  }
637
764
  }
638
- async function requirePreviewBoundConfirmation(parsed, preview, persistPreview = false) {
765
+ async function requirePreviewBoundConfirmation(parsed, preview, persistOrOptions = false) {
766
+ const options = typeof persistOrOptions === "boolean"
767
+ ? { persistPreview: persistOrOptions }
768
+ : persistOrOptions;
769
+ assertExplicitWriteReason(parsed);
639
770
  const approvalToken = approvalTokenFor(preview);
640
771
  const suppliedOperationKey = flagString(parsed, "operation-key");
772
+ const operationKey = suppliedOperationKey ?? operationKeyFor(approvalToken);
641
773
  const boundPreview = {
642
774
  ...preview,
643
775
  details: {
644
776
  ...preview.details,
645
777
  approvalToken,
646
- operationKey: suppliedOperationKey ?? operationKeyFor(approvalToken),
778
+ operationKey,
779
+ retry: CONFIRM_RETRY_HINT,
780
+ ...confirmNextHint(parsed, operationKey),
647
781
  },
648
782
  };
649
- if (!hasFlag(parsed, "confirm")) {
783
+ if (!hasFlag(parsed, "confirm") && !options.ungated) {
784
+ const replay = replayFor(parsed);
650
785
  await appendJobEvent({
651
- jobId: String(boundPreview.details.operationKey),
786
+ jobId: operationKey,
652
787
  status: "awaiting_confirmation",
653
788
  timestamp: new Date().toISOString(),
654
789
  action: preview.action,
@@ -656,27 +791,32 @@ async function requirePreviewBoundConfirmation(parsed, preview, persistPreview =
656
791
  target: preview.target,
657
792
  // Opted-in operations retain the approved receipt in the 0600 ledger so
658
793
  // retries can reach server idempotency after their own write changed state.
659
- ...(persistPreview ? { preview } : {}),
794
+ ...(options.persistPreview ? { preview } : {}),
795
+ ...(replay ? { replay } : {}),
660
796
  });
661
797
  requireConfirmation(false, boundPreview);
662
798
  }
663
- const supplied = flagString(parsed, "approval-token");
664
- if (supplied !== approvalToken) {
665
- 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" });
666
- }
667
- if (!suppliedOperationKey) {
799
+ if (!suppliedOperationKey && !options.ungated) {
668
800
  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" });
669
801
  }
670
- assertOperationKeyMatchesPreview(suppliedOperationKey, approvalToken, boundPreview);
802
+ if (suppliedOperationKey) {
803
+ assertOperationKeyMatchesPreview(suppliedOperationKey, approvalToken, boundPreview);
804
+ }
805
+ // The approval token is the operation key's suffix; --approval-token is
806
+ // optional and, when given, must agree with the key.
807
+ const supplied = resolveApprovalToken(parsed);
808
+ if (!options.ungated && supplied !== approvalToken) {
809
+ 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" });
810
+ }
671
811
  await appendJobEvent({
672
- jobId: suppliedOperationKey,
812
+ jobId: operationKey,
673
813
  status: "running",
674
814
  timestamp: new Date().toISOString(),
675
815
  action: preview.action,
676
816
  fingerprint: approvalToken,
677
817
  target: preview.target,
678
818
  });
679
- return { operationKey: suppliedOperationKey, fingerprint: approvalToken };
819
+ return { operationKey, fingerprint: approvalToken };
680
820
  }
681
821
  /**
682
822
  * A tutor template's `body` is the `## Subjects` block markdown (no `###`
@@ -716,8 +856,8 @@ async function readTutorTemplateLessons(directory) {
716
856
  }
717
857
  return lessons;
718
858
  }
719
- async function previewBoundWrite(parsed, preview, execute, persistPreview = false) {
720
- const context = await requirePreviewBoundConfirmation(parsed, preview, persistPreview);
859
+ async function previewBoundWrite(parsed, preview, execute, persistOrOptions = false) {
860
+ const context = await requirePreviewBoundConfirmation(parsed, preview, persistOrOptions);
721
861
  try {
722
862
  const result = await withIdempotencyContext(context, execute);
723
863
  await appendJobEvent({
@@ -766,12 +906,20 @@ async function readExecutedPreview(parsed) {
766
906
  const saved = receipt.preview;
767
907
  const fingerprint = approvalTokenFor(saved);
768
908
  if (receipt.fingerprint !== fingerprint ||
769
- flagString(parsed, "approval-token") !== fingerprint) {
909
+ resolveApprovalToken(parsed) !== fingerprint) {
770
910
  throw new CliError("approval_mismatch", "This operation key does not match the approved command. Retry the original command unchanged, or review a new preview.");
771
911
  }
772
912
  assertOperationKeyMatchesPreview(key, fingerprint, saved);
773
913
  return saved;
774
914
  }
915
+ /** `--confirm` names an operation key the local ledger shows already attempted. */
916
+ async function operationKeyAttempted(parsed) {
917
+ const key = flagString(parsed, "operation-key");
918
+ if (!hasFlag(parsed, "confirm") || !key)
919
+ return false;
920
+ const { history } = await getJob(key);
921
+ return history.some((event) => event.status !== "awaiting_confirmation");
922
+ }
775
923
  /** A retried write must retain its approved fence after changing its own source state. */
776
924
  async function recoverExecutedPreview(parsed, expected) {
777
925
  const saved = await readExecutedPreview(parsed);
@@ -784,6 +932,98 @@ async function recoverExecutedPreview(parsed, expected) {
784
932
  }
785
933
  return saved;
786
934
  }
935
+ function shellQuote(argv) {
936
+ return argv
937
+ .map((value) => /^[A-Za-z0-9_@%+=:,./-]+$/.test(value)
938
+ ? value
939
+ : `'${value.replaceAll("'", `'\\''`)}'`)
940
+ .join(" ");
941
+ }
942
+ /** Flags a confirmation may add on top of the stored command. */
943
+ const CONFIRM_PASSTHROUGH_FLAGS = [
944
+ "confirm-destructive-changes",
945
+ "destructive-change-token",
946
+ ];
947
+ /**
948
+ * `recess confirm <operation-key>`: replay the exact argv a preview stored in
949
+ * the local job ledger with `--confirm --operation-key <key>`. The replay
950
+ * rebuilds the preview and the write machinery refuses to execute unless its
951
+ * fingerprint still equals the key's suffix — the same guarantee as typing the
952
+ * full command again, without retyping it.
953
+ */
954
+ async function confirmStagedWrite(parsed, options) {
955
+ const operationKey = positional(parsed, 1, "operation key");
956
+ const fixed = ["reason", "profile", "operation-key", "approval-token"].find((name) => hasFlag(parsed, name));
957
+ if (fixed) {
958
+ throw new CliError("invalid_arguments", `recess confirm takes --${fixed} from the stored preview; pass only the operation key.`);
959
+ }
960
+ const { history } = await getJob(operationKey);
961
+ const staged = [...history]
962
+ .reverse()
963
+ .find((event) => event.status === "awaiting_confirmation" && event.replay);
964
+ if (!staged?.replay) {
965
+ throw new CliError("not_found", history.length === 0
966
+ ? `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.`
967
+ : `Operation ${operationKey} has no stored command to replay (previewed by an older recess). Rerun the original command with --confirm --operation-key ${operationKey}.`, 1, { operationKey });
968
+ }
969
+ const command = `recess ${shellQuote(staged.replay.argv)}`;
970
+ const completed = [...history]
971
+ .reverse()
972
+ .find((event) => event.status === "completed");
973
+ if (completed) {
974
+ return {
975
+ operationKey,
976
+ alreadyCompleted: true,
977
+ completedAt: completed.timestamp,
978
+ result: completed.result,
979
+ };
980
+ }
981
+ if (Date.now() - Date.parse(staged.timestamp) > CONFIRM_REPLAY_TTL_MS) {
982
+ 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 });
983
+ }
984
+ if (!operationKey.endsWith(`_${staged.fingerprint}`)) {
985
+ throw new CliError("approval_mismatch", `Operation ${operationKey} was not minted for the payload stored under it. Preview again: ${command}`, 2, { operationKey, command });
986
+ }
987
+ const config = options.config ??
988
+ (await resolveConfig(flagString(parseArgs(staged.replay.argv), "profile")));
989
+ if (staged.replay.apiOrigin && staged.replay.apiOrigin !== config.apiOrigin) {
990
+ 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, {
991
+ operationKey,
992
+ previewedApiOrigin: staged.replay.apiOrigin,
993
+ apiOrigin: config.apiOrigin,
994
+ });
995
+ }
996
+ if (process.cwd() !== staged.replay.cwd) {
997
+ try {
998
+ // Relative --file/--source-dir paths resolve where the preview ran.
999
+ process.chdir(staged.replay.cwd);
1000
+ }
1001
+ catch {
1002
+ throw new CliError("confirmation_target_changed", `Operation ${operationKey} was previewed in ${staged.replay.cwd}, which no longer exists. Preview again: ${command}`, 2, { operationKey, command });
1003
+ }
1004
+ }
1005
+ const passthrough = CONFIRM_PASSTHROUGH_FLAGS.flatMap((name) => {
1006
+ const value = parsed.flags.get(name);
1007
+ if (value === undefined)
1008
+ return [];
1009
+ return value === true ? [`--${name}`] : [`--${name}`, value];
1010
+ });
1011
+ try {
1012
+ return await executeRecessCommand([
1013
+ ...staged.replay.argv,
1014
+ ...passthrough,
1015
+ "--confirm",
1016
+ "--operation-key",
1017
+ operationKey,
1018
+ ], { ...options, config });
1019
+ }
1020
+ catch (error) {
1021
+ if (error instanceof CliError && error.code === "approval_mismatch") {
1022
+ 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);
1023
+ }
1024
+ throw error;
1025
+ }
1026
+ }
787
1027
  async function cleanupPlannerUpload(api, conversationId, signed, includeDelete) {
788
1028
  if (signed.kind === "multipart") {
789
1029
  await api.client
@@ -1452,6 +1692,122 @@ function parseGoalTemplateDocument(doc) {
1452
1692
  : { outputTemplate: optionalDocString(doc, "outputTemplate") }),
1453
1693
  };
1454
1694
  }
1695
+ /**
1696
+ * Validate the WHOLE template document, not just its spec, so slug clashes and
1697
+ * title/emoji/coin limits surface here instead of after approval on create. A
1698
+ * server that predates whole-document checks strips the extra fields (its body
1699
+ * schema is non-strict) and still validates the spec. The server's structured
1700
+ * `{path, message}` errors and warnings print as `path: message` lines.
1701
+ * `specOnly` skips the document checks (slug availability included).
1702
+ */
1703
+ async function validateGoalTemplateDocument(api, document, options = {}) {
1704
+ const result = unwrap(await api.client.POST("/ai/goal-templates/validate-spec", {
1705
+ body: options.specOnly
1706
+ ? { setupWorkflowSpec: document.setupWorkflowSpec, kind: document.kind }
1707
+ : { ...document },
1708
+ }));
1709
+ // Older servers omit the warnings array; the line formatter tolerates that.
1710
+ const warnings = specValidationErrorLines({
1711
+ errors: result.warnings ?? [],
1712
+ });
1713
+ if (result.valid) {
1714
+ return { ...result, errors: specValidationErrorLines(result), warnings };
1715
+ }
1716
+ const errors = specValidationErrorLines(result);
1717
+ return {
1718
+ ...result,
1719
+ errors: errors.length ? errors : [result.error],
1720
+ warnings,
1721
+ };
1722
+ }
1723
+ /**
1724
+ * Bring a clean, fully pushed checkout up to the remote workspace tip as one
1725
+ * local commit, then advance its metadata. Capture writes lesson `Item key`
1726
+ * lines back into the source workspace; without this the next push from the
1727
+ * same checkout is refused as STALE_WORKSPACE.
1728
+ */
1729
+ async function syncCheckoutFromRemote(api, checkout) {
1730
+ const root = checkout.root;
1731
+ if ((await runGit(root, ["status", "--porcelain=v1"])).trim()) {
1732
+ throw new CliError("uncommitted_changes", "The checkout gained local changes during capture; its metadata was left unchanged.");
1733
+ }
1734
+ const { snapshot } = await readRemoteWorkspaceSnapshot(api, checkout.metadata.studentId, checkout.metadata.target);
1735
+ const remotePaths = new Set(snapshot.files.map((file) => file.path));
1736
+ const changedFiles = [];
1737
+ for (const file of snapshot.files) {
1738
+ const destination = resolveWorkspaceCheckoutPath(root, file.path);
1739
+ const bytes = Buffer.from(file.content, file.contentEncoding === "base64" ? "base64" : "utf8");
1740
+ if (createHash("sha256").update(bytes).digest("hex") !== file.sha256) {
1741
+ throw new CliError("invalid_workspace", `Mesa snapshot integrity check failed for ${file.path}.`);
1742
+ }
1743
+ const local = await fs.readFile(destination).catch(() => null);
1744
+ if (local && local.equals(bytes))
1745
+ continue;
1746
+ await fs.mkdir(path.dirname(destination), { recursive: true });
1747
+ await fs.writeFile(destination, bytes);
1748
+ changedFiles.push(file.path);
1749
+ }
1750
+ const tracked = (await runGit(root, ["ls-files", "-z"]))
1751
+ .split("\0")
1752
+ .filter(Boolean);
1753
+ const deletedFiles = tracked.filter((file) => !remotePaths.has(file));
1754
+ for (const file of deletedFiles) {
1755
+ await fs.rm(resolveWorkspaceCheckoutPath(root, file), { force: true });
1756
+ }
1757
+ if (changedFiles.length > 0 || deletedFiles.length > 0) {
1758
+ await runGit(root, ["add", "-A"]);
1759
+ await runGit(root, [
1760
+ "commit",
1761
+ "--quiet",
1762
+ "-m",
1763
+ `Sync Recess ${checkout.metadata.target.kind} workspace at ${snapshot.changeId}`,
1764
+ ], { identity: true });
1765
+ }
1766
+ const upstreamCommit = (await runGit(root, ["rev-parse", "HEAD"])).trim();
1767
+ await writeRecessGitMetadata(root, {
1768
+ ...checkout.metadata,
1769
+ changeId: snapshot.changeId,
1770
+ upstreamCommit,
1771
+ });
1772
+ return {
1773
+ directory: root,
1774
+ changeId: snapshot.changeId,
1775
+ upstreamCommit,
1776
+ changedFiles,
1777
+ deletedFiles,
1778
+ };
1779
+ }
1780
+ /** Every tracked file of a clean checkout, as text, for local validation. */
1781
+ async function readCheckoutTree(root) {
1782
+ const tracked = (await runGit(root, ["ls-files", "-z"]))
1783
+ .split("\0")
1784
+ .filter(Boolean);
1785
+ return Promise.all(tracked.map(async (file) => ({
1786
+ path: file,
1787
+ content: await fs.readFile(resolveWorkspaceCheckoutPath(root, file), "utf8"),
1788
+ })));
1789
+ }
1790
+ /**
1791
+ * The draft's validation verdict after this change: the server's when its dry
1792
+ * run reports one, else the local mirror over the resulting tree. Reported,
1793
+ * never enforced — a draft is work in progress; create/capture enforce.
1794
+ */
1795
+ async function draftWorkspaceValidation(preflight, resultingTree) {
1796
+ return (serverWorkspaceValidation(preflight) ??
1797
+ validateGoalWorkspaceLocally(await resultingTree()));
1798
+ }
1799
+ async function studentFlag(api, parsed, options = {}) {
1800
+ const value = flagString(parsed, "student", {
1801
+ required: options.required ?? false,
1802
+ });
1803
+ return value === undefined ? undefined : resolveStudentReference(api, value);
1804
+ }
1805
+ /** Preview details naming a student that was resolved from a name. */
1806
+ function resolvedStudentDetails(student) {
1807
+ return student?.name
1808
+ ? { resolvedStudent: { id: student.id, name: student.name } }
1809
+ : {};
1810
+ }
1455
1811
  /**
1456
1812
  * Resolve a template reference that may be a UUID or a slug. Slugs are what an
1457
1813
  * author types and what the skill's prose uses; the routes take a UUID only.
@@ -1481,16 +1837,29 @@ async function resolveGoalTemplateId(api, reference) {
1481
1837
  }
1482
1838
  return match.id;
1483
1839
  }
1484
- function requiredExpectedVersion(parsed) {
1840
+ /**
1841
+ * `--expected-version` is optional. When omitted, the template's current
1842
+ * version is read now and pinned into the preview, so the approval fingerprint
1843
+ * changes (and the confirm refuses) if the template moves between preview and
1844
+ * confirm. The flag still pins an older read explicitly.
1845
+ */
1846
+ async function resolveExpectedTemplateVersion(api, parsed, templateId, recovered) {
1485
1847
  const value = flagNumber(parsed, "expected-version");
1486
- if (value === undefined) {
1487
- 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.");
1848
+ if (value !== undefined) {
1849
+ if (!Number.isInteger(value) || value < 1) {
1850
+ throw new CliError("invalid_arguments", "--expected-version must be a positive integer.");
1851
+ }
1852
+ return { expectedVersion: value, pinnedFrom: "flag" };
1488
1853
  }
1489
- if (!Number.isInteger(value) || value < 1) {
1490
- throw new CliError("invalid_arguments", "--expected-version must be a positive integer.");
1854
+ if (recovered !== undefined) {
1855
+ return { expectedVersion: recovered, pinnedFrom: "current" };
1491
1856
  }
1492
- return value;
1857
+ const current = unwrap(await api.client.GET("/ai/goal-templates/{id}", {
1858
+ params: { path: { id: templateId } },
1859
+ }));
1860
+ return { expectedVersion: current.version, pinnedFrom: "current" };
1493
1861
  }
1862
+ 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>.";
1494
1863
  async function readMapScorePdf(filePath) {
1495
1864
  const absolutePath = path.resolve(filePath);
1496
1865
  if (path.extname(absolutePath).toLowerCase() !== ".pdf") {
@@ -1686,7 +2055,9 @@ function cliErrorShape(error) {
1686
2055
  };
1687
2056
  }
1688
2057
  function remoteWriteCommand(argv, structuredInput, store) {
1689
- return async (parsed, preview, execute) => {
2058
+ // Hosted writes stay gated even for WriteOptions.ungated: the hosted
2059
+ // operation store is the only replay channel there.
2060
+ return async (parsed, preview, execute, _options) => {
1690
2061
  const fingerprint = approvalTokenFor({
1691
2062
  ...preview,
1692
2063
  details: {
@@ -1736,6 +2107,9 @@ export async function executeRecessCommand(argv, options = {}) {
1736
2107
  const [noun, verb] = parsed.positionals;
1737
2108
  const commands = buildCommandSchema(HELP);
1738
2109
  const isRemote = options.transport === "remote";
2110
+ if (!isRemote && !options.operationStore) {
2111
+ localInvocations.set(parsed, { argv: [...argv] });
2112
+ }
1739
2113
  if (isRemote &&
1740
2114
  (!options.api || !options.config || !options.operationStore)) {
1741
2115
  throw new CliError("remote_context_required", "Hosted execution requires injected API, configuration, and operation-store adapters.");
@@ -1755,7 +2129,7 @@ export async function executeRecessCommand(argv, options = {}) {
1755
2129
  if (isRemote) {
1756
2130
  throw new CliError("remote_command_unavailable", "The version command is not exposed by the hosted Recess CLI.");
1757
2131
  }
1758
- const unknown = Array.from(parsed.flags.keys()).filter((name) => !["deliver", "json", "version"].includes(name));
2132
+ const unknown = Array.from(parsed.flags.keys()).filter((name) => !["deliver", "json", "no-json", "pretty", "version"].includes(name));
1759
2133
  if (unknown.length > 0) {
1760
2134
  throw new CliError("unknown_flag", `Unknown flag${unknown.length === 1 ? "" : "s"}: ${unknown
1761
2135
  .map((name) => `--${name}`)
@@ -1767,7 +2141,15 @@ export async function executeRecessCommand(argv, options = {}) {
1767
2141
  };
1768
2142
  }
1769
2143
  if (!noun) {
1770
- const unknown = Array.from(parsed.flags.keys()).filter((name) => !["deliver", "help", "json", "profile"].includes(name));
2144
+ const unknown = Array.from(parsed.flags.keys()).filter((name) => ![
2145
+ "all",
2146
+ "deliver",
2147
+ "help",
2148
+ "json",
2149
+ "no-json",
2150
+ "pretty",
2151
+ "profile",
2152
+ ].includes(name));
1771
2153
  if (unknown.length > 0) {
1772
2154
  throw new CliError("unknown_flag", `Unknown flag${unknown.length === 1 ? "" : "s"}: ${unknown
1773
2155
  .map((name) => `--${name}`)
@@ -1779,6 +2161,7 @@ export async function executeRecessCommand(argv, options = {}) {
1779
2161
  return {
1780
2162
  help: scopedHelp(HELP, visibleCommands, [], discovery, {
1781
2163
  remoteOnly: isRemote,
2164
+ all: hasFlag(parsed, "all"),
1782
2165
  }),
1783
2166
  };
1784
2167
  }
@@ -1790,6 +2173,7 @@ export async function executeRecessCommand(argv, options = {}) {
1790
2173
  return {
1791
2174
  help: scopedHelp(HELP, visibleCommands, scope, discovery, {
1792
2175
  remoteOnly: isRemote,
2176
+ all: hasFlag(parsed, "all"),
1793
2177
  }),
1794
2178
  };
1795
2179
  }
@@ -1837,6 +2221,9 @@ export async function executeRecessCommand(argv, options = {}) {
1837
2221
  feedbackUpstreamConfigured: Boolean(process.env.RECESS_CLI_FEEDBACK_ENDPOINT),
1838
2222
  discovery,
1839
2223
  remoteOnly: isRemote,
2224
+ scope: parsed.positionals.slice(1),
2225
+ full: hasFlag(parsed, "full"),
2226
+ help: HELP,
1840
2227
  });
1841
2228
  }
1842
2229
  if (noun === "profile") {
@@ -1911,6 +2298,12 @@ export async function executeRecessCommand(argv, options = {}) {
1911
2298
  return pruneJobs(olderThanDays);
1912
2299
  }
1913
2300
  }
2301
+ if (noun === "confirm") {
2302
+ if (isRemote) {
2303
+ throw new CliError("remote_command_unavailable", "Hosted writes confirm with the same command plus --confirm --operation-key.");
2304
+ }
2305
+ return confirmStagedWrite(parsed, options);
2306
+ }
1914
2307
  if (noun === "feedback") {
1915
2308
  if (verb === "list") {
1916
2309
  const limit = flagNumber(parsed, "limit") ?? 20;
@@ -1940,7 +2333,17 @@ export async function executeRecessCommand(argv, options = {}) {
1940
2333
  }));
1941
2334
  }
1942
2335
  }
2336
+ // Resolved before anything touches the network, so a write missing its
2337
+ // --reason fails without a session refresh or preview read.
2338
+ const requestReason = noun === "auth"
2339
+ ? undefined
2340
+ : noun === "update"
2341
+ ? requireCliRequestReason(flagString(parsed, "reason") ?? "check for a recess CLI update")
2342
+ : resolveRequestReason(parsed, findCommandSchema(commands, parsed.positionals), isRemote);
1943
2343
  const config = options.config ?? (await resolveConfig(flagString(parsed, "profile")));
2344
+ const invocation = localInvocations.get(parsed);
2345
+ if (invocation)
2346
+ invocation.apiOrigin = config.apiOrigin;
1944
2347
  // Renew a refreshable session's 15-minute access cookie before any command
1945
2348
  // that uses it. Sign-in/out commands manage the session themselves. Not
1946
2349
  // fatal here: an offline local command must still run, and an API call
@@ -1950,11 +2353,6 @@ export async function executeRecessCommand(argv, options = {}) {
1950
2353
  noun !== "setup") {
1951
2354
  await ensureFreshSession(config).catch(() => undefined);
1952
2355
  }
1953
- const requestReason = noun === "auth"
1954
- ? undefined
1955
- : noun === "update"
1956
- ? requireCliRequestReason(flagString(parsed, "reason") ?? "check for a recess CLI update")
1957
- : requiredRequestReason(parsed);
1958
2356
  if (noun === "doctor" && isRemote) {
1959
2357
  return {
1960
2358
  transport: "streamable-http-mcp",
@@ -2503,9 +2901,9 @@ export async function executeRecessCommand(argv, options = {}) {
2503
2901
  }
2504
2902
  const tierId = assertChoice(flagString(parsed, "tier", { required: true }), SCHOOL_TIER_IDS, "--tier");
2505
2903
  const proposedSlots = tierSlots(parsed);
2506
- const expectedUpdatedAt = action === "set"
2507
- ? flagString(parsed, "expected-updated-at", { required: true })
2508
- : undefined;
2904
+ // Optional: without it, the updatedAt read for this preview is pinned
2905
+ // into it, so a change before confirm alters the preview and is refused.
2906
+ const expectedUpdatedAt = action === "set" ? flagString(parsed, "expected-updated-at") : undefined;
2509
2907
  if (expectedUpdatedAt !== undefined &&
2510
2908
  Number.isNaN(Date.parse(expectedUpdatedAt))) {
2511
2909
  throw new CliError("invalid_arguments", "--expected-updated-at must be an ISO-8601 timestamp from users tier get.");
@@ -2543,7 +2941,7 @@ export async function executeRecessCommand(argv, options = {}) {
2543
2941
  const body = {
2544
2942
  tierId,
2545
2943
  ...(proposedSlots === undefined ? {} : { slotsPerKid: proposedSlots }),
2546
- expectedUpdatedAt: expectedUpdatedAt,
2944
+ expectedUpdatedAt: expectedUpdatedAt ?? state.updatedAt,
2547
2945
  allowStrand,
2548
2946
  };
2549
2947
  return writeCommand(parsed, {
@@ -2932,6 +3330,24 @@ export async function executeRecessCommand(argv, options = {}) {
2932
3330
  params: { path: { userId } },
2933
3331
  })));
2934
3332
  }
3333
+ if (noun === "students" && verb === "notes") {
3334
+ if (parsed.positionals[2] !== "add") {
3335
+ throw new CliError("invalid_arguments", "Use students notes add.");
3336
+ }
3337
+ const studentId = flagString(parsed, "student", { required: true });
3338
+ const content = flagString(parsed, "text", { required: true }).trim();
3339
+ if (!content) {
3340
+ throw new CliError("invalid_arguments", "--text must not be empty.");
3341
+ }
3342
+ return writeCommand(parsed, {
3343
+ action: "add a guide note to the kid's profile (staff-visible; Rocky reads it as guide context)",
3344
+ target: { studentUserId: studentId },
3345
+ request: { content },
3346
+ }, async () => unwrap(await api.client.POST("/tutor/students/{studentId}/notes", {
3347
+ params: { path: { studentId } },
3348
+ body: { content },
3349
+ })));
3350
+ }
2935
3351
  if (noun === "students" && verb === "upload-map-scores") {
2936
3352
  const studentId = flagString(parsed, "student", { required: true });
2937
3353
  const pdf = await readMapScorePdf(flagString(parsed, "file", { required: true }));
@@ -3040,7 +3456,9 @@ export async function executeRecessCommand(argv, options = {}) {
3040
3456
  const lineItem = flagString(parsed, "line-item", { required: true });
3041
3457
  const method = assertChoice(flagString(parsed, "method", { required: true }), ["refund", "credit", "tokens"], "--method");
3042
3458
  const whoPays = assertChoice(flagString(parsed, "who-pays") ?? "guide", ["guide", "recess"], "--who-pays");
3043
- const reason = flagString(parsed, "reason");
3459
+ // --refund-reason feeds the refund record; --reason (audit) is the
3460
+ // fallback only for older invocations.
3461
+ const reason = flagString(parsed, "refund-reason") ?? flagString(parsed, "reason");
3044
3462
  const amount = flagNumber(parsed, "amount-cents");
3045
3463
  const fullRefund = hasFlag(parsed, "full");
3046
3464
  if (method === "tokens" && (!amount || fullRefund)) {
@@ -3194,7 +3612,9 @@ export async function executeRecessCommand(argv, options = {}) {
3194
3612
  });
3195
3613
  const immediate = hasFlag(parsed, "immediate");
3196
3614
  const restore = hasFlag(parsed, "restore");
3197
- const reason = flagString(parsed, "reason");
3615
+ // --cancel-reason feeds the subscription record; --reason (audit) is the
3616
+ // fallback only for older invocations.
3617
+ const reason = flagString(parsed, "cancel-reason") ?? flagString(parsed, "reason");
3198
3618
  const body = {
3199
3619
  immediate,
3200
3620
  subscriptionId,
@@ -3278,7 +3698,10 @@ export async function executeRecessCommand(argv, options = {}) {
3278
3698
  const removalQuery = zeroBalance
3279
3699
  ? {
3280
3700
  zeroBalance: "true",
3281
- reason: flagString(parsed, "reason", { required: true }),
3701
+ // --zero-balance-reason feeds the payout record; --reason (audit)
3702
+ // is the fallback only for older invocations.
3703
+ reason: flagString(parsed, "zero-balance-reason") ??
3704
+ flagString(parsed, "reason", { required: true }),
3282
3705
  expectedBalanceCents,
3283
3706
  }
3284
3707
  : {};
@@ -3546,6 +3969,23 @@ export async function executeRecessCommand(argv, options = {}) {
3546
3969
  params: { path: { eventId } },
3547
3970
  }));
3548
3971
  }
3972
+ if (noun === "events" && verb === "list") {
3973
+ const date = flagString(parsed, "date");
3974
+ if (!date) {
3975
+ throw new CliError("invalid_arguments", "events list requires --date YYYY-MM-DD.");
3976
+ }
3977
+ const timezone = flagString(parsed, "timezone");
3978
+ const search = flagString(parsed, "search");
3979
+ return unwrap(await api.client.GET("/admin/events/by-date", {
3980
+ params: {
3981
+ query: {
3982
+ date,
3983
+ ...(timezone && { timezone }),
3984
+ ...(search && { search }),
3985
+ },
3986
+ },
3987
+ }));
3988
+ }
3549
3989
  if (noun === "events" && verb === "take-attendance") {
3550
3990
  const eventId = positional(parsed, 2, "event ID");
3551
3991
  const attended = flagIdList(parsed, "attended");
@@ -3591,11 +4031,14 @@ export async function executeRecessCommand(argv, options = {}) {
3591
4031
  }
3592
4032
  if (noun === "events" && verb === "cancel") {
3593
4033
  const eventId = positional(parsed, 2, "event ID");
3594
- const reason = flagString(parsed, "reason", { required: true }).trim();
3595
- if (!reason) {
3596
- throw new CliError("invalid_arguments", "--reason must not be empty.");
3597
- }
3598
- const body = { reason };
4034
+ // Family-facing: the server posts this verbatim to the kids' and parents'
4035
+ // class chats, the class announcement, parent emails, and Slack. --reason
4036
+ // is only the audit-log note, so it is never reused here.
4037
+ const message = flagString(parsed, "message")?.trim();
4038
+ if (!message) {
4039
+ 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" });
4040
+ }
4041
+ const body = { reason: message };
3599
4042
  return writeCommand(parsed, {
3600
4043
  action: "cancel event AND NOTIFY: messages kid + parent channels, emails every registered parent, files credit-owed notes, posts to Slack",
3601
4044
  target: { eventId },
@@ -3960,15 +4403,16 @@ export async function executeRecessCommand(argv, options = {}) {
3960
4403
  if (verb === "validate-spec") {
3961
4404
  const document = parseGoalTemplateDocument(await readTemplateDocument());
3962
4405
  // A read-only validation: no gate, and iterating on it is the whole point.
4406
+ const validation = await validateGoalTemplateDocument(api, document);
3963
4407
  return {
3964
4408
  slug: document.slug,
3965
4409
  kind: document.kind,
3966
- ...unwrap(await api.client.POST("/ai/goal-templates/validate-spec", {
3967
- body: {
3968
- setupWorkflowSpec: document.setupWorkflowSpec,
3969
- kind: document.kind,
3970
- },
3971
- })),
4410
+ ...validation,
4411
+ ...(validation.valid && !("answersTemplate" in validation)
4412
+ ? {
4413
+ answersTemplate: buildAnswersTemplate(document.setupWorkflowSpec, []).answers,
4414
+ }
4415
+ : {}),
3972
4416
  };
3973
4417
  }
3974
4418
  if (verb === "create") {
@@ -3993,14 +4437,21 @@ export async function executeRecessCommand(argv, options = {}) {
3993
4437
  // answer keys `apply` will demand all come out of the spec's own
3994
4438
  // validation — a locally guessed preview could name a different handler
3995
4439
  // than the one that lands. Validation writes nothing.
3996
- const validation = unwrap(await api.client.POST("/ai/goal-templates/validate-spec", {
3997
- body: {
3998
- setupWorkflowSpec: document.setupWorkflowSpec,
3999
- kind: document.kind,
4000
- },
4001
- }));
4440
+ // A confirmed retry of a key that already ran may have created this very
4441
+ // template, and the document check would then call its own slug taken.
4442
+ // It validates the spec alone (the same preview details), so the keyed
4443
+ // create reaches server idempotency; the approval fingerprint still
4444
+ // refuses any changed input.
4445
+ const validation = await validateGoalTemplateDocument(api, document, {
4446
+ specOnly: await operationKeyAttempted(parsed),
4447
+ });
4002
4448
  if (!validation.valid) {
4003
- throw new CliError("invalid_spec", `The setupWorkflowSpec is invalid, so nothing was created: ${validation.error}`, 1, filePath ? { file: path.resolve(filePath) } : { input: "template" });
4449
+ throw new CliError("invalid_spec", `The template is invalid, so nothing was created:\n${validation.errors.join("\n")}`, 1, {
4450
+ ...(filePath
4451
+ ? { file: path.resolve(filePath) }
4452
+ : { input: "template" }),
4453
+ errors: validation.errors,
4454
+ });
4004
4455
  }
4005
4456
  return writeCommand(parsed, {
4006
4457
  action: "create a NEW global goal template (DETERMINISTIC_WORKFLOW — this cannot be converted back)",
@@ -4023,6 +4474,9 @@ export async function executeRecessCommand(argv, options = {}) {
4023
4474
  wizardStepKeys: validation.stepKeys,
4024
4475
  specSha256: validation.sha256,
4025
4476
  specInventory: validation.totals,
4477
+ answersTemplate: "answersTemplate" in validation
4478
+ ? validation.answersTemplate
4479
+ : buildAnswersTemplate(document.setupWorkflowSpec, []).answers,
4026
4480
  note: "Setup mode is DETERMINISTIC_WORKFLOW and is one-way: this template can never be converted back to a chat-driven setup.",
4027
4481
  },
4028
4482
  }, async () => {
@@ -4061,6 +4515,15 @@ export async function executeRecessCommand(argv, options = {}) {
4061
4515
  }
4062
4516
  if (target === undefined && minimum === undefined)
4063
4517
  throw new CliError("invalid_arguments", "Provide --target-modules or --required-modules N|all");
4518
+ // A retry after the policy write landed must reuse the approved
4519
+ // version, not the one that write just bumped it to.
4520
+ const executed = await readExecutedPreview(parsed);
4521
+ const executedVersion = executed?.action ===
4522
+ "edit shared goal-template assigned target or completion minimum" &&
4523
+ typeof executed.request.expectedVersion === "number"
4524
+ ? executed.request.expectedVersion
4525
+ : undefined;
4526
+ const { expectedVersion } = await resolveExpectedTemplateVersion(api, parsed, id, executedVersion);
4064
4527
  const body = {
4065
4528
  recipeKey: flagString(parsed, "recipe", { required: true }),
4066
4529
  ...(target === undefined ? {} : { targetModuleCount: Number(target) }),
@@ -4069,7 +4532,7 @@ export async function executeRecessCommand(argv, options = {}) {
4069
4532
  : {
4070
4533
  requiredModuleCount: minimum === "all" ? null : Number(minimum),
4071
4534
  }),
4072
- expectedVersion: requiredExpectedVersion(parsed),
4535
+ expectedVersion,
4073
4536
  };
4074
4537
  const requestPreview = {
4075
4538
  action: "edit shared goal-template assigned target or completion minimum",
@@ -4208,7 +4671,7 @@ export async function executeRecessCommand(argv, options = {}) {
4208
4671
  }
4209
4672
  if (verb === "patch-spec") {
4210
4673
  const id = await resolveGoalTemplateId(api, positional(parsed, 2, "template ID or slug"));
4211
- const expectedVersion = requiredExpectedVersion(parsed);
4674
+ const { expectedVersion, pinnedFrom } = await resolveExpectedTemplateVersion(api, parsed, id);
4212
4675
  const patchFile = await readGoalTemplateSpecPatches(flagString(parsed, "patches-file", { required: true }));
4213
4676
  // The server owns JSON Pointer semantics, strict final-spec validation,
4214
4677
  // protected-inventory counting, and the token binding the approved loss
@@ -4243,6 +4706,9 @@ export async function executeRecessCommand(argv, options = {}) {
4243
4706
  patches: patchFile.patches,
4244
4707
  },
4245
4708
  details: {
4709
+ ...(pinnedFrom === "current"
4710
+ ? { expectedVersionNote: PINNED_VERSION_NOTE }
4711
+ : {}),
4246
4712
  patchesApplied: preflight.patchesApplied,
4247
4713
  safety: preflight.preview,
4248
4714
  ...(preflight.preview.destructiveChanges
@@ -4283,7 +4749,7 @@ export async function executeRecessCommand(argv, options = {}) {
4283
4749
  }
4284
4750
  if (verb === "set-metadata") {
4285
4751
  const id = await resolveGoalTemplateId(api, positional(parsed, 2, "template ID or slug"));
4286
- const expectedVersion = requiredExpectedVersion(parsed);
4752
+ const { expectedVersion, pinnedFrom } = await resolveExpectedTemplateVersion(api, parsed, id);
4287
4753
  const agentInstructionsFile = flagString(parsed, "agent-instructions-file");
4288
4754
  const outputTemplateFile = flagString(parsed, "output-template-file");
4289
4755
  const tags = flagString(parsed, "tags");
@@ -4295,6 +4761,7 @@ export async function executeRecessCommand(argv, options = {}) {
4295
4761
  throw new CliError("invalid_arguments", "--coin-amount must be a positive integer.");
4296
4762
  }
4297
4763
  const visibility = flagString(parsed, "visibility");
4764
+ const targetPlatform = flagString(parsed, "target-platform");
4298
4765
  const isStarterRaw = flagString(parsed, "is-starter");
4299
4766
  const setupAudienceRaw = flagString(parsed, "setup-audience");
4300
4767
  const isStarter = isStarterRaw === undefined
@@ -4341,6 +4808,11 @@ export async function executeRecessCommand(argv, options = {}) {
4341
4808
  visibility: assertChoice(visibility, ["PUBLIC", "PRIVATE", "STAFF_ONLY"], "--visibility"),
4342
4809
  }
4343
4810
  : {}),
4811
+ ...(targetPlatform
4812
+ ? {
4813
+ targetPlatform: assertChoice(targetPlatform.toUpperCase(), ["ANY", "MOBILE", "DESKTOP"], "--target-platform"),
4814
+ }
4815
+ : {}),
4344
4816
  ...(agentInstructionsFile
4345
4817
  ? {
4346
4818
  agentInstructions: await fs.readFile(path.resolve(agentInstructionsFile), "utf8"),
@@ -4357,12 +4829,15 @@ export async function executeRecessCommand(argv, options = {}) {
4357
4829
  // shape that caused the template incident; editing an existing spec goes
4358
4830
  // through the guarded /ai patch path with its destructive-change token.
4359
4831
  if (Object.keys(body).length === 1) {
4360
- throw new CliError("invalid_arguments", "Pass at least one field to change (--title, --description, --emoji, --image-url, --coin-amount, --category, --tags, --sort-order, --is-starter, --setup-audience, --kind, --visibility, --agent-instructions-file, --output-template-file).");
4832
+ throw new CliError("invalid_arguments", "Pass at least one field to change (--title, --description, --emoji, --image-url, --coin-amount, --category, --tags, --sort-order, --is-starter, --setup-audience, --kind, --visibility, --target-platform, --agent-instructions-file, --output-template-file).");
4361
4833
  }
4362
4834
  return writeCommand(parsed, {
4363
4835
  action: "update goal template metadata (never its setupWorkflowSpec)",
4364
4836
  target: { templateId: id, expectedVersion },
4365
4837
  request: body,
4838
+ ...(pinnedFrom === "current"
4839
+ ? { details: { expectedVersionNote: PINNED_VERSION_NOTE } }
4840
+ : {}),
4366
4841
  }, async () => unwrap(await api.client.PUT("/ai/goal-templates/{id}", {
4367
4842
  params: { path: { id } },
4368
4843
  body,
@@ -4392,13 +4867,14 @@ export async function executeRecessCommand(argv, options = {}) {
4392
4867
  }
4393
4868
  if (verb === "delete") {
4394
4869
  const id = await resolveGoalTemplateId(api, positional(parsed, 2, "template ID or slug"));
4395
- const expectedVersion = requiredExpectedVersion(parsed);
4396
4870
  // Read the current version so the gate refuses a stale delete locally,
4397
4871
  // and so the preview names the template a human is being asked to approve
4398
- // rather than only its UUID.
4872
+ // rather than only its UUID. Without --expected-version the version read
4873
+ // here is pinned into the preview instead.
4399
4874
  const current = unwrap(await api.client.GET("/ai/goal-templates/{id}", {
4400
4875
  params: { path: { id } },
4401
4876
  }));
4877
+ const { expectedVersion } = await resolveExpectedTemplateVersion(api, parsed, id, current.version);
4402
4878
  if (current.version !== expectedVersion) {
4403
4879
  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 });
4404
4880
  }
@@ -4445,14 +4921,17 @@ export async function executeRecessCommand(argv, options = {}) {
4445
4921
  const checkoutHead = checkout
4446
4922
  ? await assertCheckoutReadyForMaterialization(checkout)
4447
4923
  : null;
4448
- const requestedSourceStudentId = flagString(parsed, "student");
4924
+ const requestedSourceStudent = await studentFlag(api, parsed, {
4925
+ required: Boolean(sourceDraft),
4926
+ });
4927
+ const requestedSourceStudentId = requestedSourceStudent?.id;
4449
4928
  if (checkout &&
4450
4929
  requestedSourceStudentId &&
4451
4930
  requestedSourceStudentId !== checkout.metadata.studentId) {
4452
4931
  throw new CliError("invalid_arguments", `--student ${requestedSourceStudentId} does not match checkout owner ${checkout.metadata.studentId}.`);
4453
4932
  }
4454
4933
  const sourceStudentUserId = sourceDraft
4455
- ? flagString(parsed, "student", { required: true })
4934
+ ? requestedSourceStudentId
4456
4935
  : checkout?.metadata.studentId;
4457
4936
  let source;
4458
4937
  if (sourceGoalId) {
@@ -4513,19 +4992,95 @@ export async function executeRecessCommand(argv, options = {}) {
4513
4992
  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.",
4514
4993
  },
4515
4994
  };
4516
- return previewBoundWrite(parsed, preview, async () => unwrap(await api.client.POST("/ai/goal-templates/{id}/snapshot/capture", {
4517
- params: { path: { id } },
4518
- body: {
4519
- ...source,
4520
- dryRun: false,
4521
- expectedTemplateVersion: preflight.template.version,
4522
- expectedSourceChangeId: preflight.source.changeId,
4523
- },
4524
- })));
4995
+ return previewBoundWrite(parsed, preview, async () => {
4996
+ const result = unwrap(await api.client.POST("/ai/goal-templates/{id}/snapshot/capture", {
4997
+ params: { path: { id } },
4998
+ body: {
4999
+ ...source,
5000
+ dryRun: false,
5001
+ expectedTemplateVersion: preflight.template.version,
5002
+ expectedSourceChangeId: preflight.source.changeId,
5003
+ },
5004
+ }));
5005
+ const sourceChangeId = "sourceChangeId" in result &&
5006
+ typeof result.sourceChangeId === "string"
5007
+ ? result.sourceChangeId
5008
+ : null;
5009
+ if (!checkout ||
5010
+ !sourceChangeId ||
5011
+ sourceChangeId === checkout.metadata.changeId) {
5012
+ return result;
5013
+ }
5014
+ // Capture committed lesson identities back to the source workspace.
5015
+ // Pull them so the checkout can keep pushing.
5016
+ try {
5017
+ return {
5018
+ ...result,
5019
+ local: {
5020
+ synced: true,
5021
+ ...(await syncCheckoutFromRemote(api, checkout)),
5022
+ },
5023
+ };
5024
+ }
5025
+ catch (error) {
5026
+ return {
5027
+ ...result,
5028
+ local: {
5029
+ synced: false,
5030
+ directory: checkout.root,
5031
+ error: error instanceof Error ? error.message : String(error),
5032
+ next: "Capture changed the source workspace. Check it out again (goals files checkout) before the next push.",
5033
+ },
5034
+ };
5035
+ }
5036
+ });
5037
+ }
5038
+ // `--student` takes IDs or exact roster names, comma-separated.
5039
+ const resolveStudentList = async () => Promise.all((flagString(parsed, "student") ?? "")
5040
+ .split(",")
5041
+ .map((value) => value.trim())
5042
+ .filter(Boolean)
5043
+ .map((value) => resolveStudentReference(api, value)));
5044
+ if (verb === "answers-template") {
5045
+ const id = await resolveGoalTemplateId(api, positional(parsed, 2, "template ID or slug"));
5046
+ const [template, students] = await Promise.all([
5047
+ api.client.GET("/ai/goal-templates/{id}", { params: { path: { id } } }),
5048
+ resolveStudentList(),
5049
+ ]);
5050
+ const current = unwrap(template);
5051
+ const skeleton = buildAnswersTemplate(current.setupWorkflowSpec, students.map((student) => student.id));
5052
+ return {
5053
+ templateId: current.id,
5054
+ slug: current.slug,
5055
+ version: current.version,
5056
+ answers: skeleton.answers,
5057
+ placeholders: skeleton.placeholders,
5058
+ steps: skeleton.steps,
5059
+ next: skeleton.placeholders.length > 0
5060
+ ? `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.`
5061
+ : `Save the answers to a file, or run goal-templates apply ${current.slug} --student <kid> --dry-run directly.`,
5062
+ };
4525
5063
  }
4526
5064
  if (verb === "apply") {
4527
5065
  const id = await resolveGoalTemplateId(api, positional(parsed, 2, "template ID or slug"));
4528
- const answers = await readJsonFile(flagString(parsed, "answers-file", { required: true }), "Answers file");
5066
+ const answersFile = flagString(parsed, "answers-file");
5067
+ const students = await resolveStudentList();
5068
+ if (!answersFile && students.length === 0) {
5069
+ 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.");
5070
+ }
5071
+ let answers = answersFile
5072
+ ? await readJsonFile(answersFile, "Answers file")
5073
+ : {};
5074
+ if (students.length > 0) {
5075
+ const template = unwrap(await api.client.GET("/ai/goal-templates/{id}", {
5076
+ params: { path: { id } },
5077
+ }));
5078
+ const filled = applyStudentsToAnswers(template.setupWorkflowSpec, answers, students.map((student) => student.id));
5079
+ if (filled.missingRequired.length > 0) {
5080
+ 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 });
5081
+ }
5082
+ answers = filled.answers;
5083
+ }
4529
5084
  // `--dry-run` is a read: it resolves the whole plan and writes nothing,
4530
5085
  // so it does not gate. Run it, read the per-student results, then confirm.
4531
5086
  if (hasFlag(parsed, "dry-run")) {
@@ -4551,6 +5106,14 @@ export async function executeRecessCommand(argv, options = {}) {
4551
5106
  target: { templateId: id, students: preflight.results.length },
4552
5107
  request: { answers },
4553
5108
  details: {
5109
+ ...(students.some((student) => student.name)
5110
+ ? {
5111
+ resolvedStudents: students.map(({ id, name }) => ({
5112
+ id,
5113
+ name,
5114
+ })),
5115
+ }
5116
+ : {}),
4554
5117
  counts,
4555
5118
  results: preflight.results.map((result) => ({
4556
5119
  student: result.studentName,
@@ -4576,7 +5139,8 @@ export async function executeRecessCommand(argv, options = {}) {
4576
5139
  }
4577
5140
  if (verb === "apply-starter") {
4578
5141
  const id = await resolveGoalTemplateId(api, positional(parsed, 2, "template ID or slug"));
4579
- const studentUserId = flagString(parsed, "student", { required: true });
5142
+ const student = await studentFlag(api, parsed, { required: true });
5143
+ const studentUserId = student.id;
4580
5144
  const answersFile = flagString(parsed, "answers-file");
4581
5145
  const answers = answersFile
4582
5146
  ? await readJsonFile(answersFile, "Answers file")
@@ -4589,6 +5153,7 @@ export async function executeRecessCommand(argv, options = {}) {
4589
5153
  target: { templateId: id, studentUserId },
4590
5154
  request: { answers },
4591
5155
  details: {
5156
+ ...resolvedStudentDetails(student),
4592
5157
  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.",
4593
5158
  },
4594
5159
  }, async () => unwrap(await api.client.POST("/ai/goal-templates/{id}/apply-starter", {
@@ -4596,11 +5161,12 @@ export async function executeRecessCommand(argv, options = {}) {
4596
5161
  body: { studentUserId, answers },
4597
5162
  })));
4598
5163
  }
4599
- 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.");
5164
+ 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.");
4600
5165
  }
4601
5166
  if (noun === "goals" && verb === "adaptations") {
4602
5167
  const action = positional(parsed, 2, "goals adaptations action");
4603
- const studentId = flagString(parsed, "student", { required: true });
5168
+ const student = await studentFlag(api, parsed, { required: true });
5169
+ const studentId = student.id;
4604
5170
  const goalId = flagString(parsed, "goal", { required: true });
4605
5171
  if (action === "list") {
4606
5172
  return unwrap(await api.client.GET("/tutor/students/{studentId}/goals/{goalId}/adaptations", { params: { path: { studentId, goalId } } }));
@@ -4645,7 +5211,8 @@ export async function executeRecessCommand(argv, options = {}) {
4645
5211
  }
4646
5212
  if (verb === "archive" || verb === "unarchive") {
4647
5213
  const goalId = positional(parsed, 2, "goal ID");
4648
- const studentId = flagString(parsed, "student", { required: true });
5214
+ const student = await studentFlag(api, parsed, { required: true });
5215
+ const studentId = student.id;
4649
5216
  const reopen = verb === "unarchive";
4650
5217
  const current = unwrap(await api.client.GET("/tutor/browser/students/{userId}/goals/", {
4651
5218
  params: { path: { userId: studentId } },
@@ -4675,6 +5242,7 @@ export async function executeRecessCommand(argv, options = {}) {
4675
5242
  },
4676
5243
  request: { goalId },
4677
5244
  details: {
5245
+ ...resolvedStudentDetails(student),
4678
5246
  note: reopen
4679
5247
  ? "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)."
4680
5248
  : "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`.",
@@ -4689,7 +5257,8 @@ export async function executeRecessCommand(argv, options = {}) {
4689
5257
  })));
4690
5258
  }
4691
5259
  if (verb === "list") {
4692
- const userId = flagString(parsed, "student", { required: true });
5260
+ const student = await studentFlag(api, parsed, { required: true });
5261
+ const userId = student.id;
4693
5262
  const result = unwrap(await api.client.GET("/tutor/browser/students/{userId}/goals/", {
4694
5263
  params: { path: { userId } },
4695
5264
  }));
@@ -4712,7 +5281,8 @@ export async function executeRecessCommand(argv, options = {}) {
4712
5281
  // no retiring the work they have already done, nobody else's goal touched.
4713
5282
  if (verb === "move-module") {
4714
5283
  const moduleRef = positional(parsed, 2, "module ref (e.g. Q006)");
4715
- const studentId = flagString(parsed, "student", { required: true });
5284
+ const student = await studentFlag(api, parsed, { required: true });
5285
+ const studentId = student.id;
4716
5286
  const goalId = flagString(parsed, "goal", { required: true });
4717
5287
  const toEnd = hasFlag(parsed, "to-end");
4718
5288
  const position = flagNumber(parsed, "position");
@@ -4750,6 +5320,7 @@ export async function executeRecessCommand(argv, options = {}) {
4750
5320
  },
4751
5321
  request: { moduleId: target.id, ordinal },
4752
5322
  details: {
5323
+ ...resolvedStudentDetails(student),
4753
5324
  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.",
4754
5325
  ...(collision
4755
5326
  ? {
@@ -4766,7 +5337,8 @@ export async function executeRecessCommand(argv, options = {}) {
4766
5337
  })));
4767
5338
  }
4768
5339
  if (verb === "create") {
4769
- const requestedStudentId = flagString(parsed, "student");
5340
+ const requestedStudent = await studentFlag(api, parsed);
5341
+ const requestedStudentId = requestedStudent?.id;
4770
5342
  const sourceDirectory = flagString(parsed, "source-dir");
4771
5343
  const explicitDraftSlug = flagString(parsed, "draft");
4772
5344
  if (sourceDirectory && explicitDraftSlug) {
@@ -4858,6 +5430,7 @@ export async function executeRecessCommand(argv, options = {}) {
4858
5430
  : {}),
4859
5431
  },
4860
5432
  details: {
5433
+ ...resolvedStudentDetails(requestedStudent),
4861
5434
  currentChangeId: preflight.currentChangeId,
4862
5435
  workspaceSha256: preflight.workspaceSha256,
4863
5436
  fileCount: preflight.fileCount,
@@ -4915,6 +5488,7 @@ export async function executeRecessCommand(argv, options = {}) {
4915
5488
  schedule: schedule ?? null,
4916
5489
  },
4917
5490
  details: {
5491
+ ...resolvedStudentDetails(requestedStudent),
4918
5492
  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.",
4919
5493
  },
4920
5494
  }, async () => unwrap(await api.client.POST("/tutor/browser/students/{userId}/goals/", {
@@ -4924,7 +5498,8 @@ export async function executeRecessCommand(argv, options = {}) {
4924
5498
  }
4925
5499
  if (verb === "edit") {
4926
5500
  const goalId = positional(parsed, 2, "goal ID");
4927
- const studentId = flagString(parsed, "student", { required: true });
5501
+ const student = await studentFlag(api, parsed, { required: true });
5502
+ const studentId = student.id;
4928
5503
  const patchFile = flagString(parsed, "patch-file", { required: true });
4929
5504
  const patch = (await readJsonFile(patchFile, "Goal patch file"));
4930
5505
  assertGoalPatchValues(patch, patchFile);
@@ -4944,6 +5519,7 @@ export async function executeRecessCommand(argv, options = {}) {
4944
5519
  expectedUpdatedAt: current.updatedAt,
4945
5520
  patch,
4946
5521
  },
5522
+ details: resolvedStudentDetails(student),
4947
5523
  };
4948
5524
  return previewBoundWrite(parsed, preview, async () => unwrap(await api.client.PATCH("/tutor/browser/students/goals/{goalId}/", {
4949
5525
  params: { path: { goalId } },
@@ -4952,7 +5528,8 @@ export async function executeRecessCommand(argv, options = {}) {
4952
5528
  }
4953
5529
  if (verb === "delete") {
4954
5530
  const goalId = positional(parsed, 2, "goal ID");
4955
- const studentId = flagString(parsed, "student", { required: true });
5531
+ const student = await studentFlag(api, parsed, { required: true });
5532
+ const studentId = student.id;
4956
5533
  // Deletion is an /admin/* route, so a guardian or guide session can never
4957
5534
  // complete it. Refuse here, before the preview, rather than rendering a
4958
5535
  // full and entirely plausible preview — resolved goal, named title,
@@ -4978,6 +5555,7 @@ export async function executeRecessCommand(argv, options = {}) {
4978
5555
  },
4979
5556
  request: { expectedUpdatedAt: current.updatedAt },
4980
5557
  details: {
5558
+ ...resolvedStudentDetails(student),
4981
5559
  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.",
4982
5560
  },
4983
5561
  };
@@ -4990,7 +5568,8 @@ export async function executeRecessCommand(argv, options = {}) {
4990
5568
  }
4991
5569
  if (verb === "restore") {
4992
5570
  const goalId = positional(parsed, 2, "goal ID");
4993
- const studentId = flagString(parsed, "student", { required: true });
5571
+ const student = await studentFlag(api, parsed, { required: true });
5572
+ const studentId = student.id;
4994
5573
  const sessionRole = await resolveSessionRole(api);
4995
5574
  if (sessionRole && sessionRole !== "ADMIN") {
4996
5575
  throw new CliError("forbidden", "Restoring a deleted goal is admin-only.", 1, { sessionRole, requiredRole: "ADMIN" });
@@ -5016,6 +5595,7 @@ export async function executeRecessCommand(argv, options = {}) {
5016
5595
  },
5017
5596
  request: body,
5018
5597
  details: {
5598
+ ...resolvedStudentDetails(student),
5019
5599
  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.",
5020
5600
  },
5021
5601
  };
@@ -5024,7 +5604,8 @@ export async function executeRecessCommand(argv, options = {}) {
5024
5604
  if (verb === "queue") {
5025
5605
  const subverb = positional(parsed, 2, "queue action (get|set)");
5026
5606
  const goalId = positional(parsed, 3, "goal ID");
5027
- const studentId = flagString(parsed, "student", { required: true });
5607
+ const student = await studentFlag(api, parsed, { required: true });
5608
+ const studentId = student.id;
5028
5609
  if (subverb === "get") {
5029
5610
  return unwrap(await api.client.GET("/tutor/browser/students/goals/{goalId}/queue/", { params: { path: { goalId } } }));
5030
5611
  }
@@ -5077,6 +5658,7 @@ export async function executeRecessCommand(argv, options = {}) {
5077
5658
  unchangedTitleForConcurrencyFence: goal.title,
5078
5659
  },
5079
5660
  details: {
5661
+ ...resolvedStudentDetails(student),
5080
5662
  currentQueue: current.queue.map((item) => ({
5081
5663
  moduleRef: item.moduleRef,
5082
5664
  url: item.url,
@@ -5129,6 +5711,9 @@ export async function executeRecessCommand(argv, options = {}) {
5129
5711
  if (noun === "rooms") {
5130
5712
  return runRoomsCommand({ parsed, api, writeCommand });
5131
5713
  }
5714
+ if (noun === "feed") {
5715
+ return runFeedCommand({ parsed, api, writeCommand });
5716
+ }
5132
5717
  if (noun === "students" && verb === "texts") {
5133
5718
  return runStudentsTextsCommand({ parsed, api, writeCommand });
5134
5719
  }
@@ -5204,20 +5789,7 @@ export async function executeRecessCommand(argv, options = {}) {
5204
5789
  }
5205
5790
  const cursor = flagString(parsed, "cursor");
5206
5791
  const limit = flagNumber(parsed, "limit");
5207
- let studentId = student;
5208
- if (!/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i.test(student)) {
5209
- const roster = unwrap(await api.client.GET("/tutor/students", {
5210
- params: { query: { scope: "mine" } },
5211
- }));
5212
- const normalize = (name) => name.trim().replace(/\s+/g, " ").toLowerCase();
5213
- const matches = roster.items.filter((item) => normalize(item.name) === normalize(student));
5214
- if (matches.length !== 1) {
5215
- throw new CliError(matches.length ? "ambiguous_student" : "student_not_found", matches.length
5216
- ? "Multiple students have that name. Ask which student, then retry with their ID."
5217
- : "No exact name match in your roster. Use students list to find the student's ID.", 1, { matches: matches.map(({ userId, name }) => ({ userId, name })) });
5218
- }
5219
- studentId = matches[0].userId;
5220
- }
5792
+ const studentId = (await resolveStudentReference(api, student)).id;
5221
5793
  return unwrap(await api.client.GET("/studio/students/{studentId}/todos", {
5222
5794
  params: {
5223
5795
  path: { studentId },
@@ -5261,7 +5833,8 @@ export async function executeRecessCommand(argv, options = {}) {
5261
5833
  }
5262
5834
  if (noun === "todos") {
5263
5835
  if (verb === "create") {
5264
- const studentId = flagString(parsed, "student", { required: true });
5836
+ const student = await studentFlag(api, parsed, { required: true });
5837
+ const studentId = student.id;
5265
5838
  const title = flagString(parsed, "title", { required: true });
5266
5839
  const targetDurationInMins = flagNumber(parsed, "target-minutes");
5267
5840
  const body = {
@@ -5279,6 +5852,7 @@ export async function executeRecessCommand(argv, options = {}) {
5279
5852
  action: "create a todo for a managed student",
5280
5853
  target: { studentUserId: studentId },
5281
5854
  request: body,
5855
+ details: resolvedStudentDetails(student),
5282
5856
  }, async () => unwrap(await api.client.POST("/tutor/browser/todos/", { body })));
5283
5857
  }
5284
5858
  if (verb === "edit") {
@@ -5476,7 +6050,8 @@ export async function executeRecessCommand(argv, options = {}) {
5476
6050
  }
5477
6051
  if (verb === "generate-applet") {
5478
6052
  const todoId = positional(parsed, 2, "todo ID");
5479
- const studentId = flagString(parsed, "student", { required: true });
6053
+ const student = await studentFlag(api, parsed, { required: true });
6054
+ const studentId = student.id;
5480
6055
  const targetDueDateISO = flagDateOnly(parsed, "due-date");
5481
6056
  const [todo, learningAnalysis] = await Promise.all([
5482
6057
  api.client.GET("/tutor/browser/todos/{id}/", {
@@ -5518,7 +6093,8 @@ export async function executeRecessCommand(argv, options = {}) {
5518
6093
  throw new CliError("invalid_arguments", "Use todos create|edit|complete|delete|restore|generate-learning-analysis|generate-applet.");
5519
6094
  }
5520
6095
  if (noun === "memories") {
5521
- const studentId = flagString(parsed, "student", { required: true });
6096
+ const student = await studentFlag(api, parsed, { required: true });
6097
+ const studentId = student.id;
5522
6098
  if (verb === "context") {
5523
6099
  return unwrap(await api.client.GET("/tutor/students/{studentId}/prompt-memory", {
5524
6100
  params: { path: { studentId } },
@@ -5542,10 +6118,17 @@ export async function executeRecessCommand(argv, options = {}) {
5542
6118
  if (verb === "set") {
5543
6119
  const patchFile = flagString(parsed, "patch-file", { required: true });
5544
6120
  const patch = (await readJsonFile(patchFile, "Rocky config patch file"));
5545
- const expected = flagString(parsed, "expected-updated-at", {
5546
- required: true,
5547
- });
5548
- const expectedUpdatedAt = expected === "none" ? null : expected;
6121
+ // Optional: without it, the config's current updatedAt (null when the
6122
+ // student has none yet) is read now and pinned into the preview, so a
6123
+ // change before confirm alters the preview and the confirm is refused.
6124
+ const expected = flagString(parsed, "expected-updated-at");
6125
+ const expectedUpdatedAt = expected === undefined
6126
+ ? unwrap(await api.client.GET("/tutor/students/{studentId}/rocky-config", {
6127
+ params: { path: { studentId } },
6128
+ })).updatedAt
6129
+ : expected === "none"
6130
+ ? null
6131
+ : expected;
5549
6132
  if (expectedUpdatedAt !== null &&
5550
6133
  Number.isNaN(Date.parse(expectedUpdatedAt))) {
5551
6134
  throw new CliError("invalid_arguments", "--expected-updated-at must be an ISO datetime from `rocky get`, or `none`.");
@@ -5778,7 +6361,8 @@ export async function executeRecessCommand(argv, options = {}) {
5778
6361
  if (action !== "upload") {
5779
6362
  throw new CliError("invalid_arguments", "Use goals pdf upload.");
5780
6363
  }
5781
- const studentId = flagString(parsed, "student", { required: true });
6364
+ const student = await studentFlag(api, parsed, { required: true });
6365
+ const studentId = student.id;
5782
6366
  const goalId = flagString(parsed, "goal");
5783
6367
  const draftSlug = flagString(parsed, "draft");
5784
6368
  if (Boolean(goalId) === Boolean(draftSlug)) {
@@ -5843,6 +6427,7 @@ export async function executeRecessCommand(argv, options = {}) {
5843
6427
  message,
5844
6428
  },
5845
6429
  details: {
6430
+ ...resolvedStudentDetails(student),
5846
6431
  currentChangeId: preflight.currentChangeId,
5847
6432
  note: "The PDF is stored separately and the goal workspace receives a small verified reference, matching planner-authored textbook goals.",
5848
6433
  },
@@ -5943,17 +6528,21 @@ export async function executeRecessCommand(argv, options = {}) {
5943
6528
  workspacePath,
5944
6529
  workspace,
5945
6530
  };
5946
- });
6531
+ },
6532
+ // A draft workspace is never served to a kid: no confirm round trip.
6533
+ { ungated: !goalId });
5947
6534
  }
5948
6535
  if (noun === "goals" && verb === "files") {
5949
6536
  const action = positional(parsed, 2, "goals files action");
5950
6537
  if (action === "list") {
5951
- const studentId = flagString(parsed, "student", { required: true });
6538
+ const student = await studentFlag(api, parsed, { required: true });
6539
+ const studentId = student.id;
5952
6540
  const goalId = flagString(parsed, "goal", { required: true });
5953
6541
  return unwrap(await api.client.GET("/tutor/students/{studentId}/goals/{goalId}/workspace/files", { params: { path: { studentId, goalId } } }));
5954
6542
  }
5955
6543
  if (action === "read") {
5956
- const studentId = flagString(parsed, "student", { required: true });
6544
+ const student = await studentFlag(api, parsed, { required: true });
6545
+ const studentId = student.id;
5957
6546
  const goalId = flagString(parsed, "goal", { required: true });
5958
6547
  return unwrap(await api.client.GET("/tutor/students/{studentId}/goals/{goalId}/workspace/file", {
5959
6548
  params: {
@@ -5963,7 +6552,8 @@ export async function executeRecessCommand(argv, options = {}) {
5963
6552
  }));
5964
6553
  }
5965
6554
  if (action === "init" || action === "checkout") {
5966
- const studentId = flagString(parsed, "student", { required: true });
6555
+ const student = await studentFlag(api, parsed, { required: true });
6556
+ const studentId = student.id;
5967
6557
  const goalId = flagString(parsed, "goal");
5968
6558
  const draftSlug = flagString(parsed, "draft");
5969
6559
  if (action === "init" && (goalId || !draftSlug)) {
@@ -5978,16 +6568,112 @@ export async function executeRecessCommand(argv, options = {}) {
5978
6568
  const target = goalId
5979
6569
  ? { kind: "goal", goalId }
5980
6570
  : { kind: "draft", draftSlug: draftSlug };
5981
- const response = await readRemoteWorkspaceSnapshot(api, studentId, target);
5982
- if (action === "init" && response.snapshot.fileCount > 0) {
5983
- throw new CliError("draft_exists", `Draft ${draftSlug} already has files. Use goals files checkout --draft to preserve them.`);
6571
+ const scaffold = hasFlag(parsed, "scaffold");
6572
+ const modulesFlag = flagString(parsed, "modules");
6573
+ const title = flagString(parsed, "title");
6574
+ if (!scaffold && (modulesFlag !== undefined || title !== undefined)) {
6575
+ throw new CliError("invalid_arguments", "--modules and --title are used with goals files init --scaffold.");
6576
+ }
6577
+ const moduleCount = flagNumber(parsed, "modules") ?? 3;
6578
+ if (scaffold &&
6579
+ (!Number.isInteger(moduleCount) || moduleCount < 1 || moduleCount > 20)) {
6580
+ throw new CliError("invalid_arguments", "--modules must be an integer from 1 through 20.");
6581
+ }
6582
+ if (title !== undefined && (!title.trim() || title.length > 200)) {
6583
+ throw new CliError("invalid_arguments", "--title must be 1 to 200 characters.");
6584
+ }
6585
+ if (scaffold && action !== "init") {
6586
+ throw new CliError("invalid_arguments", "--scaffold is only for goals files init on an empty draft.");
6587
+ }
6588
+ if (action === "checkout") {
6589
+ const response = await readRemoteWorkspaceSnapshot(api, studentId, target);
6590
+ return checkoutGoalWorkspace({
6591
+ outputDirectory,
6592
+ studentId,
6593
+ target,
6594
+ snapshot: response.snapshot,
6595
+ });
6596
+ }
6597
+ // The server scaffold is a fixed two-lesson tree; an explicit --modules
6598
+ // count keeps the local scaffold, as does a server without the init route.
6599
+ const serverScaffold = scaffold && modulesFlag === undefined;
6600
+ const initialized = await initDraftWorkspace(api, {
6601
+ studentId,
6602
+ draftSlug: draftSlug,
6603
+ outputDirectory,
6604
+ scaffold: serverScaffold,
6605
+ title,
6606
+ });
6607
+ let snapshot = initialized?.snapshot;
6608
+ if (!initialized) {
6609
+ const response = await readRemoteWorkspaceSnapshot(api, studentId, target);
6610
+ // An existing but empty draft is adopted as-is; one with files is only
6611
+ // ever checked out, so init can never shadow authored content.
6612
+ if (response.snapshot.fileCount > 0) {
6613
+ throw draftNotEmptyError({
6614
+ draftSlug: draftSlug,
6615
+ studentId,
6616
+ outputDirectory,
6617
+ fileCount: response.snapshot.fileCount,
6618
+ });
6619
+ }
6620
+ snapshot = response.snapshot;
5984
6621
  }
5985
- return checkoutGoalWorkspace({
6622
+ const checkedOut = await checkoutGoalWorkspace({
5986
6623
  outputDirectory,
5987
6624
  studentId,
5988
6625
  target,
5989
- snapshot: response.snapshot,
6626
+ snapshot: snapshot,
5990
6627
  });
6628
+ const initDetails = initialized
6629
+ ? {
6630
+ adopted: initialized.adopted,
6631
+ previousChangeId: initialized.previousChangeId,
6632
+ }
6633
+ : {};
6634
+ if (initialized?.scaffolded) {
6635
+ const files = initialized.snapshot.files.map((file) => file.path);
6636
+ return {
6637
+ ...checkedOut,
6638
+ ...initDetails,
6639
+ scaffold: {
6640
+ source: "server",
6641
+ files,
6642
+ modules: files.filter((file) => file.startsWith("modules/")),
6643
+ validation: serverWorkspaceValidation(initialized),
6644
+ },
6645
+ 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.`,
6646
+ };
6647
+ }
6648
+ if (!scaffold)
6649
+ return { ...checkedOut, ...initDetails };
6650
+ // The local scaffold is a LOCAL commit on top of the empty draft:
6651
+ // nothing is published until the author rewrites it and pushes.
6652
+ const files = buildGoalWorkspaceScaffold({
6653
+ draftSlug: draftSlug,
6654
+ moduleCount,
6655
+ title,
6656
+ });
6657
+ for (const file of files) {
6658
+ const destination = resolveWorkspaceCheckoutPath(checkedOut.directory, file.path);
6659
+ await fs.mkdir(path.dirname(destination), { recursive: true });
6660
+ await fs.writeFile(destination, file.content);
6661
+ }
6662
+ await runGit(checkedOut.directory, ["add", "-A"]);
6663
+ await runGit(checkedOut.directory, ["commit", "--quiet", "-m", "Scaffold module-backed goal workspace"], { identity: true });
6664
+ return {
6665
+ ...checkedOut,
6666
+ ...initDetails,
6667
+ scaffold: {
6668
+ source: "local",
6669
+ files: files.map((file) => file.path),
6670
+ modules: files
6671
+ .map((file) => file.path)
6672
+ .filter((file) => file.startsWith("modules/")),
6673
+ validation: validateGoalWorkspaceLocally(files),
6674
+ },
6675
+ 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.`,
6676
+ };
5991
6677
  }
5992
6678
  if (action === "push") {
5993
6679
  const sourceDirectory = flagString(parsed, "source-dir", {
@@ -6089,11 +6775,15 @@ export async function executeRecessCommand(argv, options = {}) {
6089
6775
  JSON.stringify(receipt.request) !== JSON.stringify(request)) {
6090
6776
  throw new CliError("approval_mismatch", "The command or committed file bytes differ from the approved push.");
6091
6777
  }
6778
+ const workspaceValidation = isGoal
6779
+ ? undefined
6780
+ : await draftWorkspaceValidation(preflight, () => readCheckoutTree(checkout.root));
6092
6781
  const preview = receipt ?? {
6093
6782
  action: actionDescription,
6094
6783
  target: boundTarget ?? preflight.target,
6095
6784
  request,
6096
6785
  details: {
6786
+ ...(workspaceValidation ? { workspaceValidation } : {}),
6097
6787
  stateModificationPaths: preflight.stateModificationPaths ?? [],
6098
6788
  warnings: preflight.warnings ?? [],
6099
6789
  currentChangeId: preflight.currentChangeId,
@@ -6118,17 +6808,24 @@ export async function executeRecessCommand(argv, options = {}) {
6118
6808
  changeId: result.changeId,
6119
6809
  upstreamCommit: local.head,
6120
6810
  });
6811
+ const writtenValidation = serverWorkspaceValidation(result) ?? workspaceValidation;
6121
6812
  return {
6122
6813
  ...result,
6814
+ ...(writtenValidation
6815
+ ? { workspaceValidation: writtenValidation }
6816
+ : {}),
6123
6817
  local: {
6124
6818
  directory: checkout.root,
6125
6819
  upstreamCommit: local.head,
6126
6820
  },
6127
6821
  };
6128
- }, isGoal);
6822
+ },
6823
+ // A draft workspace is never served to a kid: no confirm round trip.
6824
+ { persistPreview: isGoal, ungated: !isGoal });
6129
6825
  }
6130
6826
  if (action === "write") {
6131
- const studentId = flagString(parsed, "student", { required: true });
6827
+ const student = await studentFlag(api, parsed, { required: true });
6828
+ const studentId = student.id;
6132
6829
  const goalId = flagString(parsed, "goal");
6133
6830
  const draftSlug = flagString(parsed, "draft");
6134
6831
  if (Boolean(goalId) === Boolean(draftSlug)) {
@@ -6189,11 +6886,32 @@ export async function executeRecessCommand(argv, options = {}) {
6189
6886
  if (preflight && preflight.action !== "preview_workspace_files_write") {
6190
6887
  throw new CliError("unexpected_response", "Goal workspace write did not return a preview; nothing was written.");
6191
6888
  }
6889
+ // The draft after this upsert: its current files overlaid with these.
6890
+ const workspaceValidation = target.kind === "draft"
6891
+ ? await draftWorkspaceValidation(preflight, async () => {
6892
+ const tree = new Map();
6893
+ const { snapshot } = await readRemoteWorkspaceSnapshot(api, studentId, target);
6894
+ for (const file of snapshot.files) {
6895
+ tree.set(file.path, file.contentEncoding === "base64"
6896
+ ? Buffer.from(file.content, "base64").toString("utf8")
6897
+ : file.content);
6898
+ }
6899
+ for (const file of input.files) {
6900
+ tree.set(file.path, Buffer.from(file.content, "base64").toString("utf8"));
6901
+ }
6902
+ return [...tree].map(([filePath, content]) => ({
6903
+ path: filePath,
6904
+ content,
6905
+ }));
6906
+ })
6907
+ : undefined;
6192
6908
  const preview = receipt ?? {
6193
6909
  action: "batch-upsert files in a student's goal workspace",
6194
6910
  target: boundTarget ?? preflight.target,
6195
6911
  request,
6196
6912
  details: {
6913
+ ...resolvedStudentDetails(student),
6914
+ ...(workspaceValidation ? { workspaceValidation } : {}),
6197
6915
  stateModificationPaths: preflight.stateModificationPaths ?? [],
6198
6916
  warnings: preflight.warnings ?? [],
6199
6917
  currentChangeId: preflight.currentChangeId,
@@ -6204,13 +6922,21 @@ export async function executeRecessCommand(argv, options = {}) {
6204
6922
  : "This directly edits the live goal workspace, including modules/ and state/. The write remains bound to the previewed workspace revision.",
6205
6923
  },
6206
6924
  };
6207
- return previewBoundWrite(parsed, preview, async () => unwrap(await api.client.POST("/tutor/browser/mesa/workspace-files", {
6208
- body: {
6209
- ...body,
6210
- dryRun: false,
6211
- expectedChangeId: String(preview.details.currentChangeId),
6212
- },
6213
- })), Boolean(goalId));
6925
+ return previewBoundWrite(parsed, preview, async () => {
6926
+ const result = unwrap(await api.client.POST("/tutor/browser/mesa/workspace-files", {
6927
+ body: {
6928
+ ...body,
6929
+ dryRun: false,
6930
+ expectedChangeId: String(preview.details.currentChangeId),
6931
+ },
6932
+ }));
6933
+ const writtenValidation = serverWorkspaceValidation(result) ?? workspaceValidation;
6934
+ return writtenValidation
6935
+ ? { ...result, workspaceValidation: writtenValidation }
6936
+ : result;
6937
+ },
6938
+ // A draft workspace is never served to a kid: no confirm round trip.
6939
+ { persistPreview: Boolean(goalId), ungated: !goalId });
6214
6940
  }
6215
6941
  throw new CliError("invalid_arguments", "Use goals files list|read|init|checkout|push|write.");
6216
6942
  }