recess-cli 3.10.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
@@ -30,15 +30,99 @@ import { HELP } from "./help.js";
30
30
  export { HELP };
31
31
  import { cliRequestHeaders, noteServerCliVersions, requireCliRequestReason, } from "./http.js";
32
32
  import { runSelfUpdate, UPGRADE_COMMAND, updateNoticeText, updateStatus, } from "./update-notice.js";
33
- import { requireConfirmation } from "./safety.js";
33
+ import { requireConfirmation, resolveApprovalToken, } from "./safety.js";
34
34
  import { installSkill, isEphemeralInstall, readBundledSkillVersion, readCliVersion, } from "./setup.js";
35
35
  import { ensureFreshSession, revokeSession } from "./session-refresh.js";
36
36
  import { compareVersions, updateSkillFromServer } from "./skill-update.js";
37
37
  import { readSkillCache, writeSkillCache } from "./skills-cache.js";
38
38
  import { sanitizeWorkspaceUploadName } from "./upload-names.js";
39
39
  import { appendJobEvent, getJob, listJobs, pruneJobs } from "./jobs.js";
40
- function requiredRequestReason(parsed) {
41
- 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
+ }
42
126
  }
43
127
  /**
44
128
  * Role of whoever this session belongs to.
@@ -252,17 +336,26 @@ async function skillStatus(config, reason) {
252
336
  };
253
337
  }
254
338
  }
255
- 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);
256
347
  const fingerprint = approvalTokenFor(preview);
257
- const suppliedOperationKey = flagString(parsed, "operation-key");
258
- if (!hasFlag(parsed, "confirm")) {
348
+ let suppliedOperationKey = flagString(parsed, "operation-key");
349
+ if (!hasFlag(parsed, "confirm") && !options.ungated) {
259
350
  const operationKey = operationKeyFor(fingerprint);
351
+ const replay = replayFor(parsed);
260
352
  const boundPreview = {
261
353
  ...preview,
262
354
  details: {
263
355
  ...preview.details,
264
356
  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.",
357
+ retry: CONFIRM_RETRY_HINT,
358
+ ...confirmNextHint(parsed, operationKey),
266
359
  },
267
360
  };
268
361
  await appendJobEvent({
@@ -277,9 +370,13 @@ async function localWriteCommand(parsed, preview, execute) {
277
370
  preview.request.zeroBalance === "true"
278
371
  ? { preview }
279
372
  : {}),
373
+ ...(replay ? { replay } : {}),
280
374
  });
281
375
  requireConfirmation(false, boundPreview);
282
376
  }
377
+ if (options.ungated && !suppliedOperationKey) {
378
+ suppliedOperationKey = operationKeyFor(fingerprint);
379
+ }
283
380
  if (!suppliedOperationKey) {
284
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" });
285
382
  }
@@ -523,6 +620,35 @@ async function readRemoteWorkspaceSnapshot(api, studentId, target) {
523
620
  },
524
621
  }));
525
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
+ }
526
652
  async function assertCheckoutReadyForMaterialization(checkout) {
527
653
  const status = await runGit(checkout.root, ["status", "--porcelain=v1"]);
528
654
  if (status.trim()) {
@@ -636,20 +762,28 @@ function assertOperationKeyMatchesPreview(operationKey, fingerprint, preview) {
636
762
  });
637
763
  }
638
764
  }
639
- 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);
640
770
  const approvalToken = approvalTokenFor(preview);
641
771
  const suppliedOperationKey = flagString(parsed, "operation-key");
772
+ const operationKey = suppliedOperationKey ?? operationKeyFor(approvalToken);
642
773
  const boundPreview = {
643
774
  ...preview,
644
775
  details: {
645
776
  ...preview.details,
646
777
  approvalToken,
647
- operationKey: suppliedOperationKey ?? operationKeyFor(approvalToken),
778
+ operationKey,
779
+ retry: CONFIRM_RETRY_HINT,
780
+ ...confirmNextHint(parsed, operationKey),
648
781
  },
649
782
  };
650
- if (!hasFlag(parsed, "confirm")) {
783
+ if (!hasFlag(parsed, "confirm") && !options.ungated) {
784
+ const replay = replayFor(parsed);
651
785
  await appendJobEvent({
652
- jobId: String(boundPreview.details.operationKey),
786
+ jobId: operationKey,
653
787
  status: "awaiting_confirmation",
654
788
  timestamp: new Date().toISOString(),
655
789
  action: preview.action,
@@ -657,27 +791,32 @@ async function requirePreviewBoundConfirmation(parsed, preview, persistPreview =
657
791
  target: preview.target,
658
792
  // Opted-in operations retain the approved receipt in the 0600 ledger so
659
793
  // retries can reach server idempotency after their own write changed state.
660
- ...(persistPreview ? { preview } : {}),
794
+ ...(options.persistPreview ? { preview } : {}),
795
+ ...(replay ? { replay } : {}),
661
796
  });
662
797
  requireConfirmation(false, boundPreview);
663
798
  }
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) {
799
+ if (!suppliedOperationKey && !options.ungated) {
669
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" });
670
801
  }
671
- 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
+ }
672
811
  await appendJobEvent({
673
- jobId: suppliedOperationKey,
812
+ jobId: operationKey,
674
813
  status: "running",
675
814
  timestamp: new Date().toISOString(),
676
815
  action: preview.action,
677
816
  fingerprint: approvalToken,
678
817
  target: preview.target,
679
818
  });
680
- return { operationKey: suppliedOperationKey, fingerprint: approvalToken };
819
+ return { operationKey, fingerprint: approvalToken };
681
820
  }
682
821
  /**
683
822
  * A tutor template's `body` is the `## Subjects` block markdown (no `###`
@@ -717,8 +856,8 @@ async function readTutorTemplateLessons(directory) {
717
856
  }
718
857
  return lessons;
719
858
  }
720
- async function previewBoundWrite(parsed, preview, execute, persistPreview = false) {
721
- const context = await requirePreviewBoundConfirmation(parsed, preview, persistPreview);
859
+ async function previewBoundWrite(parsed, preview, execute, persistOrOptions = false) {
860
+ const context = await requirePreviewBoundConfirmation(parsed, preview, persistOrOptions);
722
861
  try {
723
862
  const result = await withIdempotencyContext(context, execute);
724
863
  await appendJobEvent({
@@ -767,12 +906,20 @@ async function readExecutedPreview(parsed) {
767
906
  const saved = receipt.preview;
768
907
  const fingerprint = approvalTokenFor(saved);
769
908
  if (receipt.fingerprint !== fingerprint ||
770
- flagString(parsed, "approval-token") !== fingerprint) {
909
+ resolveApprovalToken(parsed) !== fingerprint) {
771
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.");
772
911
  }
773
912
  assertOperationKeyMatchesPreview(key, fingerprint, saved);
774
913
  return saved;
775
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
+ }
776
923
  /** A retried write must retain its approved fence after changing its own source state. */
