recess-cli 3.10.0 → 3.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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",
@@ -182,6 +138,7 @@ const FAMILY_AI_COMMANDS = new Set([
182
138
  "goals files push",
183
139
  "goals files read",
184
140
  "goals files write",
141
+ "goals launch-todo",
185
142
  "goals list",
186
143
  "goals move-module",
187
144
  "goals pdf upload",
@@ -238,8 +195,6 @@ const STAFF_COMMANDS = new Set([
238
195
  "events reschedule",
239
196
  "events set-status",
240
197
  "events take-attendance",
241
- "goal-templates delete",
242
- "goal-templates set-metadata",
243
198
  "goal-templates versions",
244
199
  "goals complete",
245
200
  "goals undo-completion",
@@ -308,6 +263,7 @@ const STAFF_COMMANDS = new Set([
308
263
  "store-items list",
309
264
  "students upload-map-scores",
310
265
  "students issue-email",
266
+ "students notes add",
311
267
  "students todos",
312
268
  "students analysis",
313
269
  "todos complete",
@@ -484,6 +440,7 @@ export function buildCommandSchema(help) {
484
440
  return {
485
441
  path,
486
442
  usage,
443
+ summary: COMMAND_SUMMARIES[pathKey] ?? "",
487
444
  flags: { ...flags, ...remoteFlags },
488
445
  positionals,
489
446
  access: commandAccess(path),
@@ -522,11 +479,190 @@ const REMOTE_HELP_NOTES = [
522
479
  "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.",
523
480
  "Report recorded todo statuses only. These results do not establish account creation, complete activity history, or whether work happened outside Recess.",
524
481
  ];
525
- export function scopedHelp(_help, commands, scope, context, options = {}) {
482
+ /**
483
+ * Usage notes by noun, parsed from the prose after HELP's usage block.
484
+ * A "<Label> notes:" paragraph attaches to NOTE_LABEL_NOUNS[label]; an
485
+ * unlabeled paragraph opening with a quoted command ("users lock" …) attaches
486
+ * to that noun; anything else is global (shown with root help).
487
+ */
488
+ const NOTE_LABEL_NOUNS = {
489
+ Authoring: ["goal-templates", "goals", "skills"],
490
+ "School-onboarding workflow": ["onboarding", "school"],
491
+ "Parent SMS summary": ["students"],
492
+ Onboarding: ["onboarding"],
493
+ "Class-ops": ["events"],
494
+ Channel: ["channels"],
495
+ "Family address": ["families"],
496
+ "Tuition-plan": ["tuition-plans"],
497
+ Payout: ["payout"],
498
+ Auth: ["auth"],
499
+ Skill: ["setup", "doctor"],
500
+ };
501
+ export function parseHelpNotes(help) {
502
+ const notes = { global: [], byNoun: new Map() };
503
+ const usageEnd = help.indexOf("\n\n", help.indexOf("Usage:"));
504
+ if (usageEnd < 0)
505
+ return notes;
506
+ for (const paragraph of help.slice(usageEnd).split(/\n\s*\n/)) {
507
+ const text = paragraph.trim();
508
+ if (!text)
509
+ continue;
510
+ const label = text.match(/^([A-Z][\w -]*?) notes:/)?.[1];
511
+ const quotedNoun = text.match(/^"([a-z][a-z-]*)[ "]/)?.[1];
512
+ const nouns = label
513
+ ? (NOTE_LABEL_NOUNS[label] ?? [])
514
+ : quotedNoun
515
+ ? [quotedNoun]
516
+ : [];
517
+ if (nouns.length === 0) {
518
+ notes.global.push(text);
519
+ continue;
520
+ }
521
+ for (const noun of nouns) {
522
+ notes.byNoun.set(noun, [...(notes.byNoun.get(noun) ?? []), text]);
523
+ }
524
+ }
525
+ return notes;
526
+ }
527
+ function unwrapParagraph(text) {
528
+ return text.replace(/\s*\n\s*/g, " ");
529
+ }
530
+ const ACCESS_RANK = {
531
+ local: 0,
532
+ authenticated: 1,
533
+ family_ai: 2,
534
+ staff: 3,
535
+ admin: 4,
536
+ };
537
+ const ACCESS_NEEDS = {
538
+ local: "no session",
539
+ authenticated: "any signed-in session",
540
+ family_ai: "a family_ai session (a guardian with access:ai), a guide, or an admin",
541
+ staff: "a staff session (guide or admin)",
542
+ admin: "an admin session (full_admin)",
543
+ };
544
+ /** The least-privileged access that reaches any command under `scope`. */
545
+ function scopeNeeds(commands) {
546
+ return commands.reduce((lowest, command) => ACCESS_RANK[command.access] < ACCESS_RANK[lowest]
547
+ ? command.access
548
+ : lowest, "admin");
549
+ }
550
+ function editDistance(left, right) {
551
+ let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
552
+ for (let row = 1; row <= left.length; row += 1) {
553
+ const current = [row];
554
+ for (let column = 1; column <= right.length; column += 1) {
555
+ current[column] = Math.min(previous[column] + 1, current[column - 1] + 1, previous[column - 1] + (left[row - 1] === right[column - 1] ? 0 : 1));
556
+ }
557
+ previous = current;
558
+ }
559
+ return previous[right.length];
560
+ }
561
+ /**
562
+ * Closest command paths (or noun/verb prefixes) to what was typed:
563
+ * `biling pause` → `billing pause`, `help biling` → `billing`. Each candidate is
564
+ * compared against the same number of typed words, so a typo in the noun OR
565
+ * the verb still lands. `closest` is set only for a genuine near-miss; otherwise
566
+ * `suggestions` falls back to the typed noun's commands, then the nearest nouns.
567
+ */
568
+ export function suggestCommands(typed, commands, limit = 8) {
569
+ const paths = commands
570
+ .filter((command) => command.path[0] !== "--version")
571
+ .map((command) => command.path);
572
+ const candidates = Array.from(new Set(paths.flatMap((path) => path.map((_, index) => path.slice(0, index + 1).join(" ")))));
573
+ if (typed.length === 0)
574
+ return { suggestions: candidates.slice(0, limit) };
575
+ const scored = candidates
576
+ .map((candidate) => {
577
+ const words = candidate.split(" ").length;
578
+ const input = typed.slice(0, words).join(" ");
579
+ return {
580
+ candidate,
581
+ words,
582
+ distance: editDistance(input, candidate),
583
+ budget: Math.max(2, Math.floor(candidate.length / 4)),
584
+ };
585
+ })
586
+ .filter((entry) => entry.distance > 0 && entry.distance <= entry.budget)
587
+ .sort((left, right) => left.distance - right.distance || right.words - left.words);
588
+ if (scored.length > 0) {
589
+ const best = scored[0].distance;
590
+ return {
591
+ closest: scored[0].candidate,
592
+ suggestions: scored
593
+ .filter((entry) => entry.distance <= best + 1)
594
+ .slice(0, limit)
595
+ .map((entry) => entry.candidate),
596
+ };
597
+ }
598
+ const sameNoun = Array.from(new Set(paths.filter((path) => path[0] === typed[0]).map((path) => path.join(" "))));
599
+ if (sameNoun.length > 0)
600
+ return { suggestions: sameNoun.slice(0, 12) };
601
+ const nouns = Array.from(new Set(paths.map((path) => path[0])));
602
+ return {
603
+ suggestions: nouns
604
+ .map((noun) => ({ noun, distance: editDistance(typed[0], noun) }))
605
+ .sort((left, right) => left.distance - right.distance)
606
+ .slice(0, 5)
607
+ .map((entry) => entry.noun),
608
+ };
609
+ }
610
+ /**
611
+ * Nothing under `scope` is visible to this session. Say whether it does not
612
+ * exist (with suggestions) or exists but needs sign-in / a wider scope.
613
+ */
614
+ function unavailableScopeError(allCommands, scope, context, helpCommand) {
615
+ const label = scope.join(" ");
616
+ const existing = allCommands.filter((command) => pathStartsWith(command.path, scope));
617
+ if (existing.length > 0) {
618
+ const needs = ACCESS_NEEDS[scopeNeeds(existing)];
619
+ const message = context.scope
620
+ ? `\`${label}\` exists but needs ${needs}; this session is ${context.role} (${context.scope}).`
621
+ : `\`${label}\` exists but needs ${needs}. ${context.source === "unavailable"
622
+ ? "The stored session could not be read"
623
+ : "You are signed out"} — run \`recess auth login\` (or \`recess auth request\` when headless), then retry.`;
624
+ return new CliError("command_unavailable", message, 1, {
625
+ requires: scopeNeeds(existing),
626
+ session: context,
627
+ });
628
+ }
629
+ const { suggestions, closest } = suggestCommands(scope, allCommands);
630
+ return new CliError("unknown_command", `Unknown command: ${label}.${closest ? ` Did you mean \`${closest}\`?` : ""} Run \`${helpCommand}\` for available commands.`, 1, suggestions.length > 0 ? { suggestions } : undefined);
631
+ }
632
+ function isWrite(command, remote = false) {
633
+ return ("confirm" in command.flags ||
634
+ (remote && REMOTE_CONFIRMATION_COMMANDS.has(command.path.join(" "))));
635
+ }
636
+ /** Nouns whose usage stays inline in the compact root help. */
637
+ const ROOT_GLOBAL_NOUNS = new Set([
638
+ "--version",
639
+ "help",
640
+ "agent-context",
641
+ "confirm",
642
+ "setup",
643
+ "doctor",
644
+ "update",
645
+ ]);
646
+ function nounIndex(commands) {
647
+ const counts = new Map();
648
+ for (const command of commands) {
649
+ const noun = command.path[0];
650
+ if (ROOT_GLOBAL_NOUNS.has(noun))
651
+ continue;
652
+ counts.set(noun, (counts.get(noun) ?? 0) + 1);
653
+ }
654
+ const width = Math.max(...Array.from(counts.keys(), (noun) => noun.length));
655
+ return Array.from(counts, ([noun, count]) => ` ${`${noun} (${count})`.padEnd(width + 6)}${NOUN_SUMMARIES[noun] ?? ""}`.trimEnd());
656
+ }
657
+ 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.";
658
+ export function scopedHelp(help, commands, scope, context, options = {}) {
526
659
  const matches = commands.filter((command) => pathStartsWith(command.path, scope) &&
527
660
  commandIsAvailable(command, context.scope));
661
+ // Root help is what an agent reads first: global commands + one line per
662
+ // noun. `--all` (and hosted MCP's small catalog) keep the full listing.
663
+ const compactRoot = scope.length === 0 && !options.all && !options.remoteOnly;
528
664
  if (matches.length === 0) {
529
- throw new CliError("unknown_command", `Unknown command scope: ${scope.join(" ")}. Run \`${options.remoteOnly ? "help" : "recess --help"}\` for available commands.`);
665
+ throw unavailableScopeError(commands, scope, context, options.remoteOnly ? "help" : "recess --help");
530
666
  }
531
667
  const uniqueUsages = Array.from(new Map(matches.map((command) => [command.usage, command])).values());
532
668
  const accessLabel = context.scope
@@ -534,22 +670,64 @@ export function scopedHelp(_help, commands, scope, context, options = {}) {
534
670
  : context.source === "unavailable"
535
671
  ? "session unavailable (local and authentication commands only)"
536
672
  : "signed out (local and authentication commands only)";
673
+ const notes = parseHelpNotes(help);
674
+ const nounNotes = scope[0] ? (notes.byNoun.get(scope[0]) ?? []) : [];
675
+ const summaryFor = (usage) => {
676
+ const sharing = matches.filter((command) => command.usage === usage);
677
+ const summaries = Array.from(new Set(sharing.map((command) => command.summary).filter(Boolean)));
678
+ return summaries.length > 1
679
+ ? sharing
680
+ .map((command) => `${command.path.at(-1)}: ${command.summary}`)
681
+ .join(" ")
682
+ : (summaries[0] ?? "");
683
+ };
537
684
  return [
538
685
  scope.length > 0
539
686
  ? `recess ${scope.join(" ")} — command help`
540
687
  : "recess — safe Recess administration and family AI tools",
541
688
  "",
542
689
  `Access: ${accessLabel}`,
543
- "Key: ◇ shared command ◆ admin-only command",
690
+ "Key: ◇ shared command ◆ admin-only command ✎ write (previews; needs confirmation)",
691
+ ...(options.remoteOnly ? [] : [LOCAL_CONVENTIONS]),
544
692
  "",
545
693
  "Usage:",
546
- ...uniqueUsages.flatMap((command) => wrapUsage(options.remoteOnly ? remoteUsage(command) : command.usage, command.access === "admin" ? "◆" : "◇")),
694
+ ...(compactRoot
695
+ ? uniqueUsages.filter((command) => ROOT_GLOBAL_NOUNS.has(command.path[0]))
696
+ : uniqueUsages).flatMap((command) => {
697
+ const summary = summaryFor(command.usage);
698
+ const write = isWrite(command, options.remoteOnly);
699
+ return [
700
+ ...wrapUsage(options.remoteOnly ? remoteUsage(command) : command.usage, command.access === "admin" ? "◆" : "◇"),
701
+ ...(summary || write
702
+ ? [` ${write ? "✎ " : ""}${summary}`.trimEnd()]
703
+ : []),
704
+ ];
705
+ }),
706
+ ...(compactRoot
707
+ ? [
708
+ "",
709
+ ...notes.global.flatMap((text) => [text, ""]),
710
+ "Commands by noun:",
711
+ ...nounIndex(matches),
712
+ ]
713
+ : []),
547
714
  "",
548
715
  options.remoteOnly
549
716
  ? "Run `help <noun> [verb]` for a focused list."
550
- : "Run `recess help <noun> [verb]` for a focused list.",
551
- ...(options.remoteOnly ? ["", ...REMOTE_HELP_NOTES] : []),
552
- ].join("\n");
717
+ : compactRoot
718
+ ? "Run `recess help <noun>` for commands, flags, and notes; `recess help --all` for everything."
719
+ : "Run `recess help <noun> [verb]` for a focused list and that noun's notes.",
720
+ ...(nounNotes.length > 0
721
+ ? ["", "Notes:", ...nounNotes.flatMap((text) => [text, ""])]
722
+ : []),
723
+ ...(options.remoteOnly
724
+ ? ["", ...REMOTE_HELP_NOTES]
725
+ : scope.length === 0 && !compactRoot
726
+ ? ["", ...notes.global.flatMap((text) => [text, ""])]
727
+ : []),
728
+ ]
729
+ .join("\n")
730
+ .trimEnd();
553
731
  }
554
732
  export function remoteCommands(commands) {
555
733
  return commands.filter((command) => command.remoteCapable);
@@ -576,12 +754,8 @@ export function validateInvocation(parsed, commands, options = {}) {
576
754
  const command = findCommandSchema(commands, parsed.positionals);
577
755
  if (!command) {
578
756
  const scope = parsed.positionals.join(" ");
579
- const first = parsed.positionals[0];
580
- const suggestions = commands
581
- .filter((candidate) => !first || candidate.path[0] === first)
582
- .slice(0, 12)
583
- .map((candidate) => candidate.path.join(" "));
584
- throw new CliError("unknown_command", `Unknown command: ${scope || "(none)"}.`, 1, suggestions.length > 0 ? { suggestions } : undefined);
757
+ const { suggestions, closest } = suggestCommands(parsed.positionals, commands);
758
+ throw new CliError("unknown_command", `Unknown command: ${scope || "(none)"}.${closest ? ` Did you mean \`${closest}\`?` : ""}`, 1, suggestions.length > 0 ? { suggestions } : undefined);
585
759
  }
586
760
  const usage = options.remote ? remoteUsage(command) : command.usage;
587
761
  const remoteConfirmation = options.remote && REMOTE_CONFIRMATION_COMMANDS.has(command.path.join(" "));
@@ -589,8 +763,7 @@ export function validateInvocation(parsed, commands, options = {}) {
589
763
  ...Object.keys(command.flags),
590
764
  ...GLOBAL_FLAGS,
591
765
  ...(remoteConfirmation ? ["confirm"] : []),
592
- ].filter((flag) => !options.remote ||
593
- !["json", "profile", "deliver", "file"].includes(flag)));
766
+ ].filter((flag) => !options.remote || ![...LOCAL_ONLY_FLAGS, "file"].includes(flag)));
594
767
  const unknown = Array.from(parsed.flags.keys()).filter((name) => name !== "version" && !allowed.has(name));
595
768
  if (unknown.length > 0) {
596
769
  const validFlags = Array.from(allowed)
@@ -623,40 +796,119 @@ export function validateInvocation(parsed, commands, options = {}) {
623
796
  }
624
797
  return command;
625
798
  }
799
+ /** Positional placeholders (`<user-id>`, `[dir]`) between the path and the first flag. */
800
+ function positionalArgs(command) {
801
+ const rest = command.usage
802
+ .replace(/^recess\s+(?:\[--json\]\s+)?/, "")
803
+ .split(/\s+/)
804
+ .slice(command.path.length);
805
+ const args = [];
806
+ for (const token of rest) {
807
+ if (/^(?:<[^>]+>|\[<[^>]+>(?:\.\.\.)?\]|\[[a-z][a-z0-9-]*\])$/.test(token)) {
808
+ args.push(token);
809
+ continue;
810
+ }
811
+ break;
812
+ }
813
+ return args;
814
+ }
815
+ function remoteFlags(command) {
816
+ const flags = Object.fromEntries(Object.entries(command.flags).filter(([name]) => !["json", "file"].includes(name)));
817
+ return REMOTE_CONFIRMATION_COMMANDS.has(command.path.join(" "))
818
+ ? {
819
+ ...flags,
820
+ confirm: { type: "boolean", repeatable: false, required: false },
821
+ }
822
+ : flags;
823
+ }
824
+ /**
825
+ * The agent's command catalog, filtered to the session's scope.
826
+ *
827
+ * Default is COMPACT — per command only its summary, positional args, required
828
+ * flags, and whether it is a confirmation-gated write — because the full
829
+ * catalog runs ~170 KB for an admin. `scope` (`agent-context goals`) narrows to
830
+ * one noun and adds its usage line and notes; `full` restores every flag
831
+ * schema (the v4 shape plus `summary`).
832
+ */
626
833
  export function agentContext(commands, options) {
627
- return {
628
- schema_version: AGENT_CONTEXT_SCHEMA_VERSION,
629
- cli_version: options.cliVersion,
630
- session: options.discovery,
631
- commands: Object.fromEntries(commands
632
- .filter((command) => !options.remoteOnly || command.remoteCapable)
633
- .filter((command) => command.path[0] !== "--version" &&
634
- commandIsAvailable(command, options.discovery.scope))
635
- .map((command) => [
636
- command.path.join(" "),
637
- {
638
- usage: options.remoteOnly ? remoteUsage(command) : command.usage,
639
- flags: options.remoteOnly &&
640
- REMOTE_CONFIRMATION_COMMANDS.has(command.path.join(" "))
641
- ? {
642
- ...Object.fromEntries(Object.entries(command.flags).filter(([name]) => !["json", "file"].includes(name))),
643
- confirm: {
644
- type: "boolean",
645
- repeatable: false,
646
- required: false,
647
- },
648
- }
649
- : options.remoteOnly
650
- ? Object.fromEntries(Object.entries(command.flags).filter(([name]) => !["json", "file"].includes(name)))
651
- : command.flags,
834
+ const scope = options.scope ?? [];
835
+ const remote = options.remoteOnly === true;
836
+ const visible = commands
837
+ .filter((command) => !remote || command.remoteCapable)
838
+ .filter((command) => command.path[0] !== "--version" &&
839
+ commandIsAvailable(command, options.discovery.scope));
840
+ const selected = visible.filter((command) => pathStartsWith(command.path, scope));
841
+ if (scope.length > 0 && selected.length === 0) {
842
+ throw unavailableScopeError(remote ? commands.filter((command) => command.remoteCapable) : commands, scope, options.discovery, remote ? "agent-context" : "recess agent-context");
843
+ }
844
+ const notes = options.help ? parseHelpNotes(options.help) : null;
845
+ const nouns = Array.from(new Set(selected.map((command) => command.path[0])));
846
+ const noteEntries = notes
847
+ ? Object.fromEntries(nouns
848
+ .filter(() => scope.length > 0 || options.full)
849
+ .map((noun) => [
850
+ noun,
851
+ (notes.byNoun.get(noun) ?? []).map(unwrapParagraph),
852
+ ])
853
+ .filter(([, entries]) => entries.length > 0))
854
+ : {};
855
+ const usageOf = (command) => remote
856
+ ? remoteUsage(command)
857
+ : command.usage.replace(/^recess\s+(?:\[--json\]\s+)?/, "");
858
+ const entry = (command) => {
859
+ if (options.full) {
860
+ return {
861
+ summary: command.summary,
862
+ usage: remote ? remoteUsage(command) : command.usage,
863
+ flags: remote ? remoteFlags(command) : command.flags,
652
864
  positionals: command.positionals,
653
865
  access: command.access,
654
866
  admin_only: command.access === "admin",
655
867
  remote_capable: command.remoteCapable,
656
868
  oauth_scopes: command.oauthScopes,
657
- },
658
- ])),
659
- global_flags: options.remoteOnly
869
+ };
870
+ }
871
+ const write = isWrite(command, remote) ? { write: true } : {};
872
+ // One noun is small enough to carry its exact syntax, which subsumes the
873
+ // args/required digest.
874
+ if (scope.length > 0) {
875
+ return { summary: command.summary, usage: usageOf(command), ...write };
876
+ }
877
+ const args = positionalArgs(command);
878
+ const required = Object.entries(command.flags)
879
+ .filter(([, flag]) => flag.required)
880
+ .map(([name]) => `--${name}`);
881
+ return {
882
+ summary: command.summary,
883
+ ...(args.length > 0 ? { args } : {}),
884
+ ...(required.length > 0 ? { required } : {}),
885
+ ...write,
886
+ };
887
+ };
888
+ return {
889
+ schema_version: AGENT_CONTEXT_SCHEMA_VERSION,
890
+ cli_version: options.cliVersion,
891
+ session: options.discovery,
892
+ detail: options.full ? "full" : "compact",
893
+ ...(options.full
894
+ ? {}
895
+ : {
896
+ hint: remote
897
+ ? "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."
898
+ : "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.",
899
+ }),
900
+ ...(remote
901
+ ? { instructions: REMOTE_HELP_NOTES }
902
+ : {
903
+ conventions: [
904
+ "--reason TEXT (1–1024 characters, audit-logged) is required on write: true commands; reads default it to `Read: <command>`.",
905
+ "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.",
906
+ "Output is a JSON envelope when stdout is not a terminal or RECESS_CLI_JSON=1; --pretty forces human output.",
907
+ ],
908
+ }),
909
+ commands: Object.fromEntries(selected.map((command) => [command.path.join(" "), entry(command)])),
910
+ ...(Object.keys(noteEntries).length > 0 ? { notes: noteEntries } : {}),
911
+ global_flags: remote
660
912
  ? {
661
913
  "--operation-key": { type: "string" },
662
914
  "--reason": {
@@ -668,19 +920,19 @@ export function agentContext(commands, options) {
668
920
  }
669
921
  : {
670
922
  "--json": { type: "boolean" },
923
+ "--pretty": { type: "boolean", alias: "--no-json" },
671
924
  "--profile": { type: "string" },
672
925
  "--operation-key": { type: "string" },
673
926
  "--reason": {
674
927
  type: "string",
675
- required_for: "every Recess API request except authentication",
928
+ required_for: "confirmation-gated writes; reads and auth default it",
676
929
  max_length: 1024,
677
930
  },
678
931
  "--deliver": { type: "enum", values: ["stdout", "file:<path>"] },
679
932
  "--help": { type: "boolean" },
680
933
  },
681
- ...(options.remoteOnly ? { instructions: REMOTE_HELP_NOTES } : {}),
682
934
  available_profiles: options.availableProfiles,
683
- ...(options.remoteOnly
935
+ ...(remote
684
936
  ? {}
685
937
  : {
686
938
  jobs: { commands: ["jobs list", "jobs get", "jobs prune"] },