@wringer/gunshi 0.0.0-stage → 0.1.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.
Files changed (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +55 -2
  3. package/dist/build-failure-envelope.d.ts +2 -0
  4. package/dist/build-gunshi-args.d.ts +4 -0
  5. package/dist/build-gunshi-commands.d.ts +22 -0
  6. package/dist/build-positional-args.d.ts +4 -0
  7. package/dist/build-raw-args.d.ts +17 -0
  8. package/dist/collect-boolean-flags-with-value.d.ts +3 -0
  9. package/dist/collect-flags-without-value.d.ts +3 -0
  10. package/dist/find-signed-value-flag.d.ts +6 -0
  11. package/dist/index.d.ts +3 -0
  12. package/dist/keep-flag-text.d.ts +1 -0
  13. package/dist/parse-arg-properties.d.ts +22 -0
  14. package/dist/pick-cli-outcome.d.ts +23 -0
  15. package/dist/pick-command-name.d.ts +1 -0
  16. package/dist/pick-dispatch-plan.d.ts +13 -0
  17. package/dist/pick-output-mode.d.ts +8 -0
  18. package/dist/read-repo-root.d.ts +2 -0
  19. package/dist/render-envelope.d.ts +3 -0
  20. package/dist/render-human-envelope.d.ts +2 -0
  21. package/dist/render-human-event.d.ts +1 -0
  22. package/dist/run-cli.d.ts +19 -0
  23. package/dist/run-verify.d.ts +2 -0
  24. package/package.json +46 -4
  25. package/src/build-failure-envelope.ts +19 -0
  26. package/src/build-gunshi-args.ts +66 -0
  27. package/src/build-gunshi-commands.ts +217 -0
  28. package/src/build-positional-args.ts +83 -0
  29. package/src/build-raw-args.ts +132 -0
  30. package/src/collect-boolean-flags-with-value.ts +22 -0
  31. package/src/collect-flags-without-value.ts +26 -0
  32. package/src/find-signed-value-flag.ts +35 -0
  33. package/src/index.ts +3 -0
  34. package/src/keep-flag-text.ts +6 -0
  35. package/src/parse-arg-properties.ts +117 -0
  36. package/src/pick-cli-outcome.ts +32 -0
  37. package/src/pick-command-name.ts +9 -0
  38. package/src/pick-dispatch-plan.ts +24 -0
  39. package/src/pick-output-mode.ts +31 -0
  40. package/src/read-repo-root.ts +35 -0
  41. package/src/render-envelope.ts +7 -0
  42. package/src/render-human-envelope.ts +29 -0
  43. package/src/render-human-event.ts +8 -0
  44. package/src/run-cli.ts +186 -0
  45. package/src/run-verify.ts +35 -0
@@ -0,0 +1,83 @@
1
+ import type { CommandInfo } from '@wringer/core';
2
+ import type { ArgSchema } from 'gunshi';
3
+ import type { GunshiArgs } from './build-gunshi-args.ts';
4
+ import { parseArgProperties, scalarTypeSchema } from './parse-arg-properties.ts';
5
+ import type { ArgProperty, ScalarType } from './parse-arg-properties.ts';
6
+
7
+ // gunshi gives the words that no declared positional takes to this hidden one, so the adapter can
8
+ // refuse them.
9
+ export const extraWordsArg = 'wringer-extra-words';
10
+
11
+ // The positionals in the order the command declares them, for gunshi to assign. Each converts its
12
+ // words to the type the command's schema gives it; every one is optional to gunshi, so the schema
13
+ // requires or defaults it.
14
+ export function buildPositionalArgs(info: CommandInfo | null): GunshiArgs {
15
+ const properties = info === null ? {} : parseArgProperties(info);
16
+
17
+ const declared = (info?.positionals ?? []).map((name): [string, ArgSchema] => {
18
+ const property = properties[name];
19
+ const list = property?.type === 'array';
20
+ const wordType = list ? property.items?.type : property?.type;
21
+ const type = pickWordType(property, wordType);
22
+
23
+ const described =
24
+ property?.description === undefined ? {} : { description: property.description };
25
+
26
+ return [
27
+ name,
28
+ {
29
+ type: 'positional',
30
+ required: false,
31
+ ...(list ? { multiple: true } : {}),
32
+ parse: (word: string) => toTyped(word, type),
33
+ ...described,
34
+ },
35
+ ];
36
+ });
37
+
38
+ return Object.fromEntries([
39
+ ...declared,
40
+ [extraWordsArg, { type: 'positional', required: false, multiple: true, hidden: true }],
41
+ ]);
42
+ }
43
+
44
+ type WordType = ScalarType | 'json';
45
+
46
+ // A field the schema gives no one scalar type, such as an object, takes JSON text, as its flag
47
+ // would.
48
+ function pickWordType(property: ArgProperty | undefined, wordType: unknown): WordType {
49
+ const parsed = scalarTypeSchema.safeParse(wordType);
50
+
51
+ if (parsed.success) {
52
+ return parsed.data;
53
+ }
54
+
55
+ return property === undefined ? 'string' : 'json';
56
+ }
57
+
58
+ // A word that does not convert stays text, so the command's schema rejects it with its path.
59
+ function toTyped(word: string, type: WordType): unknown {
60
+ if (type === 'json') {
61
+ return parseJSONWord(word);
62
+ }
63
+
64
+ if (type === 'number' || type === 'integer') {
65
+ const value = Number(word);
66
+
67
+ return word.trim() === '' || Number.isNaN(value) ? word : value;
68
+ }
69
+
70
+ if (type === 'boolean' && (word === 'true' || word === 'false')) {
71
+ return word === 'true';
72
+ }
73
+
74
+ return word;
75
+ }
76
+
77
+ function parseJSONWord(word: string): unknown {
78
+ try {
79
+ return JSON.parse(word);
80
+ } catch {
81
+ return word;
82
+ }
83
+ }
@@ -0,0 +1,132 @@
1
+ import { WringerError } from '@wringer/core';
2
+ import type { ArgSchema, ArgToken } from 'gunshi';
3
+ import type { GunshiArgs } from './build-gunshi-args.ts';
4
+ import { extraWordsArg } from './build-positional-args.ts';
5
+
6
+ export interface ParsedCommand {
7
+ readonly tokens: readonly ArgToken[];
8
+ readonly values: Readonly<Record<string, unknown>>;
9
+ readonly explicit: Readonly<Record<string, boolean>>;
10
+
11
+ // The words after `--` that gunshi assigns to no positional.
12
+ readonly rest: readonly string[];
13
+ }
14
+
15
+ export type RawArgsResult =
16
+ | { readonly ok: true; readonly raw: Record<string, unknown> }
17
+ | { readonly ok: false; readonly error: WringerError };
18
+
19
+ // The parser reads a word such as `-15` as short options, so it reaches a positional only after
20
+ // `--`. A word no positional takes is a usage failure, so `down prod` never stops the current
21
+ // target in place of `prod`.
22
+ export function buildRawArgs(args: GunshiArgs, parsed: ParsedCommand): RawArgsResult {
23
+ const afterTerminator = collectWordsAfterTerminator(parsed.tokens);
24
+
25
+ const values = collectValuesBeforeTerminator(
26
+ args,
27
+ parsed.values,
28
+ parsed.explicit,
29
+ afterTerminator.length - parsed.rest.length,
30
+ );
31
+
32
+ const raw: Record<string, unknown> = Object.fromEntries(
33
+ Object.keys(args).flatMap((name) =>
34
+ name !== extraWordsArg && Object.hasOwn(values, name) ? [[name, values[name]] as const] : [],
35
+ ),
36
+ );
37
+
38
+ const extra = toWords(values[extraWordsArg]);
39
+
40
+ const positionals = Object.entries(args).filter(
41
+ ([name, schema]) => name !== extraWordsArg && schema.type === 'positional',
42
+ );
43
+
44
+ // The words after `--` go on where the words before it stopped, in the declared order: an unset
45
+ // scalar takes one word, and a list takes every word left, as gunshi fills them before `--`.
46
+ const restWords = [...afterTerminator];
47
+
48
+ for (const [name, schema] of positionals) {
49
+ const [word] = restWords;
50
+
51
+ if (word === undefined) {
52
+ break;
53
+ }
54
+
55
+ if (schema.multiple === true) {
56
+ const restValues = restWords.splice(0).map((restWord) => parseWord(schema, restWord));
57
+
58
+ raw[name] = [...toWords(raw[name]), ...restValues];
59
+ } else if (!Object.hasOwn(raw, name)) {
60
+ restWords.shift();
61
+
62
+ raw[name] = parseWord(schema, word);
63
+ }
64
+ }
65
+
66
+ const leftover = [...extra, ...restWords];
67
+
68
+ if (leftover.length > 0) {
69
+ return {
70
+ ok: false,
71
+ error: new WringerError('usage', {
72
+ message: `The command takes no argument ${leftover.map((word) => `\`${String(word)}\``).join(', ')}.`,
73
+ hint: 'Pass a value with its flag, such as `--target prod`.',
74
+ }),
75
+ };
76
+ }
77
+
78
+ return { ok: true, raw };
79
+ }
80
+
81
+ function collectWordsAfterTerminator(tokens: readonly ArgToken[]): readonly string[] {
82
+ const terminator = tokens.findIndex((token) => token.kind === 'option-terminator');
83
+
84
+ return terminator === -1 ? [] : tokens.slice(terminator + 1).map((token) => token.value ?? '');
85
+ }
86
+
87
+ // gunshi takes an empty word after `--` as a positional, behind every other positional word, and
88
+ // leaves it out of `rest`. Dropping the last `movedCount` positional words gives back what came
89
+ // before `--`, so each word after it keeps its place. Only the caller's own values are kept.
90
+ function collectValuesBeforeTerminator(
91
+ args: GunshiArgs,
92
+ values: Readonly<Record<string, unknown>>,
93
+ explicit: Readonly<Record<string, boolean>>,
94
+ movedCount: number,
95
+ ): Readonly<Record<string, unknown>> {
96
+ const given = Object.keys(args).filter((name) => explicit[name] === true);
97
+
98
+ const filled = given.flatMap((name) =>
99
+ args[name]?.type === 'positional'
100
+ ? (args[name].multiple === true ? toWords(values[name]) : [values[name]]).map(
101
+ (value) => [name, value] as const,
102
+ )
103
+ : [],
104
+ );
105
+
106
+ const kept = filled.slice(0, filled.length - movedCount);
107
+
108
+ return Object.fromEntries([
109
+ ...given.flatMap((name): [string, unknown][] =>
110
+ args[name]?.type === 'positional' ? [] : [[name, values[name]]],
111
+ ),
112
+ ...given.flatMap((name): [string, unknown][] => {
113
+ const words = kept.filter(([keptName]) => keptName === name).map(([, value]) => value);
114
+
115
+ if (words.length === 0) {
116
+ return [];
117
+ }
118
+
119
+ return [[name, args[name]?.multiple === true ? words : words[0]]];
120
+ }),
121
+ ]);
122
+ }
123
+
124
+ // gunshi leaves a multiple positional that took no word unset.
125
+ function toWords(value: unknown): readonly unknown[] {
126
+ return Array.isArray(value) ? value : [];
127
+ }
128
+
129
+ // A parser's result is the value, `null` included; only a positional with no parser keeps the word.
130
+ function parseWord(schema: ArgSchema, word: string): unknown {
131
+ return schema.parse === undefined ? word : schema.parse(word);
132
+ }
@@ -0,0 +1,22 @@
1
+ import type { ArgToken } from 'gunshi';
2
+ import { kebabnize } from 'gunshi/utils';
3
+ import type { GunshiArgs } from './build-gunshi-args.ts';
4
+
5
+ // gunshi sets a boolean flag to true whatever value follows its `=`, so `--dry-run=false` would
6
+ // run the command as a dry run. A boolean flag takes no value: `--no-<flag>` turns it off.
7
+ export function collectBooleanFlagsWithValue(
8
+ tokens: readonly ArgToken[],
9
+ args: GunshiArgs,
10
+ ): readonly string[] {
11
+ const booleanFlags = new Set(
12
+ Object.entries(args).flatMap(([name, schema]) =>
13
+ schema.type === 'boolean' ? [`--${kebabnize(name)}`, `--no-${kebabnize(name)}`] : [],
14
+ ),
15
+ );
16
+
17
+ return tokens.flatMap((token) =>
18
+ token.kind === 'option' && token.value !== undefined && booleanFlags.has(token.rawName ?? '')
19
+ ? [token.rawName ?? '']
20
+ : [],
21
+ );
22
+ }
@@ -0,0 +1,26 @@
1
+ import type { ArgToken } from 'gunshi';
2
+ import { kebabnize } from 'gunshi/utils';
3
+ import type { GunshiArgs } from './build-gunshi-args.ts';
4
+
5
+ // gunshi hands a custom parse function an empty string for a flag typed with no value after it, so
6
+ // `--label` at the end reads as `--label ''`. A value flag takes the word after it, an empty word
7
+ // included; one with an option or nothing after it has no value.
8
+ export function collectFlagsWithoutValue(
9
+ tokens: readonly ArgToken[],
10
+ args: GunshiArgs,
11
+ ): readonly string[] {
12
+ const valueFlags = new Set(
13
+ Object.entries(args).flatMap(([name, schema]) =>
14
+ schema.type === 'boolean' || schema.type === 'positional' ? [] : [`--${kebabnize(name)}`],
15
+ ),
16
+ );
17
+
18
+ return tokens.flatMap((token, index) =>
19
+ token.kind === 'option' &&
20
+ token.value === undefined &&
21
+ valueFlags.has(token.rawName ?? '') &&
22
+ tokens[index + 1]?.kind !== 'positional'
23
+ ? [token.rawName ?? '']
24
+ : [],
25
+ );
26
+ }
@@ -0,0 +1,35 @@
1
+ import type { ArgToken } from 'gunshi';
2
+
3
+ export interface SignedValueFlag {
4
+ readonly flag: string;
5
+ readonly value: string;
6
+ }
7
+
8
+ const signedStartPattern = /^-[\d.]$/u;
9
+
10
+ // gunshi reads a word such as `-15` as the short options `-1` and `-5`, so `--degrees -15` leaves
11
+ // the flag with no value. Each token keeps the index of the word it came from, which gives back the
12
+ // whole word for the hint.
13
+ export function findSignedValueFlag(
14
+ tokens: readonly ArgToken[],
15
+ argv: readonly string[],
16
+ ): SignedValueFlag | undefined {
17
+ for (const [index, token] of tokens.entries()) {
18
+ const next = tokens[index + 1];
19
+
20
+ const isSignedValue =
21
+ token.kind === 'option' &&
22
+ token.rawName?.startsWith('--') === true &&
23
+ token.value === undefined &&
24
+ next?.kind === 'option' &&
25
+ signedStartPattern.test(next.rawName ?? '');
26
+
27
+ const value = next === undefined ? undefined : argv[next.index];
28
+
29
+ if (isSignedValue && value !== undefined) {
30
+ return { flag: token.rawName ?? '', value };
31
+ }
32
+ }
33
+
34
+ return undefined;
35
+ }
package/src/index.ts ADDED
@@ -0,0 +1,3 @@
1
+ export { runCLI } from './run-cli.ts';
2
+ export type { CLIPorts } from './run-cli.ts';
3
+ export { runVerify } from './run-verify.ts';
@@ -0,0 +1,6 @@
1
+ // gunshi swaps an empty string for a string flag's default, which is undefined here, so `--label ''`
2
+ // would reach the schema as a missing flag. A string flag passes this parse function to keep the
3
+ // value as typed.
4
+ export function keepFlagText(value: string): string {
5
+ return value;
6
+ }
@@ -0,0 +1,117 @@
1
+ import { findOwnValue } from '@wringer/core';
2
+ import type { CommandInfo } from '@wringer/core';
3
+ import { z } from 'zod';
4
+
5
+ export const scalarTypeSchema = z.enum(['string', 'number', 'integer', 'boolean']);
6
+
7
+ export type ScalarType = z.infer<typeof scalarTypeSchema>;
8
+
9
+ const itemSchema = z.looseObject({ type: z.unknown().optional() });
10
+
11
+ // A tuple's JSON Schema holds `items: false`, so its items have no one type.
12
+ const noItemSchema = z.boolean().transform(() => ({ type: null }));
13
+
14
+ const propertyJSONSchema = z.looseObject({
15
+ type: z.unknown().optional(),
16
+ enum: z.array(z.unknown()).optional(),
17
+ items: z.union([itemSchema, noItemSchema]).optional(),
18
+ description: z.string().optional(),
19
+ });
20
+
21
+ export type ArgProperty = z.infer<typeof propertyJSONSchema>;
22
+
23
+ // A schema with an `id` in its metadata sits under `$defs`, and its place holds a `$ref` to it.
24
+ const definitionsJSONSchema = z.looseObject({
25
+ $defs: z.record(z.string(), z.unknown()).default({}),
26
+ });
27
+
28
+ // The JSON Schema of a command's arguments gives each field's type without walking zod's internals.
29
+ // A union's fields all become flags, and the command's own schema then checks which branch matched.
30
+ export function parseArgProperties(info: CommandInfo): Readonly<Record<string, ArgProperty>> {
31
+ const jsonSchema = z.toJSONSchema(info.args, { io: 'input', unrepresentable: 'any' });
32
+ const definitions = definitionsJSONSchema.parse(jsonSchema).$defs;
33
+
34
+ return collectProperties(jsonSchema, definitions);
35
+ }
36
+
37
+ // A union of objects, such as a discriminated union, puts its fields under `oneOf` or `anyOf`.
38
+ const objectJSONSchema = z.looseObject({
39
+ properties: z.record(z.string(), z.unknown()).default({}),
40
+ oneOf: z.array(z.unknown()).default([]),
41
+ anyOf: z.array(z.unknown()).default([]),
42
+ });
43
+
44
+ // A field that two branches type differently, items included, takes JSON text, so either branch's
45
+ // value parses. Two enums of one type join their choices.
46
+ function collectProperties(
47
+ jsonSchema: unknown,
48
+ definitions: Readonly<Record<string, unknown>>,
49
+ ): Record<string, ArgProperty> {
50
+ const parsed = objectJSONSchema.safeParse(findReferenced(jsonSchema, definitions));
51
+
52
+ if (!parsed.success) {
53
+ return {};
54
+ }
55
+
56
+ const branches = [...parsed.data.oneOf, ...parsed.data.anyOf].map((branch) =>
57
+ collectProperties(branch, definitions),
58
+ );
59
+
60
+ const own = Object.fromEntries(
61
+ Object.entries(parsed.data.properties).flatMap(([name, property]) => {
62
+ const typed = propertyJSONSchema.safeParse(findReferenced(property, definitions));
63
+
64
+ return typed.success ? [[name, typed.data] as const] : [];
65
+ }),
66
+ );
67
+
68
+ // A Map holds any argument name, `constructor` included, as its own key.
69
+ const collected = new Map<string, ArgProperty>();
70
+
71
+ for (const properties of [own, ...branches]) {
72
+ for (const [name, property] of Object.entries(properties)) {
73
+ const seen = collected.get(name);
74
+ const merged = seen === undefined ? property : pickMergedProperty(seen, property);
75
+
76
+ collected.set(name, merged);
77
+ }
78
+ }
79
+
80
+ return Object.fromEntries(collected);
81
+ }
82
+
83
+ const referenceJSONSchema = z.looseObject({ $ref: z.string().startsWith('#/$defs/') });
84
+
85
+ // The schema a local `$ref` names, or the schema itself when it holds no such reference.
86
+ function findReferenced(
87
+ jsonSchema: unknown,
88
+ definitions: Readonly<Record<string, unknown>>,
89
+ ): unknown {
90
+ const reference = referenceJSONSchema.safeParse(jsonSchema);
91
+
92
+ if (!reference.success) {
93
+ return jsonSchema;
94
+ }
95
+
96
+ return (
97
+ findOwnValue(definitions, toPointerSegment(reference.data.$ref.slice('#/$defs/'.length))) ??
98
+ jsonSchema
99
+ );
100
+ }
101
+
102
+ // A JSON Pointer escapes `/` as `~1` and `~` as `~0`; decoding `~1` first keeps `~01` as `~1`.
103
+ function toPointerSegment(escaped: string): string {
104
+ return escaped.replaceAll('~1', '/').replaceAll('~0', '~');
105
+ }
106
+
107
+ function pickMergedProperty(seen: ArgProperty, property: ArgProperty): ArgProperty {
108
+ if (seen.type !== property.type || seen.items?.type !== property.items?.type) {
109
+ return {};
110
+ }
111
+
112
+ if (seen.enum === undefined || property.enum === undefined) {
113
+ return seen.enum === property.enum ? seen : {};
114
+ }
115
+
116
+ return { ...seen, enum: [...new Set([...seen.enum, ...property.enum])] };
117
+ }
@@ -0,0 +1,32 @@
1
+ import { exitCodeFor } from '@wringer/core';
2
+ import type { WringerError } from '@wringer/core';
3
+ import { buildFailureEnvelope } from './build-failure-envelope.ts';
4
+ import type { Invocation } from './build-gunshi-commands.ts';
5
+ import type { OutputMode } from './pick-output-mode.ts';
6
+ import { renderEnvelope } from './render-envelope.ts';
7
+
8
+ export type ParsedInvocation =
9
+ | { readonly kind: 'invoked'; readonly invocation: Invocation }
10
+ | { readonly kind: 'printed'; readonly text: string }
11
+ | { readonly kind: 'failed'; readonly command: string; readonly error: WringerError };
12
+
13
+ export type CLIOutcome =
14
+ | { readonly kind: 'write'; readonly text: string; readonly exitCode: number }
15
+ | { readonly kind: 'dispatch'; readonly invocation: Invocation };
16
+
17
+ // Help and a parse failure end the invocation with their text; only an invoked command dispatches.
18
+ export function pickCLIOutcome(parsed: ParsedInvocation, mode: OutputMode): CLIOutcome {
19
+ if (parsed.kind === 'printed') {
20
+ return { kind: 'write', text: parsed.text, exitCode: 0 };
21
+ }
22
+
23
+ if (parsed.kind === 'failed') {
24
+ return {
25
+ kind: 'write',
26
+ text: renderEnvelope(buildFailureEnvelope(parsed.command, parsed.error), mode),
27
+ exitCode: exitCodeFor[parsed.error.code],
28
+ };
29
+ }
30
+
31
+ return { kind: 'dispatch', invocation: parsed.invocation };
32
+ }
@@ -0,0 +1,9 @@
1
+ // The envelope names the command path gunshi resolved, so a flag's value or a positional never
2
+ // reaches it. gunshi resolves no path for a word that names no command.
3
+ export function pickCommandName(commandPath: readonly string[], argv: readonly string[]): string {
4
+ if (commandPath.length > 0) {
5
+ return commandPath.join('.');
6
+ }
7
+
8
+ return argv.length === 0 ? 'help' : 'unknown';
9
+ }
@@ -0,0 +1,24 @@
1
+ import { WringerError, exitCodeFor } from '@wringer/core';
2
+ import type { Envelope } from '@wringer/core';
3
+ import { buildFailureEnvelope } from './build-failure-envelope.ts';
4
+ import type { Invocation } from './build-gunshi-commands.ts';
5
+
6
+ export type DispatchPlan =
7
+ | { readonly kind: 'refuse'; readonly envelope: Envelope; readonly exitCode: number }
8
+ | { readonly kind: 'dispatch'; readonly root: string; readonly invocation: Invocation };
9
+
10
+ // A command runs only inside a repo; outside one, the invocation ends in the root's error.
11
+ export function pickDispatchPlan(
12
+ invocation: Invocation,
13
+ root: string | WringerError,
14
+ ): DispatchPlan {
15
+ if (root instanceof WringerError) {
16
+ return {
17
+ kind: 'refuse',
18
+ envelope: buildFailureEnvelope(invocation.path.join('.'), root),
19
+ exitCode: exitCodeFor[root.code],
20
+ };
21
+ }
22
+
23
+ return { kind: 'dispatch', root, invocation };
24
+ }
@@ -0,0 +1,31 @@
1
+ import type { ArgToken } from 'gunshi';
2
+
3
+ export type OutputMode = 'json' | 'human';
4
+
5
+ export interface OutputModeInput {
6
+ readonly tokens: readonly ArgToken[];
7
+ readonly isTTY: boolean;
8
+ readonly isAgent: boolean;
9
+ }
10
+
11
+ // An agent or a pipe reads JSON; a person at a terminal reads text. `--json` and `--human` override
12
+ // that guess, and the last of them wins. The tokens come from gunshi's parser, which also reads
13
+ // `--json=true`, and stops reading options at `--`.
14
+ export function pickOutputMode(input: OutputModeInput): OutputMode {
15
+ const chosen = input.tokens.findLast(
16
+ (token) =>
17
+ token.kind === 'option' &&
18
+ (token.name === 'json' || token.name === 'human') &&
19
+ token.value !== 'false',
20
+ );
21
+
22
+ if (chosen?.name === 'json') {
23
+ return 'json';
24
+ }
25
+
26
+ if (chosen?.name === 'human' || (input.isTTY && !input.isAgent)) {
27
+ return 'human';
28
+ }
29
+
30
+ return 'json';
31
+ }
@@ -0,0 +1,35 @@
1
+ import { WringerError, runProcess } from '@wringer/core';
2
+ import type { ProcessResult } from '@wringer/core';
3
+
4
+ // The run state lives at the top of the worktree, wherever in it the command starts.
5
+ export async function readRepoRoot(cwd: string): Promise<string | WringerError> {
6
+ const result = await readTopLevel(cwd);
7
+
8
+ if (result instanceof WringerError) {
9
+ return result;
10
+ }
11
+
12
+ if (result.exitCode !== 0) {
13
+ return new WringerError('environment', {
14
+ message: `${cwd} is not inside a git worktree.`,
15
+ hint: 'Run the command from inside the repo.',
16
+ });
17
+ }
18
+
19
+ // A folder name may end in a space, so only git's own line end goes.
20
+ return result.stdout.replace(/\n$/u, '');
21
+ }
22
+
23
+ // A git that fails to start, or a folder that does not exist, fails the run with an environment
24
+ // error, which the caller answers like any other.
25
+ async function readTopLevel(cwd: string): Promise<ProcessResult | WringerError> {
26
+ try {
27
+ return await runProcess({ argv: ['git', 'rev-parse', '--show-toplevel'], cwd });
28
+ } catch (error) {
29
+ if (error instanceof WringerError) {
30
+ return error;
31
+ }
32
+
33
+ throw error;
34
+ }
35
+ }
@@ -0,0 +1,7 @@
1
+ import type { Envelope } from '@wringer/core';
2
+ import type { OutputMode } from './pick-output-mode.ts';
3
+ import { renderHumanEnvelope } from './render-human-envelope.ts';
4
+
5
+ export function renderEnvelope(envelope: Envelope, mode: OutputMode): string {
6
+ return mode === 'json' ? `${JSON.stringify(envelope)}\n` : renderHumanEnvelope(envelope);
7
+ }
@@ -0,0 +1,29 @@
1
+ import type { Envelope } from '@wringer/core';
2
+ import { z } from 'zod';
3
+
4
+ const markdownDataSchema = z.looseObject({ markdown: z.string() });
5
+
6
+ // A person reads the same envelope as an agent, as text: the error and its hint, or the data. A
7
+ // command whose data carries Markdown, such as `report`, prints only that Markdown.
8
+ export function renderHumanEnvelope(envelope: Envelope): string {
9
+ if (envelope.error !== null) {
10
+ const hint = envelope.error.hint === null ? '' : `\nhint: ${envelope.error.hint}`;
11
+
12
+ return `${envelope.command} failed (${envelope.error.code}): ${envelope.error.message}${hint}\n`;
13
+ }
14
+
15
+ const markdown = markdownDataSchema.safeParse(envelope.data);
16
+
17
+ if (markdown.success) {
18
+ return `${markdown.data.markdown}\n`;
19
+ }
20
+
21
+ const truncated =
22
+ envelope.truncatedPath === undefined
23
+ ? ''
24
+ : `\nThe data was too large to print; it is in ${envelope.truncatedPath}.`;
25
+
26
+ const data = envelope.data === null ? '' : `\n${JSON.stringify(envelope.data, null, 2)}`;
27
+
28
+ return `${envelope.command} passed${data}${truncated}\n`;
29
+ }
@@ -0,0 +1,8 @@
1
+ import { streamEventSchema } from '@wringer/core';
2
+
3
+ // One NDJSON stream event as one line of text, such as a doctor check as it finishes.
4
+ export function renderHumanEvent(line: string): string {
5
+ const event = streamEventSchema.parse(JSON.parse(line));
6
+
7
+ return `${event.event}: ${JSON.stringify(event.data)}\n`;
8
+ }