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.
@@ -1,73 +1,20 @@
1
1
  import { CliError } from "./errors.js";
2
- export const AGENT_CONTEXT_SCHEMA_VERSION = "4";
3
- const BOOLEAN_FLAGS = new Set([
4
- "zero-balance",
5
- "allow-possible-duplicate",
6
- "allow-state-modification",
7
- "allow-assigned-edits",
8
- "all-references",
9
- "analyzed",
10
- "apply",
11
- "allow-billing",
12
- "allow-strand",
13
- "archived",
14
- "cancel-subscriptions",
15
- "clear",
16
- "clear-focus",
17
- "clear-send-hour",
18
- "confirm",
19
- "confirm-destructive-changes",
20
- "disable-applet-follow-ups",
21
- "dry-run",
22
- "force",
23
- "no-wait",
24
- "enable-applet-follow-ups",
25
- "full",
26
- "help",
27
- "immediate",
28
- "keep-tokens",
29
- "include-deleted",
30
- "include-archived",
31
- "include-left",
32
- "json",
33
- "mirrored",
34
- "no-collision",
35
- "no-invite",
36
- "no-join",
37
- "open",
38
- "refresh",
39
- "resend",
40
- "restore",
41
- "revoke",
42
- "send-email",
43
- "skill-only",
44
- "spec-only",
45
- "starter-only",
46
- "state-funding",
47
- "even-installments",
48
- "supersede",
49
- "unlink",
50
- "visual-only",
51
- "whole-family",
52
- "wait",
53
- ]);
54
- const REPEATABLE_FLAGS = new Set(["bill-date", "kid", "note", "unassign"]);
55
- const GLOBAL_FLAGS = new Set([
56
- "deliver",
57
- "help",
58
- "json",
59
- "operation-key",
60
- "profile",
61
- "reason",
62
- ]);
2
+ import { BOOLEAN_FLAGS, REPEATABLE_FLAGS } from "./args.js";
3
+ import { COMMAND_SUMMARIES, NOUN_SUMMARIES } from "./help.js";
4
+ export const AGENT_CONTEXT_SCHEMA_VERSION = "5";
63
5
  const GLOBAL_FLAG_TYPES = {
64
6
  deliver: "string",
65
7
  help: "boolean",
66
8
  json: "boolean",
9
+ "no-json": "boolean",
67
10
  "operation-key": "string",
11
+ pretty: "boolean",
68
12
  profile: "string",
69
13
  reason: "string",
70
14
  };