777
924
  async function recoverExecutedPreview(parsed, expected) {
778
925
  const saved = await readExecutedPreview(parsed);
@@ -785,6 +932,98 @@ async function recoverExecutedPreview(parsed, expected) {
785
932
  }
786
933
  return saved;
787
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
+ }
788
1027
  async function cleanupPlannerUpload(api, conversationId, signed, includeDelete) {
789
1028
  if (signed.kind === "multipart") {
790
1029
  await api.client
@@ -1453,6 +1692,122 @@ function parseGoalTemplateDocument(doc) {
1453
1692
  : { outputTemplate: optionalDocString(doc, "outputTemplate") }),
1454
1693
  };
1455
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
+ }
1456
1811
  /**
1457
1812
  * Resolve a template reference that may be a UUID or a slug. Slugs are what an
1458
1813
  * author types and what the skill's prose uses; the routes take a UUID only.
@@ -1482,16 +1837,29 @@ async function resolveGoalTemplateId(api, reference) {
1482
1837
  }
1483
1838
  return match.id;
1484
1839
  }
1485
- 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) {
1486
1847
  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.");
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" };
1489
1853
  }
1490
- if (!Number.isInteger(value) || value < 1) {
1491
- throw new CliError("invalid_arguments", "--expected-version must be a positive integer.");
1854
+ if (recovered !== undefined) {
1855
+ return { expectedVersion: recovered, pinnedFrom: "current" };
1492
1856
  }
1493
- 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" };
1494
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>.";
1495
1863
  async function readMapScorePdf(filePath) {
1496
1864
  const absolutePath = path.resolve(filePath);
1497
1865
  if (path.extname(absolutePath).toLowerCase() !== ".pdf") {
@@ -1687,7 +2055,9 @@ function cliErrorShape(error) {
1687
2055
  };
1688
2056
  }
1689
2057
  function remoteWriteCommand(argv, structuredInput, store) {
1690
- 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) => {
1691
2061
  const fingerprint = approvalTokenFor({
1692
2062
  ...preview,
1693
2063
  details: {
@@ -1737,6 +2107,9 @@ export async function executeRecessCommand(argv, options = {}) {
1737
2107
  const [noun, verb] = parsed.positionals;
1738
2108
  const commands = buildCommandSchema(HELP);
1739
2109
  const isRemote = options.transport === "remote";
2110
+ if (!isRemote && !options.operationStore) {
2111
+ localInvocations.set(parsed, { argv: [...argv] });
2112
+ }
1740
2113
  if (isRemote &&
1741
2114
  (!options.api || !options.config || !options.operationStore)) {
1742
2115
  throw new CliError("remote_context_required", "Hosted execution requires injected API, configuration, and operation-store adapters.");
@@ -1756,7 +2129,7 @@ export async function executeRecessCommand(argv, options = {}) {
1756
2129
  if (isRemote) {
1757
2130
  throw new CliError("remote_command_unavailable", "The version command is not exposed by the hosted Recess CLI.");
1758
2131
  }
1759
- 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));
1760
2133
  if (unknown.length > 0) {
1761
2134
  throw new CliError("unknown_flag", `Unknown flag${unknown.length === 1 ? "" : "s"}: ${unknown
1762
2135
  .map((name) => `--${name}`)
@@ -1768,7 +2141,15 @@ export async function executeRecessCommand(argv, options = {}) {
1768
2141
  };
1769
2142
  }
1770
2143
  if (!noun) {
1771
- 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));
1772
2153
  if (unknown.length > 0) {
1773
2154
  throw new CliError("unknown_flag", `Unknown flag${unknown.length === 1 ? "" : "s"}: ${unknown
1774
2155
  .map((name) => `--${name}`)
@@ -1780,6 +2161,7 @@ export async function executeRecessCommand(argv, options = {}) {
1780
2161
  return {
1781
2162
  help: scopedHelp(HELP, visibleCommands, [], discovery, {
1782
2163
  remoteOnly: isRemote,
2164
+ all: hasFlag(parsed, "all"),
1783
2165
  }),
1784
2166
  };
1785
2167
  }
@@ -1791,6 +2173,7 @@ export async function executeRecessCommand(argv, options = {}) {
1791
2173
  return {
1792
2174
  help: scopedHelp(HELP, visibleCommands, scope, discovery, {
1793
2175
  remoteOnly: isRemote,
2176
+ all: hasFlag(parsed, "all"),
1794
2177
  }),
1795
2178
  };
1796
2179
  }
@@ -1838,6 +2221,9 @@ export async function executeRecessCommand(argv, options = {}) {
1838
2221
  feedbackUpstreamConfigured: Boolean(process.env.RECESS_CLI_FEEDBACK_ENDPOINT),
1839
2222
  discovery,
1840
2223
  remoteOnly: isRemote,
2224
+ scope: parsed.positionals.slice(1),
2225
+ full: hasFlag(parsed, "full"),
2226
+ help: HELP,
1841
2227
  });
1842
2228
  }
1843
2229
  if (noun === "profile") {
@@ -1912,6 +2298,12 @@ export async function executeRecessCommand(argv, options = {}) {
1912
2298
  return pruneJobs(olderThanDays);
1913
2299
  }
1914
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
+ }
1915
2307
  if (noun === "feedback") {
1916
2308
  if (verb === "list") {
1917
2309
  const limit = flagNumber(parsed, "limit") ?? 20;
@@ -1941,7 +2333,17 @@ export async function executeRecessCommand(argv, options = {}) {
1941
2333
  }));
1942
2334
  }
1943
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);
1944
2343
  const config = options.config ?? (await resolveConfig(flagString(parsed, "profile")));
2344
+ const invocation = localInvocations.get(parsed);
2345
+ if (invocation)
2346
+ invocation.apiOrigin = config.apiOrigin;
1945
2347
  // Renew a refreshable session's 15-minute access cookie before any command
1946
2348
  // that uses it. Sign-in/out commands manage the session themselves. Not
1947
2349
  // fatal here: an offline local command must still run, and an API call
@@ -1951,11 +2353,6 @@ export async function executeRecessCommand(argv, options = {}) {
1951
2353
  noun !== "setup") {
1952
2354
  await ensureFreshSession(config).catch(() => undefined);
1953
2355
  }
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
2356
  if (noun === "doctor" && isRemote) {
1960
2357
  return {
1961
2358
  transport: "streamable-http-mcp",
@@ -2504,9 +2901,9 @@ export async function executeRecessCommand(argv, options = {}) {
2504
2901
  }
2505
2902
  const tierId = assertChoice(flagString(parsed, "tier", { required: true }), SCHOOL_TIER_IDS, "--tier");
2506
2903
  const proposedSlots = tierSlots(parsed);
2507
- const expectedUpdatedAt = action === "set"
2508
- ? flagString(parsed, "expected-updated-at", { required: true })
2509
- : 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;
2510
2907
  if (expectedUpdatedAt !== undefined &&
2511
2908
  Number.isNaN(Date.parse(expectedUpdatedAt))) {
2512
2909
  throw new CliError("invalid_arguments", "--expected-updated-at must be an ISO-8601 timestamp from users tier get.");
@@ -2544,7 +2941,7 @@ export async function executeRecessCommand(argv, options = {}) {
2544
2941
  const body = {
2545
2942
  tierId,
2546
2943
  ...(proposedSlots === undefined ? {} : { slotsPerKid: proposedSlots }),
2547
- expectedUpdatedAt: expectedUpdatedAt,
2944
+ expectedUpdatedAt: expectedUpdatedAt ?? state.updatedAt,
2548
2945
  allowStrand,
2549
2946
  };
2550
2947
  return writeCommand(parsed, {
@@ -2933,6 +3330,24 @@ export async function executeRecessCommand(argv, options = {}) {
2933
3330
  params: { path: { userId } },
2934
3331
  })));
2935
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
+ }
2936
3351
  if (noun === "students" && verb === "upload-map-scores") {
2937
3352
  const studentId = flagString(parsed, "student", { required: true });
2938
3353
  const pdf = await readMapScorePdf(flagString(parsed, "file", { required: true }));
@@ -3041,7 +3456,9 @@ export async function executeRecessCommand(argv, options = {}) {
3041
3456
  const lineItem = flagString(parsed, "line-item", { required: true });
3042
3457
  const method = assertChoice(flagString(parsed, "method", { required: true }), ["refund", "credit", "tokens"], "--method");
3043
3458
  const whoPays = assertChoice(flagString(parsed, "who-pays") ?? "guide", ["guide", "recess"], "--who-pays");
3044
- 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");
3045
3462
  const amount = flagNumber(parsed, "amount-cents");
3046
3463
  const fullRefund = hasFlag(parsed, "full");
3047
3464
  if (method === "tokens" && (!amount || fullRefund)) {
@@ -3195,7 +3612,9 @@ export async function executeRecessCommand(argv, options = {}) {
3195
3612
  });
3196
3613
  const immediate = hasFlag(parsed, "immediate");
3197
3614
  const restore = hasFlag(parsed, "restore");
3198
- 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");
3199
3618
  const body = {
3200
3619
  immediate,
3201
3620
  subscriptionId,
@@ -3279,7 +3698,10 @@ export async function executeRecessCommand(argv, options = {}) {
3279
3698
  const removalQuery = zeroBalance
3280
3699
  ? {
3281
3700
  zeroBalance: "true",
3282
- 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 }),
3283
3705
  expectedBalanceCents,
3284
3706
  }
3285
3707
  : {};
@@ -3609,11 +4031,14 @@ export async function executeRecessCommand(argv, options = {}) {
3609
4031
  }
3610
4032
  if (noun === "events" && verb === "cancel") {
3611
4033
  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 };
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 };
3617
4042
  return writeCommand(parsed, {
3618
4043
  action: "cancel event AND NOTIFY: messages kid + parent channels, emails every registered parent, files credit-owed notes, posts to Slack",
3619
4044
  target: { eventId },
@@ -3978,15 +4403,16 @@ export async function executeRecessCommand(argv, options = {}) {
3978
4403
  if (verb === "validate-spec") {
3979
4404
  const document = parseGoalTemplateDocument(await readTemplateDocument());
3980
4405
  // A read-only validation: no gate, and iterating on it is the whole point.
4406
+ const validation = await validateGoalTemplateDocument(api, document);
3981
4407
  return {
3982
4408
  slug: document.slug,
3983
4409
  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
- })),
4410
+ ...validation,
4411
+ ...(validation.valid && !("answersTemplate" in validation)
4412
+ ? {
4413
+ answersTemplate: buildAnswersTemplate(document.setupWorkflowSpec, []).answers,
4414
+ }
4415
+ : {}),
3990
4416
  };
3991
4417
  }
3992
4418
  if (verb === "create") {
@@ -4011,14 +4437,21 @@ export async function executeRecessCommand(argv, options = {}) {
4011
4437
  // answer keys `apply` will demand all come out of the spec's own
4012
4438
  // validation — a locally guessed preview could name a different handler
4013
4439
  // 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
- }));
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
+ });
4020
4448
  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" });
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
+ });
4022
4455
  }
4023
4456
  return writeCommand(parsed, {
4024
4457
  action: "create a NEW global goal template (DETERMINISTIC_WORKFLOW — this cannot be converted back)",
@@ -4041,6 +4474,9 @@ export async function executeRecessCommand(argv, options = {}) {
4041
4474
  wizardStepKeys: validation.stepKeys,
4042
4475
  specSha256: validation.sha256,
4043
4476
  specInventory: validation.totals,
4477
+ answersTemplate: "answersTemplate" in validation
4478
+ ? validation.answersTemplate
4479
+ : buildAnswersTemplate(document.setupWorkflowSpec, []).answers,
4044
4480
  note: "Setup mode is DETERMINISTIC_WORKFLOW and is one-way: this template can never be converted back to a chat-driven setup.",
4045
4481
  },
4046
4482
  }, async () => {
@@ -4079,6 +4515,15 @@ export async function executeRecessCommand(argv, options = {}) {
4079
4515
  }
4080
4516
  if (target === undefined && minimum === undefined)
4081
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);
4082
4527
  const body = {
4083
4528
  recipeKey: flagString(parsed, "recipe", { required: true }),
4084
4529
  ...(target === undefined ? {} : { targetModuleCount: Number(target) }),
@@ -4087,7 +4532,7 @@ export async function executeRecessCommand(argv, options = {}) {
4087
4532
  : {
4088
4533
  requiredModuleCount: minimum === "all" ? null : Number(minimum),
4089
4534
  }),
4090
- expectedVersion: requiredExpectedVersion(parsed),
4535
+ expectedVersion,
4091
4536
  };
4092
4537
  const requestPreview = {
4093
4538
  action: "edit shared goal-template assigned target or completion minimum",
@@ -4226,7 +4671,7 @@ export async function executeRecessCommand(argv, options = {}) {
4226
4671
  }
4227
4672
  if (verb === "patch-spec") {
4228
4673
  const id = await resolveGoalTemplateId(api, positional(parsed, 2, "template ID or slug"));
4229
- const expectedVersion = requiredExpectedVersion(parsed);
4674
+ const { expectedVersion, pinnedFrom } = await resolveExpectedTemplateVersion(api, parsed, id);
4230
4675
  const patchFile = await readGoalTemplateSpecPatches(flagString(parsed, "patches-file", { required: true }));
4231
4676
  // The server owns JSON Pointer semantics, strict final-spec validation,
4232
4677
  // protected-inventory counting, and the token binding the approved loss
@@ -4261,6 +4706,9 @@ export async function executeRecessCommand(argv, options = {}) {
4261
4706
  patches: patchFile.patches,
4262
4707
  },
4263
4708
  details: {
4709
+ ...(pinnedFrom === "current"
4710
+ ? { expectedVersionNote: PINNED_VERSION_NOTE }
4711
+ : {}),
4264
4712
  patchesApplied: preflight.patchesApplied,
4265
4713
  safety: preflight.preview,
4266
4714
  ...(preflight.preview.destructiveChanges
@@ -4301,7 +4749,7 @@ export async function executeRecessCommand(argv, options = {}) {
4301
4749
  }
4302
4750
  if (verb === "set-metadata") {
4303
4751
  const id = await resolveGoalTemplateId(api, positional(parsed, 2, "template ID or slug"));
4304
- const expectedVersion = requiredExpectedVersion(parsed);
4752
+ const { expectedVersion, pinnedFrom } = await resolveExpectedTemplateVersion(api, parsed, id);
4305
4753
  const agentInstructionsFile = flagString(parsed, "agent-instructions-file");
4306
4754
  const outputTemplateFile = flagString(parsed, "output-template-file");
4307
4755
  const tags = flagString(parsed, "tags");
@@ -4387,6 +4835,9 @@ export async function executeRecessCommand(argv, options = {}) {
4387
4835
  action: "update goal template metadata (never its setupWorkflowSpec)",
4388
4836
  target: { templateId: id, expectedVersion },
4389
4837
  request: body,
4838
+ ...(pinnedFrom === "current"
4839
+ ? { details: { expectedVersionNote: PINNED_VERSION_NOTE } }
4840
+ : {}),
4390
4841
  }, async () => unwrap(await api.client.PUT("/ai/goal-templates/{id}", {
4391
4842
  params: { path: { id } },
4392
4843
  body,
@@ -4416,13 +4867,14 @@ export async function executeRecessCommand(argv, options = {}) {
4416
4867
  }
4417
4868
  if (verb === "delete") {
4418
4869
  const id = await resolveGoalTemplateId(api, positional(parsed, 2, "template ID or slug"));
4419
- const expectedVersion = requiredExpectedVersion(parsed);
4420
4870
  // Read the current version so the gate refuses a stale delete locally,
4421
4871
  // and so the preview names the template a human is being asked to approve
4422
- // 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.
4423
4874
  const current = unwrap(await api.client.GET("/ai/goal-templates/{id}", {
4424
4875
  params: { path: { id } },
4425
4876
  }));
4877
+ const { expectedVersion } = await resolveExpectedTemplateVersion(api, parsed, id, current.version);
4426
4878
  if (current.version !== expectedVersion) {
4427
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 });
4428
4880
  }
@@ -4469,14 +4921,17 @@ export async function executeRecessCommand(argv, options = {}) {
4469
4921
  const checkoutHead = checkout
4470
4922
  ? await assertCheckoutReadyForMaterialization(checkout)
4471
4923
  : null;
4472
- const requestedSourceStudentId = flagString(parsed, "student");
4924
+ const requestedSourceStudent = await studentFlag(api, parsed, {
4925
+ required: Boolean(sourceDraft),
4926
+ });
4927
+ const requestedSourceStudentId = requestedSourceStudent?.id;
4473
4928
  if (checkout &&
4474
4929
  requestedSourceStudentId &&
4475
4930
  requestedSourceStudentId !== checkout.metadata.studentId) {
4476
4931
  throw new CliError("invalid_arguments", `--student ${requestedSourceStudentId} does not match checkout owner ${checkout.metadata.studentId}.`);
4477
4932
  }
4478
4933
  const sourceStudentUserId = sourceDraft
4479
- ? flagString(parsed, "student", { required: true })
4934
+ ? requestedSourceStudentId
4480
4935
  : checkout?.metadata.studentId;
4481
4936
  let source;
4482
4937
  if (sourceGoalId) {
@@ -4537,19 +4992,95 @@ export async function executeRecessCommand(argv, options = {}) {
4537
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.",
4538
4993
  },
4539
4994
  };
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
- })));
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
+ };
4549
5063
  }
4550
5064
  if (verb === "apply") {
4551
5065
  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");
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
+ }
4553
5084
  // `--dry-run` is a read: it resolves the whole plan and writes nothing,
4554
5085
  // so it does not gate. Run it, read the per-student results, then confirm.
4555
5086
  if (hasFlag(parsed, "dry-run")) {
@@ -4575,6 +5106,14 @@ export async function executeRecessCommand(argv, options = {}) {
4575
5106
  target: { templateId: id, students: preflight.results.length },
4576
5107
  request: { answers },
4577
5108
  details: {
5109
+ ...(students.some((student) => student.name)
5110
+ ? {
5111
+ resolvedStudents: students.map(({ id, name }) => ({
5112
+ id,
5113
+ name,
5114
+ })),
5115
+ }
5116
+ : {}),
4578
5117
  counts,
4579
5118
  results: preflight.results.map((result) => ({
4580
5119
  student: result.studentName,
@@ -4600,7 +5139,8 @@ export async function executeRecessCommand(argv, options = {}) {
4600
5139
  }
4601
5140
  if (verb === "apply-starter") {
4602
5141
  const id = await resolveGoalTemplateId(api, positional(parsed, 2, "template ID or slug"));
4603
- const studentUserId = flagString(parsed, "student", { required: true });
5142
+ const student = await studentFlag(api, parsed, { required: true });
5143
+ const studentUserId = student.id;
4604
5144
  const answersFile = flagString(parsed, "answers-file");
4605
5145
  const answers = answersFile
4606
5146
  ? await readJsonFile(answersFile, "Answers file")
@@ -4613,6 +5153,7 @@ export async function executeRecessCommand(argv, options = {}) {
4613
5153
  target: { templateId: id, studentUserId },
4614
5154
  request: { answers },
4615
5155
  details: {
5156
+ ...resolvedStudentDetails(student),
4616
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.",
4617
5158
  },
4618
5159
  }, async () => unwrap(await api.client.POST("/ai/goal-templates/{id}/apply-starter", {
@@ -4620,11 +5161,12 @@ export async function executeRecessCommand(argv, options = {}) {
4620
5161
  body: { studentUserId, answers },
4621
5162
  })));
4622
5163
  }
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.");
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.");
4624
5165
  }
4625
5166
  if (noun === "goals" && verb === "adaptations") {
4626
5167
  const action = positional(parsed, 2, "goals adaptations action");
4627
- const studentId = flagString(parsed, "student", { required: true });
5168
+ const student = await studentFlag(api, parsed, { required: true });
5169
+ const studentId = student.id;
4628
5170
  const goalId = flagString(parsed, "goal", { required: true });
4629
5171
  if (action === "list") {
4630
5172
  return unwrap(await api.client.GET("/tutor/students/{studentId}/goals/{goalId}/adaptations", { params: { path: { studentId, goalId } } }));
@@ -4669,7 +5211,8 @@ export async function executeRecessCommand(argv, options = {}) {
4669
5211
  }
4670
5212
  if (verb === "archive" || verb === "unarchive") {
4671
5213
  const goalId = positional(parsed, 2, "goal ID");
4672
- const studentId = flagString(parsed, "student", { required: true });
5214
+ const student = await studentFlag(api, parsed, { required: true });
5215
+ const studentId = student.id;
4673
5216
  const reopen = verb === "unarchive";
4674
5217
  const current = unwrap(await api.client.GET("/tutor/browser/students/{userId}/goals/", {
4675
5218
  params: { path: { userId: studentId } },
@@ -4699,6 +5242,7 @@ export async function executeRecessCommand(argv, options = {}) {
4699
5242
  },
4700
5243
  request: { goalId },
4701
5244
  details: {
5245
+ ...resolvedStudentDetails(student),
4702
5246
  note: reopen
4703
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)."
4704
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`.",
@@ -4713,7 +5257,8 @@ export async function executeRecessCommand(argv, options = {}) {
4713
5257
  })));
4714
5258
  }
4715
5259
  if (verb === "list") {
4716
- const userId = flagString(parsed, "student", { required: true });
5260
+ const student = await studentFlag(api, parsed, { required: true });
5261
+ const userId = student.id;
4717
5262
  const result = unwrap(await api.client.GET("/tutor/browser/students/{userId}/goals/", {
4718
5263
  params: { path: { userId } },
4719
5264
  }));
@@ -4736,7 +5281,8 @@ export async function executeRecessCommand(argv, options = {}) {
4736
5281
  // no retiring the work they have already done, nobody else's goal touched.
4737
5282
  if (verb === "move-module") {
4738
5283
  const moduleRef = positional(parsed, 2, "module ref (e.g. Q006)");
4739
- const studentId = flagString(parsed, "student", { required: true });
5284
+ const student = await studentFlag(api, parsed, { required: true });
5285
+ const studentId = student.id;
4740
5286
  const goalId = flagString(parsed, "goal", { required: true });
4741
5287
  const toEnd = hasFlag(parsed, "to-end");
4742
5288
  const position = flagNumber(parsed, "position");
@@ -4774,6 +5320,7 @@ export async function executeRecessCommand(argv, options = {}) {
4774
5320
  },
4775
5321
  request: { moduleId: target.id, ordinal },
4776
5322
  details: {
5323
+ ...resolvedStudentDetails(student),
4777
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.",
4778
5325
  ...(collision
4779
5326
  ? {
@@ -4790,7 +5337,8 @@ export async function executeRecessCommand(argv, options = {}) {
4790
5337
  })));
4791
5338
  }
4792
5339
  if (verb === "create") {
4793
- const requestedStudentId = flagString(parsed, "student");
5340
+ const requestedStudent = await studentFlag(api, parsed);
5341
+ const requestedStudentId = requestedStudent?.id;
4794
5342
  const sourceDirectory = flagString(parsed, "source-dir");
4795
5343
  const explicitDraftSlug = flagString(parsed, "draft");
4796
5344
  if (sourceDirectory && explicitDraftSlug) {
@@ -4882,6 +5430,7 @@ export async function executeRecessCommand(argv, options = {}) {
4882
5430
  : {}),
4883
5431
  },
4884
5432
  details: {
5433
+ ...resolvedStudentDetails(requestedStudent),
4885
5434
  currentChangeId: preflight.currentChangeId,
4886
5435
  workspaceSha256: preflight.workspaceSha256,
4887
5436
  fileCount: preflight.fileCount,
@@ -4939,6 +5488,7 @@ export async function executeRecessCommand(argv, options = {}) {
4939
5488
  schedule: schedule ?? null,
4940
5489
  },
4941
5490
  details: {
5491
+ ...resolvedStudentDetails(requestedStudent),
4942
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.",
4943
5493
  },
4944
5494
  }, async () => unwrap(await api.client.POST("/tutor/browser/students/{userId}/goals/", {
@@ -4948,7 +5498,8 @@ export async function executeRecessCommand(argv, options = {}) {
4948
5498
  }
4949
5499
  if (verb === "edit") {
4950
5500
  const goalId = positional(parsed, 2, "goal ID");
4951
- const studentId = flagString(parsed, "student", { required: true });
5501
+ const student = await studentFlag(api, parsed, { required: true });
5502
+ const studentId = student.id;
4952
5503
  const patchFile = flagString(parsed, "patch-file", { required: true });
4953
5504
  const patch = (await readJsonFile(patchFile, "Goal patch file"));
4954
5505
  assertGoalPatchValues(patch, patchFile);
@@ -4968,6 +5519,7 @@ export async function executeRecessCommand(argv, options = {}) {
4968
5519
  expectedUpdatedAt: current.updatedAt,
4969
5520
  patch,
4970
5521
  },
5522
+ details: resolvedStudentDetails(student),
4971
5523
  };
4972
5524
  return previewBoundWrite(parsed, preview, async () => unwrap(await api.client.PATCH("/tutor/browser/students/goals/{goalId}/", {
4973
5525
  params: { path: { goalId } },
@@ -4976,7 +5528,8 @@ export async function executeRecessCommand(argv, options = {}) {
4976
5528
  }
4977
5529
  if (verb === "delete") {
4978
5530
  const goalId = positional(parsed, 2, "goal ID");
4979
- const studentId = flagString(parsed, "student", { required: true });
5531
+ const student = await studentFlag(api, parsed, { required: true });
5532
+ const studentId = student.id;
4980
5533
  // Deletion is an /admin/* route, so a guardian or guide session can never
4981
5534
  // complete it. Refuse here, before the preview, rather than rendering a
4982
5535
  // full and entirely plausible preview — resolved goal, named title,
@@ -5002,6 +5555,7 @@ export async function executeRecessCommand(argv, options = {}) {
5002
5555
  },
5003
5556
  request: { expectedUpdatedAt: current.updatedAt },
5004
5557
  details: {
5558
+ ...resolvedStudentDetails(student),
5005
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.",
5006
5560
  },
5007
5561
  };
@@ -5014,7 +5568,8 @@ export async function executeRecessCommand(argv, options = {}) {
5014
5568
  }
5015
5569
  if (verb === "restore") {
5016
5570
  const goalId = positional(parsed, 2, "goal ID");
5017
- const studentId = flagString(parsed, "student", { required: true });
5571
+ const student = await studentFlag(api, parsed, { required: true });
5572
+ const studentId = student.id;
5018
5573
  const sessionRole = await resolveSessionRole(api);
5019
5574
  if (sessionRole && sessionRole !== "ADMIN") {
5020
5575
  throw new CliError("forbidden", "Restoring a deleted goal is admin-only.", 1, { sessionRole, requiredRole: "ADMIN" });
@@ -5040,6 +5595,7 @@ export async function executeRecessCommand(argv, options = {}) {
5040
5595
  },
5041
5596
  request: body,
5042
5597
  details: {
5598
+ ...resolvedStudentDetails(student),
5043
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.",
5044
5600
  },
5045
5601
  };
@@ -5048,7 +5604,8 @@ export async function executeRecessCommand(argv, options = {}) {
5048
5604
  if (verb === "queue") {
5049
5605
  const subverb = positional(parsed, 2, "queue action (get|set)");
5050
5606
  const goalId = positional(parsed, 3, "goal ID");
5051
- const studentId = flagString(parsed, "student", { required: true });
5607
+ const student = await studentFlag(api, parsed, { required: true });
5608
+ const studentId = student.id;
5052
5609
  if (subverb === "get") {
5053
5610
  return unwrap(await api.client.GET("/tutor/browser/students/goals/{goalId}/queue/", { params: { path: { goalId } } }));
5054
5611
  }
@@ -5101,6 +5658,7 @@ export async function executeRecessCommand(argv, options = {}) {
5101
5658
  unchangedTitleForConcurrencyFence: goal.title,
5102
5659
  },
5103
5660
  details: {
5661
+ ...resolvedStudentDetails(student),
5104
5662
  currentQueue: current.queue.map((item) => ({
5105
5663
  moduleRef: item.moduleRef,
5106
5664
  url: item.url,
@@ -5231,20 +5789,7 @@ export async function executeRecessCommand(argv, options = {}) {
5231
5789
  }
5232
5790
  const cursor = flagString(parsed, "cursor");
5233
5791
  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
- }
5792
+ const studentId = (await resolveStudentReference(api, student)).id;
5248
5793
  return unwrap(await api.client.GET("/studio/students/{studentId}/todos", {
5249
5794
  params: {
5250
5795
  path: { studentId },
@@ -5288,7 +5833,8 @@ export async function executeRecessCommand(argv, options = {}) {
5288
5833
  }
5289
5834
  if (noun === "todos") {
5290
5835
  if (verb === "create") {
5291
- const studentId = flagString(parsed, "student", { required: true });
5836
+ const student = await studentFlag(api, parsed, { required: true });
5837
+ const studentId = student.id;
5292
5838
  const title = flagString(parsed, "title", { required: true });
5293
5839
  const targetDurationInMins = flagNumber(parsed, "target-minutes");
5294
5840
  const body = {
@@ -5306,6 +5852,7 @@ export async function executeRecessCommand(argv, options = {}) {
5306
5852
  action: "create a todo for a managed student",
5307
5853
  target: { studentUserId: studentId },
5308
5854
  request: body,
5855
+ details: resolvedStudentDetails(student),
5309
5856
  }, async () => unwrap(await api.client.POST("/tutor/browser/todos/", { body })));
5310
5857
  }
5311
5858
  if (verb === "edit") {
@@ -5503,7 +6050,8 @@ export async function executeRecessCommand(argv, options = {}) {
5503
6050
  }
5504
6051
  if (verb === "generate-applet") {
5505
6052
  const todoId = positional(parsed, 2, "todo ID");
5506
- const studentId = flagString(parsed, "student", { required: true });
6053
+ const student = await studentFlag(api, parsed, { required: true });
6054
+ const studentId = student.id;
5507
6055
  const targetDueDateISO = flagDateOnly(parsed, "due-date");
5508
6056
  const [todo, learningAnalysis] = await Promise.all([
5509
6057
  api.client.GET("/tutor/browser/todos/{id}/", {
@@ -5545,7 +6093,8 @@ export async function executeRecessCommand(argv, options = {}) {
5545
6093
  throw new CliError("invalid_arguments", "Use todos create|edit|complete|delete|restore|generate-learning-analysis|generate-applet.");
5546
6094
  }
5547
6095
  if (noun === "memories") {
5548
- const studentId = flagString(parsed, "student", { required: true });
6096
+ const student = await studentFlag(api, parsed, { required: true });
6097
+ const studentId = student.id;
5549
6098
  if (verb === "context") {
5550
6099
  return unwrap(await api.client.GET("/tutor/students/{studentId}/prompt-memory", {
5551
6100
  params: { path: { studentId } },
@@ -5569,10 +6118,17 @@ export async function executeRecessCommand(argv, options = {}) {
5569
6118
  if (verb === "set") {
5570
6119
  const patchFile = flagString(parsed, "patch-file", { required: true });
5571
6120
  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;
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;
5576
6132
  if (expectedUpdatedAt !== null &&
5577
6133
  Number.isNaN(Date.parse(expectedUpdatedAt))) {
5578
6134
  throw new CliError("invalid_arguments", "--expected-updated-at must be an ISO datetime from `rocky get`, or `none`.");
@@ -5805,7 +6361,8 @@ export async function executeRecessCommand(argv, options = {}) {
5805
6361
  if (action !== "upload") {
5806
6362
  throw new CliError("invalid_arguments", "Use goals pdf upload.");
5807
6363
  }
5808
- const studentId = flagString(parsed, "student", { required: true });
6364
+ const student = await studentFlag(api, parsed, { required: true });
6365
+ const studentId = student.id;
5809
6366
  const goalId = flagString(parsed, "goal");
5810
6367
  const draftSlug = flagString(parsed, "draft");
5811
6368
  if (Boolean(goalId) === Boolean(draftSlug)) {
@@ -5870,6 +6427,7 @@ export async function executeRecessCommand(argv, options = {}) {
5870
6427
  message,
5871
6428
  },
5872
6429
  details: {
6430
+ ...resolvedStudentDetails(student),
5873
6431
  currentChangeId: preflight.currentChangeId,
5874
6432
  note: "The PDF is stored separately and the goal workspace receives a small verified reference, matching planner-authored textbook goals.",
5875
6433
  },
@@ -5970,17 +6528,21 @@ export async function executeRecessCommand(argv, options = {}) {
5970
6528
  workspacePath,
5971
6529
  workspace,
5972
6530
  };
5973
- });
6531
+ },
6532
+ // A draft workspace is never served to a kid: no confirm round trip.
6533
+ { ungated: !goalId });
5974
6534
  }
5975
6535
  if (noun === "goals" && verb === "files") {
5976
6536
  const action = positional(parsed, 2, "goals files action");
5977
6537
  if (action === "list") {
5978
- const studentId = flagString(parsed, "student", { required: true });
6538
+ const student = await studentFlag(api, parsed, { required: true });
6539
+ const studentId = student.id;
5979
6540
  const goalId = flagString(parsed, "goal", { required: true });
5980
6541
  return unwrap(await api.client.GET("/tutor/students/{studentId}/goals/{goalId}/workspace/files", { params: { path: { studentId, goalId } } }));
5981
6542
  }
5982
6543
  if (action === "read") {
5983
- const studentId = flagString(parsed, "student", { required: true });
6544
+ const student = await studentFlag(api, parsed, { required: true });
6545
+ const studentId = student.id;
5984
6546
  const goalId = flagString(parsed, "goal", { required: true });
5985
6547
  return unwrap(await api.client.GET("/tutor/students/{studentId}/goals/{goalId}/workspace/file", {
5986
6548
  params: {
@@ -5990,7 +6552,8 @@ export async function executeRecessCommand(argv, options = {}) {
5990
6552
  }));
5991
6553
  }
5992
6554
  if (action === "init" || action === "checkout") {
5993
- const studentId = flagString(parsed, "student", { required: true });
6555
+ const student = await studentFlag(api, parsed, { required: true });
6556
+ const studentId = student.id;
5994
6557
  const goalId = flagString(parsed, "goal");
5995
6558
  const draftSlug = flagString(parsed, "draft");
5996
6559
  if (action === "init" && (goalId || !draftSlug)) {
@@ -6005,16 +6568,112 @@ export async function executeRecessCommand(argv, options = {}) {
6005
6568
  const target = goalId
6006
6569
  ? { kind: "goal", goalId }
6007
6570
  : { 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.`);
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
+ });
6011
6596
  }
6012
- return checkoutGoalWorkspace({
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;
6621
+ }
6622
+ const checkedOut = await checkoutGoalWorkspace({
6013
6623
  outputDirectory,
6014
6624
  studentId,
6015
6625
  target,
6016
- snapshot: response.snapshot,
6626
+ snapshot: snapshot,
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,
6017
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
+ };
6018
6677
  }
6019
6678
  if (action === "push") {
6020
6679
  const sourceDirectory = flagString(parsed, "source-dir", {
@@ -6116,11 +6775,15 @@ export async function executeRecessCommand(argv, options = {}) {
6116
6775
  JSON.stringify(receipt.request) !== JSON.stringify(request)) {
6117
6776
  throw new CliError("approval_mismatch", "The command or committed file bytes differ from the approved push.");
6118
6777
  }
6778
+ const workspaceValidation = isGoal
6779
+ ? undefined
6780
+ : await draftWorkspaceValidation(preflight, () => readCheckoutTree(checkout.root));
6119
6781
  const preview = receipt ?? {
6120
6782
  action: actionDescription,
6121
6783
  target: boundTarget ?? preflight.target,
6122
6784
  request,
6123
6785
  details: {
6786
+ ...(workspaceValidation ? { workspaceValidation } : {}),
6124
6787
  stateModificationPaths: preflight.stateModificationPaths ?? [],
6125
6788
  warnings: preflight.warnings ?? [],
6126
6789
  currentChangeId: preflight.currentChangeId,
@@ -6145,17 +6808,24 @@ export async function executeRecessCommand(argv, options = {}) {
6145
6808
  changeId: result.changeId,
6146
6809
  upstreamCommit: local.head,
6147
6810
  });
6811
+ const writtenValidation = serverWorkspaceValidation(result) ?? workspaceValidation;
6148
6812
  return {
6149
6813
  ...result,
6814
+ ...(writtenValidation
6815
+ ? { workspaceValidation: writtenValidation }
6816
+ : {}),
6150
6817
  local: {
6151
6818
  directory: checkout.root,
6152
6819
  upstreamCommit: local.head,
6153
6820
  },
6154
6821
  };
6155
- }, isGoal);
6822
+ },
6823
+ // A draft workspace is never served to a kid: no confirm round trip.
6824
+ { persistPreview: isGoal, ungated: !isGoal });
6156
6825
  }
6157
6826
  if (action === "write") {
6158
- const studentId = flagString(parsed, "student", { required: true });
6827
+ const student = await studentFlag(api, parsed, { required: true });
6828
+ const studentId = student.id;
6159
6829
  const goalId = flagString(parsed, "goal");
6160
6830
  const draftSlug = flagString(parsed, "draft");
6161
6831
  if (Boolean(goalId) === Boolean(draftSlug)) {
@@ -6216,11 +6886,32 @@ export async function executeRecessCommand(argv, options = {}) {
6216
6886
  if (preflight && preflight.action !== "preview_workspace_files_write") {
6217
6887
  throw new CliError("unexpected_response", "Goal workspace write did not return a preview; nothing was written.");
6218
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;
6219
6908
  const preview = receipt ?? {
6220
6909
  action: "batch-upsert files in a student's goal workspace",
6221
6910
  target: boundTarget ?? preflight.target,
6222
6911
  request,
6223
6912
  details: {
6913
+ ...resolvedStudentDetails(student),
6914
+ ...(workspaceValidation ? { workspaceValidation } : {}),
6224
6915
  stateModificationPaths: preflight.stateModificationPaths ?? [],
6225
6916
  warnings: preflight.warnings ?? [],
6226
6917
  currentChangeId: preflight.currentChangeId,
@@ -6231,13 +6922,21 @@ export async function executeRecessCommand(argv, options = {}) {
6231
6922
  : "This directly edits the live goal workspace, including modules/ and state/. The write remains bound to the previewed workspace revision.",
6232
6923
  },
6233
6924
  };
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));
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 });
6241
6940
  }
6242
6941
  throw new CliError("invalid_arguments", "Use goals files list|read|init|checkout|push|write.");
6243
6942
  }