15
+ const GLOBAL_FLAGS = new Set(Object.keys(GLOBAL_FLAG_TYPES));
16
+ /** Output/transport flags that mean nothing over hosted MCP. */
17
+ const LOCAL_ONLY_FLAGS = ["json", "no-json", "pretty", "profile", "deliver"];
71
18
  export const RECESS_MCP_SCOPES = {
72
19
  templatesRead: "recess:goal-templates:read",
73
20
  templatesWrite: "recess:goal-templates:write",
@@ -135,6 +82,7 @@ const REMOTE_CONFIRMATION_COMMANDS = new Set([
135
82
  const LOCAL_COMMAND_NOUNS = new Set([
136
83
  "--version",
137
84
  "agent-context",
85
+ "help",
138
86
  "auth",
139
87
  "doctor",
140
88
  "feedback",
@@ -144,6 +92,8 @@ const LOCAL_COMMAND_NOUNS = new Set([
144
92
  "update",
145
93
  ]);
146
94
  const AUTHENTICATED_COMMAND_PREFIXES = [
95
+ // Replays a preview this machine staged; the replayed command re-checks scope.
96
+ "confirm",
147
97
  "village build",
148
98
  "village library",
149
99
  "village objects",
@@ -163,12 +113,18 @@ const FAMILY_AI_COMMANDS = new Set([
163
113
  "chat-logs get",
164
114
  "chat-logs list",
165
115
  "content-library search",
116
+ "goal-templates answers-template",
166
117
  "goal-templates apply",
167
118
  "goal-templates apply-starter",
168
119
  "goal-templates capture-snapshot",
169
120
  "goal-templates create",
121
+ // set-metadata/delete/patch-spec: the server lets a non-staff author touch
122
+ // only their own PRIVATE templates.
123
+ "goal-templates delete",
170
124
  "goal-templates get",
171
125
  "goal-templates list",
126
+ "goal-templates patch-spec",
127
+ "goal-templates set-metadata",
172
128
  "goal-templates snapshot-files",
173
129
  "goal-templates validate-spec",
174
130
  "goals adaptations diff",
@@ -234,11 +190,10 @@ const STAFF_COMMANDS = new Set([
234
190
  "events add",
235
191
  "events cancel",
236
192
  "events get",
193
+ "events list",
237
194
  "events reschedule",
238
195
  "events set-status",
239
196
  "events take-attendance",
240
- "goal-templates delete",
241
- "goal-templates set-metadata",
242
197
  "goal-templates versions",
243
198
  "goals complete",
244
199
  "goals undo-completion",
@@ -307,6 +262,7 @@ const STAFF_COMMANDS = new Set([
307
262
  "store-items list",
308
263
  "students upload-map-scores",
309
264
  "students issue-email",
265
+ "students notes add",
310
266
  "students todos",
311
267
  "students analysis",
312
268
  "todos complete",
@@ -483,6 +439,7 @@ export function buildCommandSchema(help) {
483
439
  return {
484
440
  path,
485
441
  usage,
442
+ summary: COMMAND_SUMMARIES[pathKey] ?? "",
486
443
  flags: { ...flags, ...remoteFlags },
487
444
  positionals,
488
445
  access: commandAccess(path),
@@ -521,11 +478,190 @@ const REMOTE_HELP_NOTES = [
521
478
  "Results include the resolved date/timezone and pagination. If hasMore, repeat with --cursor nextCursor and the same filters; use the resolved date when paging today.",
522
479
  "Report recorded todo statuses only. These results do not establish account creation, complete activity history, or whether work happened outside Recess.",
523
480
  ];
524
- export function scopedHelp(_help, commands, scope, context, options = {}) {
481
+ /**
482
+ * Usage notes by noun, parsed from the prose after HELP's usage block.
483
+ * A "<Label> notes:" paragraph attaches to NOTE_LABEL_NOUNS[label]; an
484
+ * unlabeled paragraph opening with a quoted command ("users lock" …) attaches
485
+ * to that noun; anything else is global (shown with root help).
486
+ */
487
+ const NOTE_LABEL_NOUNS = {
488
+ Authoring: ["goal-templates", "goals", "skills"],
489
+ "School-onboarding workflow": ["onboarding", "school"],
490
+ "Parent SMS summary": ["students"],
491
+ Onboarding: ["onboarding"],
492
+ "Class-ops": ["events"],
493
+ Channel: ["channels"],
494
+ "Family address": ["families"],
495
+ "Tuition-plan": ["tuition-plans"],
496
+ Payout: ["payout"],
497
+ Auth: ["auth"],
498
+ Skill: ["setup", "doctor"],
499
+ };
500
+ export function parseHelpNotes(help) {
501
+ const notes = { global: [], byNoun: new Map() };
502
+ const usageEnd = help.indexOf("\n\n", help.indexOf("Usage:"));
503
+ if (usageEnd < 0)
504
+ return notes;
505
+ for (const paragraph of help.slice(usageEnd).split(/\n\s*\n/)) {
506
+ const text = paragraph.trim();
507
+ if (!text)
508
+ continue;
509
+ const label = text.match(/^([A-Z][\w -]*?) notes:/)?.[1];
510
+ const quotedNoun = text.match(/^"([a-z][a-z-]*)[ "]/)?.[1];
511
+ const nouns = label
512
+ ? (NOTE_LABEL_NOUNS[label] ?? [])
513
+ : quotedNoun
514
+ ? [quotedNoun]
515
+ : [];
516
+ if (nouns.length === 0) {
517
+ notes.global.push(text);
518
+ continue;
519
+ }
520
+ for (const noun of nouns) {
521
+ notes.byNoun.set(noun, [...(notes.byNoun.get(noun) ?? []), text]);
522
+ }
523
+ }
524
+ return notes;
525
+ }
526
+ function unwrapParagraph(text) {
527
+ return text.replace(/\s*\n\s*/g, " ");
528
+ }
529
+ const ACCESS_RANK = {
530
+ local: 0,
531
+ authenticated: 1,
532
+ family_ai: 2,
533
+ staff: 3,
534
+ admin: 4,
535
+ };
536
+ const ACCESS_NEEDS = {
537
+ local: "no session",
538
+ authenticated: "any signed-in session",
539
+ family_ai: "a family_ai session (a guardian with access:ai), a guide, or an admin",
540
+ staff: "a staff session (guide or admin)",
541
+ admin: "an admin session (full_admin)",
542
+ };
543
+ /** The least-privileged access that reaches any command under `scope`. */
544
+ function scopeNeeds(commands) {
545
+ return commands.reduce((lowest, command) => ACCESS_RANK[command.access] < ACCESS_RANK[lowest]
546
+ ? command.access
547
+ : lowest, "admin");
548
+ }
549
+ function editDistance(left, right) {
550
+ let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
551
+ for (let row = 1; row <= left.length; row += 1) {
552
+ const current = [row];
553
+ for (let column = 1; column <= right.length; column += 1) {
554
+ current[column] = Math.min(previous[column] + 1, current[column - 1] + 1, previous[column - 1] + (left[row - 1] === right[column - 1] ? 0 : 1));
555
+ }
556
+ previous = current;
557
+ }
558
+ return previous[right.length];
559
+ }
560
+ /**
561
+ * Closest command paths (or noun/verb prefixes) to what was typed:
562
+ * `biling pause` → `billing pause`, `help biling` → `billing`. Each candidate is
563
+ * compared against the same number of typed words, so a typo in the noun OR
564
+ * the verb still lands. `closest` is set only for a genuine near-miss; otherwise
565
+ * `suggestions` falls back to the typed noun's commands, then the nearest nouns.
566
+ */
567
+ export function suggestCommands(typed, commands, limit = 8) {
568
+ const paths = commands
569
+ .filter((command) => command.path[0] !== "--version")
570
+ .map((command) => command.path);
571
+ const candidates = Array.from(new Set(paths.flatMap((path) => path.map((_, index) => path.slice(0, index + 1).join(" ")))));
572
+ if (typed.length === 0)
573
+ return { suggestions: candidates.slice(0, limit) };
574
+ const scored = candidates
575
+ .map((candidate) => {
576
+ const words = candidate.split(" ").length;
577
+ const input = typed.slice(0, words).join(" ");
578
+ return {
579
+ candidate,
580
+ words,
581
+ distance: editDistance(input, candidate),
582
+ budget: Math.max(2, Math.floor(candidate.length / 4)),
583
+ };
584
+ })
585
+ .filter((entry) => entry.distance > 0 && entry.distance <= entry.budget)
586
+ .sort((left, right) => left.distance - right.distance || right.words - left.words);
587
+ if (scored.length > 0) {
588
+ const best = scored[0].distance;
589
+ return {
590
+ closest: scored[0].candidate,
591
+ suggestions: scored
592
+ .filter((entry) => entry.distance <= best + 1)
593
+ .slice(0, limit)
594
+ .map((entry) => entry.candidate),
595
+ };
596
+ }
597
+ const sameNoun = Array.from(new Set(paths.filter((path) => path[0] === typed[0]).map((path) => path.join(" "))));
598
+ if (sameNoun.length > 0)
599
+ return { suggestions: sameNoun.slice(0, 12) };
600
+ const nouns = Array.from(new Set(paths.map((path) => path[0])));
601
+ return {
602
+ suggestions: nouns
603
+ .map((noun) => ({ noun, distance: editDistance(typed[0], noun) }))
604
+ .sort((left, right) => left.distance - right.distance)
605
+ .slice(0, 5)
606
+ .map((entry) => entry.noun),
607
+ };
608
+ }
609
+ /**
610
+ * Nothing under `scope` is visible to this session. Say whether it does not
611
+ * exist (with suggestions) or exists but needs sign-in / a wider scope.
612
+ */
613
+ function unavailableScopeError(allCommands, scope, context, helpCommand) {
614
+ const label = scope.join(" ");
615
+ const existing = allCommands.filter((command) => pathStartsWith(command.path, scope));
616
+ if (existing.length > 0) {
617
+ const needs = ACCESS_NEEDS[scopeNeeds(existing)];
618
+ const message = context.scope
619
+ ? `\`${label}\` exists but needs ${needs}; this session is ${context.role} (${context.scope}).`
620
+ : `\`${label}\` exists but needs ${needs}. ${context.source === "unavailable"
621
+ ? "The stored session could not be read"
622
+ : "You are signed out"} — run \`recess auth login\` (or \`recess auth request\` when headless), then retry.`;
623
+ return new CliError("command_unavailable", message, 1, {
624
+ requires: scopeNeeds(existing),
625
+ session: context,
626
+ });
627
+ }
628
+ const { suggestions, closest } = suggestCommands(scope, allCommands);
629
+ return new CliError("unknown_command", `Unknown command: ${label}.${closest ? ` Did you mean \`${closest}\`?` : ""} Run \`${helpCommand}\` for available commands.`, 1, suggestions.length > 0 ? { suggestions } : undefined);
630
+ }
631
+ function isWrite(command, remote = false) {
632
+ return ("confirm" in command.flags ||
633
+ (remote && REMOTE_CONFIRMATION_COMMANDS.has(command.path.join(" "))));
634
+ }
635
+ /** Nouns whose usage stays inline in the compact root help. */
636
+ const ROOT_GLOBAL_NOUNS = new Set([
637
+ "--version",
638
+ "help",
639
+ "agent-context",
640
+ "confirm",
641
+ "setup",
642
+ "doctor",
643
+ "update",
644
+ ]);
645
+ function nounIndex(commands) {
646
+ const counts = new Map();
647
+ for (const command of commands) {
648
+ const noun = command.path[0];
649
+ if (ROOT_GLOBAL_NOUNS.has(noun))
650
+ continue;
651
+ counts.set(noun, (counts.get(noun) ?? 0) + 1);
652
+ }
653
+ const width = Math.max(...Array.from(counts.keys(), (noun) => noun.length));
654
+ return Array.from(counts, ([noun, count]) => ` ${`${noun} (${count})`.padEnd(width + 6)}${NOUN_SUMMARIES[noun] ?? ""}`.trimEnd());
655
+ }
656
+ const LOCAL_CONVENTIONS = "--reason TEXT says why (audit-logged): ✎ writes require it, reads default it. Writes preview and exit 2; after human approval run `recess confirm <operation-key>` (replays the stored preview) or rerun with --confirm --operation-key KEY.";
657
+ export function scopedHelp(help, commands, scope, context, options = {}) {
525
658
  const matches = commands.filter((command) => pathStartsWith(command.path, scope) &&
526
659
  commandIsAvailable(command, context.scope));
660
+ // Root help is what an agent reads first: global commands + one line per
661
+ // noun. `--all` (and hosted MCP's small catalog) keep the full listing.
662
+ const compactRoot = scope.length === 0 && !options.all && !options.remoteOnly;
527
663
  if (matches.length === 0) {
528
- throw new CliError("unknown_command", `Unknown command scope: ${scope.join(" ")}. Run \`${options.remoteOnly ? "help" : "recess --help"}\` for available commands.`);
664
+ throw unavailableScopeError(commands, scope, context, options.remoteOnly ? "help" : "recess --help");
529
665
  }
530
666
  const uniqueUsages = Array.from(new Map(matches.map((command) => [command.usage, command])).values());
531
667
  const accessLabel = context.scope
@@ -533,22 +669,64 @@ export function scopedHelp(_help, commands, scope, context, options = {}) {
533
669
  : context.source === "unavailable"
534
670
  ? "session unavailable (local and authentication commands only)"
535
671
  : "signed out (local and authentication commands only)";
672
+ const notes = parseHelpNotes(help);
673
+ const nounNotes = scope[0] ? (notes.byNoun.get(scope[0]) ?? []) : [];
674
+ const summaryFor = (usage) => {
675
+ const sharing = matches.filter((command) => command.usage === usage);
676
+ const summaries = Array.from(new Set(sharing.map((command) => command.summary).filter(Boolean)));
677
+ return summaries.length > 1
678
+ ? sharing
679
+ .map((command) => `${command.path.at(-1)}: ${command.summary}`)
680
+ .join(" ")
681
+ : (summaries[0] ?? "");
682
+ };
536
683
  return [
537
684
  scope.length > 0
538
685
  ? `recess ${scope.join(" ")} — command help`
539
686
  : "recess — safe Recess administration and family AI tools",
540
687
  "",
541
688
  `Access: ${accessLabel}`,
542
- "Key: ◇ shared command ◆ admin-only command",
689
+ "Key: ◇ shared command ◆ admin-only command ✎ write (previews; needs confirmation)",
690
+ ...(options.remoteOnly ? [] : [LOCAL_CONVENTIONS]),
543
691
  "",
544
692
  "Usage:",
545
- ...uniqueUsages.flatMap((command) => wrapUsage(options.remoteOnly ? remoteUsage(command) : command.usage, command.access === "admin" ? "◆" : "◇")),
693
+ ...(compactRoot
694
+ ? uniqueUsages.filter((command) => ROOT_GLOBAL_NOUNS.has(command.path[0]))
695
+ : uniqueUsages).flatMap((command) => {
696
+ const summary = summaryFor(command.usage);
697
+ const write = isWrite(command, options.remoteOnly);
698
+ return [
699
+ ...wrapUsage(options.remoteOnly ? remoteUsage(command) : command.usage, command.access === "admin" ? "◆" : "◇"),
700
+ ...(summary || write
701
+ ? [` ${write ? "✎ " : ""}${summary}`.trimEnd()]
702
+ : []),
703
+ ];
704
+ }),
705
+ ...(compactRoot
706
+ ? [
707
+ "",
708
+ ...notes.global.flatMap((text) => [text, ""]),
709
+ "Commands by noun:",
710
+ ...nounIndex(matches),
711
+ ]
712
+ : []),
546
713
  "",
547
714
  options.remoteOnly
548
715
  ? "Run `help <noun> [verb]` for a focused list."
549
- : "Run `recess help <noun> [verb]` for a focused list.",
550
- ...(options.remoteOnly ? ["", ...REMOTE_HELP_NOTES] : []),
551
- ].join("\n");
716
+ : compactRoot
717
+ ? "Run `recess help <noun>` for commands, flags, and notes; `recess help --all` for everything."
718
+ : "Run `recess help <noun> [verb]` for a focused list and that noun's notes.",
719
+ ...(nounNotes.length > 0
720
+ ? ["", "Notes:", ...nounNotes.flatMap((text) => [text, ""])]
721
+ : []),
722
+ ...(options.remoteOnly
723
+ ? ["", ...REMOTE_HELP_NOTES]
724
+ : scope.length === 0 && !compactRoot
725
+ ? ["", ...notes.global.flatMap((text) => [text, ""])]
726
+ : []),
727
+ ]
728
+ .join("\n")
729
+ .trimEnd();
552
730
  }
553
731
  export function remoteCommands(commands) {
554
732
  return commands.filter((command) => command.remoteCapable);
@@ -575,12 +753,8 @@ export function validateInvocation(parsed, commands, options = {}) {
575
753
  const command = findCommandSchema(commands, parsed.positionals);
576
754
  if (!command) {
577
755
  const scope = parsed.positionals.join(" ");
578
- const first = parsed.positionals[0];
579
- const suggestions = commands
580
- .filter((candidate) => !first || candidate.path[0] === first)
581
- .slice(0, 12)
582
- .map((candidate) => candidate.path.join(" "));
583
- throw new CliError("unknown_command", `Unknown command: ${scope || "(none)"}.`, 1, suggestions.length > 0 ? { suggestions } : undefined);
756
+ const { suggestions, closest } = suggestCommands(parsed.positionals, commands);
757
+ throw new CliError("unknown_command", `Unknown command: ${scope || "(none)"}.${closest ? ` Did you mean \`${closest}\`?` : ""}`, 1, suggestions.length > 0 ? { suggestions } : undefined);
584
758
  }
585
759
  const usage = options.remote ? remoteUsage(command) : command.usage;
586
760
  const remoteConfirmation = options.remote && REMOTE_CONFIRMATION_COMMANDS.has(command.path.join(" "));
@@ -588,8 +762,7 @@ export function validateInvocation(parsed, commands, options = {}) {
588
762
  ...Object.keys(command.flags),
589
763
  ...GLOBAL_FLAGS,
590
764
  ...(remoteConfirmation ? ["confirm"] : []),
591
- ].filter((flag) => !options.remote ||
592
- !["json", "profile", "deliver", "file"].includes(flag)));
765
+ ].filter((flag) => !options.remote || ![...LOCAL_ONLY_FLAGS, "file"].includes(flag)));
593
766
  const unknown = Array.from(parsed.flags.keys()).filter((name) => name !== "version" && !allowed.has(name));
594
767
  if (unknown.length > 0) {
595
768
  const validFlags = Array.from(allowed)
@@ -622,40 +795,119 @@ export function validateInvocation(parsed, commands, options = {}) {
622
795
  }
623
796
  return command;
624
797
  }
798
+ /** Positional placeholders (`<user-id>`, `[dir]`) between the path and the first flag. */
799
+ function positionalArgs(command) {
800
+ const rest = command.usage
801
+ .replace(/^recess\s+(?:\[--json\]\s+)?/, "")
802
+ .split(/\s+/)
803
+ .slice(command.path.length);
804
+ const args = [];
805
+ for (const token of rest) {
806
+ if (/^(?:<[^>]+>|\[<[^>]+>(?:\.\.\.)?\]|\[[a-z][a-z0-9-]*\])$/.test(token)) {
807
+ args.push(token);
808
+ continue;
809
+ }
810
+ break;
811
+ }
812
+ return args;
813
+ }
814
+ function remoteFlags(command) {
815
+ const flags = Object.fromEntries(Object.entries(command.flags).filter(([name]) => !["json", "file"].includes(name)));
816
+ return REMOTE_CONFIRMATION_COMMANDS.has(command.path.join(" "))
817
+ ? {
818
+ ...flags,
819
+ confirm: { type: "boolean", repeatable: false, required: false },
820
+ }
821
+ : flags;
822
+ }
823
+ /**
824
+ * The agent's command catalog, filtered to the session's scope.
825
+ *
826
+ * Default is COMPACT — per command only its summary, positional args, required
827
+ * flags, and whether it is a confirmation-gated write — because the full
828
+ * catalog runs ~170 KB for an admin. `scope` (`agent-context goals`) narrows to
829
+ * one noun and adds its usage line and notes; `full` restores every flag
830
+ * schema (the v4 shape plus `summary`).
831
+ */
625
832
  export function agentContext(commands, options) {
626
- return {
627
- schema_version: AGENT_CONTEXT_SCHEMA_VERSION,
628
- cli_version: options.cliVersion,
629
- session: options.discovery,
630
- commands: Object.fromEntries(commands
631
- .filter((command) => !options.remoteOnly || command.remoteCapable)
632
- .filter((command) => command.path[0] !== "--version" &&
633
- commandIsAvailable(command, options.discovery.scope))
634
- .map((command) => [
635
- command.path.join(" "),
636
- {
637
- usage: options.remoteOnly ? remoteUsage(command) : command.usage,
638
- flags: options.remoteOnly &&
639
- REMOTE_CONFIRMATION_COMMANDS.has(command.path.join(" "))
640
- ? {
641
- ...Object.fromEntries(Object.entries(command.flags).filter(([name]) => !["json", "file"].includes(name))),
642
- confirm: {
643
- type: "boolean",
644
- repeatable: false,
645
- required: false,
646
- },
647
- }
648
- : options.remoteOnly
649
- ? Object.fromEntries(Object.entries(command.flags).filter(([name]) => !["json", "file"].includes(name)))
650
- : command.flags,
833
+ const scope = options.scope ?? [];
834
+ const remote = options.remoteOnly === true;
835
+ const visible = commands
836
+ .filter((command) => !remote || command.remoteCapable)
837
+ .filter((command) => command.path[0] !== "--version" &&
838
+ commandIsAvailable(command, options.discovery.scope));
839
+ const selected = visible.filter((command) => pathStartsWith(command.path, scope));
840
+ if (scope.length > 0 && selected.length === 0) {
841
+ throw unavailableScopeError(remote ? commands.filter((command) => command.remoteCapable) : commands, scope, options.discovery, remote ? "agent-context" : "recess agent-context");
842
+ }
843
+ const notes = options.help ? parseHelpNotes(options.help) : null;
844
+ const nouns = Array.from(new Set(selected.map((command) => command.path[0])));
845
+ const noteEntries = notes
846
+ ? Object.fromEntries(nouns
847
+ .filter(() => scope.length > 0 || options.full)
848
+ .map((noun) => [
849
+ noun,
850
+ (notes.byNoun.get(noun) ?? []).map(unwrapParagraph),
851
+ ])
852
+ .filter(([, entries]) => entries.length > 0))
853
+ : {};
854
+ const usageOf = (command) => remote
855
+ ? remoteUsage(command)
856
+ : command.usage.replace(/^recess\s+(?:\[--json\]\s+)?/, "");
857
+ const entry = (command) => {
858
+ if (options.full) {
859
+ return {
860
+ summary: command.summary,
861
+ usage: remote ? remoteUsage(command) : command.usage,
862
+ flags: remote ? remoteFlags(command) : command.flags,
651
863
  positionals: command.positionals,
652
864
  access: command.access,
653
865
  admin_only: command.access === "admin",
654
866
  remote_capable: command.remoteCapable,
655
867
  oauth_scopes: command.oauthScopes,
656
- },
657
- ])),
658
- global_flags: options.remoteOnly
868
+ };
869
+ }
870
+ const write = isWrite(command, remote) ? { write: true } : {};
871
+ // One noun is small enough to carry its exact syntax, which subsumes the
872
+ // args/required digest.
873
+ if (scope.length > 0) {
874
+ return { summary: command.summary, usage: usageOf(command), ...write };
875
+ }
876
+ const args = positionalArgs(command);
877
+ const required = Object.entries(command.flags)
878
+ .filter(([, flag]) => flag.required)
879
+ .map(([name]) => `--${name}`);
880
+ return {
881
+ summary: command.summary,
882
+ ...(args.length > 0 ? { args } : {}),
883
+ ...(required.length > 0 ? { required } : {}),
884
+ ...write,
885
+ };
886
+ };
887
+ return {
888
+ schema_version: AGENT_CONTEXT_SCHEMA_VERSION,
889
+ cli_version: options.cliVersion,
890
+ session: options.discovery,
891
+ detail: options.full ? "full" : "compact",
892
+ ...(options.full
893
+ ? {}
894
+ : {
895
+ hint: remote
896
+ ? "Compact catalog. `agent-context <noun>` adds usage and notes for one noun; `agent-context --full` returns every flag schema; `help <noun>` is the human view."
897
+ : "Compact catalog. `recess agent-context <noun>` adds usage and notes for one noun; `--full` returns every flag schema; `recess help <noun>` is the human view.",
898
+ }),
899
+ ...(remote
900
+ ? { instructions: REMOTE_HELP_NOTES }
901
+ : {
902
+ conventions: [
903
+ "--reason TEXT (1–1024 characters, audit-logged) is required on write: true commands; reads default it to `Read: <command>`.",
904
+ "write: true commands preview and exit 2; after human approval run `recess confirm <operation-key>` (replays the stored preview) or rerun with --confirm --operation-key KEY.",
905
+ "Output is a JSON envelope when stdout is not a terminal or RECESS_CLI_JSON=1; --pretty forces human output.",
906
+ ],
907
+ }),
908
+ commands: Object.fromEntries(selected.map((command) => [command.path.join(" "), entry(command)])),
909
+ ...(Object.keys(noteEntries).length > 0 ? { notes: noteEntries } : {}),
910
+ global_flags: remote
659
911
  ? {
660
912
  "--operation-key": { type: "string" },
661
913
  "--reason": {
@@ -667,19 +919,19 @@ export function agentContext(commands, options) {
667
919
  }
668
920
  : {
669
921
  "--json": { type: "boolean" },
922
+ "--pretty": { type: "boolean", alias: "--no-json" },
670
923
  "--profile": { type: "string" },
671
924
  "--operation-key": { type: "string" },
672
925
  "--reason": {
673
926
  type: "string",
674
- required_for: "every Recess API request except authentication",
927
+ required_for: "confirmation-gated writes; reads and auth default it",
675
928
  max_length: 1024,
676
929
  },
677
930
  "--deliver": { type: "enum", values: ["stdout", "file:<path>"] },
678
931
  "--help": { type: "boolean" },
679
932
  },
680
- ...(options.remoteOnly ? { instructions: REMOTE_HELP_NOTES } : {}),
681
933
  available_profiles: options.availableProfiles,
682
- ...(options.remoteOnly
934
+ ...(remote
683
935
  ? {}
684
936
  : {
685
937
  jobs: { commands: ["jobs list", "jobs get", "jobs prune"] },
@@ -125,9 +125,12 @@ export async function runApplicationsCommand({ parsed, api, writeCommand, }) {
125
125
  if (noun === "applications" && verb === "qualify") {
126
126
  const applicationId = positional(parsed, 2, "application ID");
127
127
  const qualityOverride = assertChoice(flagString(parsed, "quality", { required: true }), APPLICATION_QUALITIES, "--quality");
128
- const reason = flagString(parsed, "reason", { required: true }).trim();
128
+ // --override-reason is stored on the application; --reason (audit) is the
129
+ // fallback only for older invocations.
130
+ const reason = (flagString(parsed, "override-reason") ??
131
+ flagString(parsed, "reason", { required: true })).trim();
129
132
  if (!reason) {
130
- throw new CliError("invalid_arguments", "--reason must not be empty.");
133
+ throw new CliError("invalid_arguments", "--override-reason must not be empty.");
131
134
  }
132
135
  const body = { qualityOverride, reason };
133
136
  return writeCommand(parsed, {
@@ -190,9 +193,12 @@ export async function runApplicationsCommand({ parsed, api, writeCommand, }) {
190
193
  }
191
194
  if (noun === "applications" && verb === "close") {
192
195
  const applicationId = positional(parsed, 2, "application ID");
193
- const reason = flagString(parsed, "reason", { required: true }).trim();
196
+ // --close-reason is stored on the application; --reason (audit) is the
197
+ // fallback only for older invocations.
198
+ const reason = (flagString(parsed, "close-reason") ??
199
+ flagString(parsed, "reason", { required: true })).trim();
194
200
  if (!reason) {
195
- throw new CliError("invalid_arguments", "--reason must not be empty.");
201
+ throw new CliError("invalid_arguments", "--close-reason must not be empty.");
196
202
  }
197
203
  const body = { reason };
198
204
  return writeCommand(parsed, {