goals-cli 0.0.0-stage → 1.3.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 (46) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +130 -2
  3. package/dist/args.js +96 -0
  4. package/dist/auth/command.js +16 -0
  5. package/dist/auth/help.js +82 -0
  6. package/dist/auth/list.js +41 -0
  7. package/dist/auth/login.js +203 -0
  8. package/dist/auth/logout.js +25 -0
  9. package/dist/auth/select.js +30 -0
  10. package/dist/auth/status.js +43 -0
  11. package/dist/auth/use.js +10 -0
  12. package/dist/cli.js +112 -0
  13. package/dist/commands/export-help.js +49 -0
  14. package/dist/commands/export.js +194 -0
  15. package/dist/commands/goal-flags.js +111 -0
  16. package/dist/commands/goal-format.js +95 -0
  17. package/dist/commands/goal-help.js +214 -0
  18. package/dist/commands/goal-read.js +80 -0
  19. package/dist/commands/goal-write.js +186 -0
  20. package/dist/commands/goal.js +15 -0
  21. package/dist/commands/initiative-help.js +38 -0
  22. package/dist/commands/initiative.js +81 -0
  23. package/dist/commands/list-output.js +13 -0
  24. package/dist/commands/skill-help.js +18 -0
  25. package/dist/commands/skill.js +36 -0
  26. package/dist/credentials.js +270 -0
  27. package/dist/deps.js +46 -0
  28. package/dist/dispatch.js +16 -0
  29. package/dist/endpoints.js +82 -0
  30. package/dist/errors.js +29 -0
  31. package/dist/help.js +105 -0
  32. package/dist/http.js +199 -0
  33. package/dist/iso-week.js +18 -0
  34. package/dist/open-browser.js +47 -0
  35. package/dist/output.js +29 -0
  36. package/dist/vendor/cli-contract/index.js +26 -0
  37. package/dist/vendor/quarterly-markdown/dateFormat.js +101 -0
  38. package/dist/vendor/quarterly-markdown/generate.js +450 -0
  39. package/dist/vendor/quarterly-markdown/htmlToPlainText.js +101 -0
  40. package/dist/vendor/quarterly-markdown/index.js +4 -0
  41. package/dist/vendor/quarterly-markdown/types.js +1 -0
  42. package/dist/vendor/quarterly-markdown/year.js +45 -0
  43. package/dist/version.js +9 -0
  44. package/package.json +37 -4
  45. package/skills/goals-cli/REFERENCE.md +212 -0
  46. package/skills/goals-cli/SKILL.md +12 -0
@@ -0,0 +1,43 @@
1
+ import { booleanFlag } from '../args.js';
2
+ import { formatKeyValues, toJson } from '../output.js';
3
+ import { parseAndSelect } from './select.js';
4
+ const HINT = 'goals auth status --help';
5
+ const FLAGS = {
6
+ as: { type: 'string' },
7
+ json: { type: 'boolean' },
8
+ };
9
+ /** The stored origins are validated at login, so URL parsing cannot fail here. */
10
+ function hostOf(convexUrl) {
11
+ return new URL(convexUrl).host;
12
+ }
13
+ export async function runStatus(args, ctx) {
14
+ const { parsed, credential } = await parseAndSelect(args, FLAGS, HINT, ctx);
15
+ const whoami = await ctx.api.call(credential, 'auth.whoami', {});
16
+ const environment = credential.environment ?? null;
17
+ const convexHost = hostOf(credential.convexUrl);
18
+ const createdAt = new Date(whoami.createdAt).toISOString();
19
+ const expiresAt = new Date(whoami.expiresAt).toISOString();
20
+ if (booleanFlag(parsed, 'json')) {
21
+ ctx.deps.stdout.write(toJson({
22
+ name: whoami.name,
23
+ userId: whoami.userId,
24
+ label: credential.label,
25
+ environment,
26
+ convexHost,
27
+ createdAt,
28
+ expiresAt,
29
+ valid: true,
30
+ }));
31
+ return;
32
+ }
33
+ ctx.deps.stdout.write(formatKeyValues([
34
+ ['Name', whoami.name],
35
+ ['User ID', whoami.userId],
36
+ ['Identity', credential.label],
37
+ ['Environment', environment ?? 'default'],
38
+ ['Server', convexHost],
39
+ ['Created', createdAt],
40
+ ['Expires', expiresAt],
41
+ ['Valid', 'yes'],
42
+ ]));
43
+ }
@@ -0,0 +1,10 @@
1
+ import { parseFlags } from '../args.js';
2
+ import { readCredentials, setDefaultLabel, writeCredentials } from '../credentials.js';
3
+ const HINT = 'goals auth use --help';
4
+ export async function runUse(args, ctx) {
5
+ const parsed = parseFlags(args, {}, HINT, { min: 1, max: 1, name: '<label>' });
6
+ const label = parsed.positionals[0] ?? '';
7
+ const { credentials } = await readCredentials(ctx.deps.storeOptions);
8
+ await writeCredentials(setDefaultLabel(credentials, label), ctx.deps.storeOptions);
9
+ ctx.deps.stdout.write(`Default identity is now '${label}'.\n`);
10
+ }
package/dist/cli.js ADDED
@@ -0,0 +1,112 @@
1
+ #!/usr/bin/env node
2
+ import { realpathSync } from 'node:fs';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { runAuthCommand } from './auth/command.js';
5
+ import { authHelp } from './auth/help.js';
6
+ import { exportHelp } from './commands/export-help.js';
7
+ import { runExportCommand } from './commands/export.js';
8
+ import { goalHelp } from './commands/goal-help.js';
9
+ import { runGoalCommand } from './commands/goal.js';
10
+ import { initiativeHelp } from './commands/initiative-help.js';
11
+ import { runInitiativeCommand } from './commands/initiative.js';
12
+ import { skillHelp } from './commands/skill-help.js';
13
+ import { runSkillCommand } from './commands/skill.js';
14
+ import { defaultDeps } from './deps.js';
15
+ import { CliError, safeMessage, UsageError } from './errors.js';
16
+ import { resolveHelp, wantsHelp } from './help.js';
17
+ import { createApiClient } from './http.js';
18
+ import { readCliVersion } from './version.js';
19
+ /** Every help page the CLI knows; later packages append their families here. */
20
+ export const commandHelpFamilies = [
21
+ authHelp,
22
+ goalHelp,
23
+ initiativeHelp,
24
+ exportHelp,
25
+ skillHelp,
26
+ ];
27
+ const FAMILIES = {
28
+ auth: runAuthCommand,
29
+ goal: runGoalCommand,
30
+ initiative: runInitiativeCommand,
31
+ export: runExportCommand,
32
+ skill: runSkillCommand,
33
+ };
34
+ const ROOT_USAGE = 'goals <command> [options]. Run `goals --help` for commands.';
35
+ function unknownCommand(name) {
36
+ return new UsageError(`unknown command '${name}'. Run \`goals --help\` for commands.`);
37
+ }
38
+ /** One line at most: stack traces never reach the terminal. */
39
+ function firstLine(message) {
40
+ return message.split(/\r?\n/, 1)[0] ?? '';
41
+ }
42
+ function report(deps, error) {
43
+ const message = error instanceof Error ? error.message : error;
44
+ if (error instanceof UsageError) {
45
+ deps.stderr.write(`${firstLine(String(message))}\n`);
46
+ return 2;
47
+ }
48
+ if (error instanceof CliError) {
49
+ deps.stderr.write(`${firstLine(String(message))}\n`);
50
+ return 1;
51
+ }
52
+ deps.stderr.write(`Goals command failed: ${safeMessage(message, 'unexpected error')}\n`);
53
+ return 1;
54
+ }
55
+ /** True only for the bare `--version` invocation. */
56
+ function isVersionRequest(argv) {
57
+ return argv.length === 1 && argv[0] === '--version';
58
+ }
59
+ /** Runs the requested command family; unknown names are a usage error. */
60
+ async function runCommand(argv, ctx) {
61
+ const [name] = argv;
62
+ if (name === undefined)
63
+ throw new UsageError(ROOT_USAGE);
64
+ const runner = Object.hasOwn(FAMILIES, name) ? FAMILIES[name] : undefined;
65
+ if (runner === undefined)
66
+ throw unknownCommand(name);
67
+ await runner(argv.slice(1), ctx);
68
+ }
69
+ /** Dispatches one invocation; every failure is left to `report`. */
70
+ async function dispatch(argv, ctx) {
71
+ if (isVersionRequest(argv)) {
72
+ ctx.deps.stdout.write(`${readCliVersion()}\n`);
73
+ return 0;
74
+ }
75
+ if (wantsHelp(argv)) {
76
+ ctx.deps.stdout.write(resolveHelp(argv, commandHelpFamilies));
77
+ return 0;
78
+ }
79
+ await runCommand(argv, ctx);
80
+ return 0;
81
+ }
82
+ /**
83
+ * Runs the CLI and resolves with the process exit code: 0 success, 2 usage error, 1 anything
84
+ * else. All side effects come from `deps`, so specs drive it without touching the process.
85
+ */
86
+ export async function runCli(argv = process.argv.slice(2), overrides = {}) {
87
+ const deps = { ...defaultDeps(), ...overrides };
88
+ const api = createApiClient({ fetch: deps.fetch, timeoutMs: deps.timeoutMs });
89
+ try {
90
+ return await dispatch(argv, { deps, api });
91
+ }
92
+ catch (error) {
93
+ return report(deps, error);
94
+ }
95
+ }
96
+ /** True when this module is the executed script (directly, via a bin symlink, or via npx). */
97
+ function isEntryPoint() {
98
+ const argv1 = process.argv[1];
99
+ if (!argv1)
100
+ return false;
101
+ try {
102
+ return realpathSync(argv1) === realpathSync(fileURLToPath(import.meta.url));
103
+ }
104
+ catch {
105
+ return false;
106
+ }
107
+ }
108
+ if (isEntryPoint()) {
109
+ void runCli().then((code) => {
110
+ process.exitCode = code;
111
+ });
112
+ }
@@ -0,0 +1,49 @@
1
+ /** Help data for the `export` family; pinned by `src/__views__/export-*-help.txt`. */
2
+ export const exportHelp = {
3
+ name: 'export',
4
+ summary: 'Export your goals as markdown.',
5
+ actions: {
6
+ markdown: {
7
+ summary: 'Print the quarterly summary markdown for a quarter or a year.',
8
+ usage: 'goals export markdown --year <year> [--quarter <n>] [--completed-only] [--goal <id>]... [--domain <id|uncategorized>]... [--no-adhoc] [--out <file>] [--as <label>]',
9
+ options: [
10
+ { syntax: '--year <year>', description: 'Calendar year, 2000-2100; required.' },
11
+ { syntax: '--quarter <n>', description: 'Quarter 1-4; omit to export the whole year.' },
12
+ {
13
+ syntax: '--completed-only',
14
+ description: "Only completed goals, like the webapp's completed export.",
15
+ },
16
+ {
17
+ syntax: '--goal <id>',
18
+ description: 'Only this quarterly goal; repeatable; needs --quarter.',
19
+ },
20
+ {
21
+ syntax: '--domain <id|uncategorized>',
22
+ description: 'Only adhoc goals in this domain; repeatable.',
23
+ },
24
+ { syntax: '--no-adhoc', description: 'Leave adhoc goals out.' },
25
+ {
26
+ syntax: '--out <file>',
27
+ description: 'Write the markdown to this file instead of stdout.',
28
+ },
29
+ { syntax: '--as <label>', description: 'Identity to use (default: the default identity).' },
30
+ ],
31
+ examples: [
32
+ 'goals export markdown --year 2026 --quarter 3',
33
+ 'goals export markdown --year 2026 --completed-only --out goals-2026.md',
34
+ 'goals export markdown --year 2026 --quarter 3 --domain uncategorized',
35
+ ],
36
+ notes: [
37
+ 'The output matches the webapp markdown copy for the same selection.',
38
+ 'With --quarter you get that quarter document; adhoc goals are included unless --no-adhoc.',
39
+ 'With --year alone each quarter appears in order under a year heading, and quarters without goals are listed as `**No goals:**`.',
40
+ '--quarter needs --year.',
41
+ 'An empty quarter or year prints an empty-state document and a `No goals found` note on stderr, exit 0.',
42
+ 'Markdown goes to stdout; diagnostics go to stderr.',
43
+ '--goal IDs come from `goals goal list`.',
44
+ 'An unknown or foreign goal ID fails (exit 1) with nothing written.',
45
+ '--out writes the file only on success.',
46
+ ],
47
+ },
48
+ },
49
+ };
@@ -0,0 +1,194 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { open, rename, unlink } from 'node:fs/promises';
3
+ import { basename, dirname, join } from 'node:path';
4
+ import { booleanFlag, listFlag, parseFlags, stringFlag, usageFailure } from '../args.js';
5
+ import { selectIdentity } from '../auth/select.js';
6
+ import { runFamilyAction } from '../dispatch.js';
7
+ import { CliError, safeMessage } from '../errors.js';
8
+ import { intFlag, omitUndefined, requiredInt } from './goal-flags.js';
9
+ import { generateMultipleQuarterlyGoalsMarkdown, generateYearMarkdown, } from '../vendor/quarterly-markdown/index.js';
10
+ const HINT = 'goals export markdown --help';
11
+ const FLAGS = {
12
+ year: { type: 'string' },
13
+ quarter: { type: 'string' },
14
+ 'completed-only': { type: 'boolean' },
15
+ goal: { type: 'string', multiple: true },
16
+ domain: { type: 'string', multiple: true },
17
+ 'no-adhoc': { type: 'boolean' },
18
+ out: { type: 'string' },
19
+ as: { type: 'string' },
20
+ };
21
+ /** Every quarter a year-only export requests, in the order the document renders them. */
22
+ const YEAR_QUARTERS = [1, 2, 3, 4];
23
+ /** Literal the dashboard uses to mean "adhoc goals with no domain". */
24
+ const UNCATEGORIZED = 'UNCATEGORIZED';
25
+ function isQuarter(value) {
26
+ return value === 1 || value === 2 || value === 3 || value === 4;
27
+ }
28
+ /** `--quarter`, range-checked by `intFlag` and narrowed to 1-4 without a cast. */
29
+ function quarterFlag(parsed) {
30
+ const value = intFlag(parsed, 'quarter', HINT);
31
+ return isQuarter(value) ? value : undefined;
32
+ }
33
+ /**
34
+ * Every value of a repeatable flag: trimmed, non-empty, de-duplicated in first-seen order.
35
+ * Returns `undefined` when the flag was not passed at all.
36
+ */
37
+ function repeatedValues(parsed, name) {
38
+ const values = listFlag(parsed, name).map((value) => value.trim());
39
+ if (values.length === 0)
40
+ return undefined;
41
+ if (values.includes(''))
42
+ throw usageFailure(`--${name} must not be empty`, HINT);
43
+ return [...new Set(values)];
44
+ }
45
+ /** `--domain` values, with a case-insensitive `uncategorized` mapped to the wire literal. */
46
+ function domainValues(parsed) {
47
+ return repeatedValues(parsed, 'domain')?.map((value) => value.toLowerCase() === 'uncategorized' ? UNCATEGORIZED : value);
48
+ }
49
+ /** `--out`, kept as the user wrote it; an explicitly empty value is a usage error. */
50
+ function outFlag(parsed) {
51
+ const value = stringFlag(parsed, 'out');
52
+ if (value === undefined)
53
+ return undefined;
54
+ if (value.trim() === '')
55
+ throw usageFailure('--out must not be empty', HINT);
56
+ return value;
57
+ }
58
+ /** Rule 3: `--goal` ids are only meaningful for one quarter; a year-only export rejects them. */
59
+ function goalFilter(parsed, quarter) {
60
+ const goalIds = repeatedValues(parsed, 'goal');
61
+ if (goalIds === undefined)
62
+ return undefined;
63
+ if (quarter === undefined) {
64
+ throw usageFailure('--goal requires --quarter (a goal belongs to exactly one quarter)', HINT);
65
+ }
66
+ return goalIds;
67
+ }
68
+ /** Rule 4: `--domain` filters the adhoc goals `--no-adhoc` removes, so the pair is rejected. */
69
+ function domainFilter(parsed, includeAdhoc) {
70
+ const adhocDomainIds = domainValues(parsed);
71
+ if (adhocDomainIds === undefined)
72
+ return undefined;
73
+ if (!includeAdhoc)
74
+ throw usageFailure('--domain cannot be combined with --no-adhoc', HINT);
75
+ return adhocDomainIds;
76
+ }
77
+ /** Rules 1-5: everything about the flags is decided here, before any credential read. */
78
+ function parseExportRequest(parsed) {
79
+ const year = requiredInt(parsed, 'year', 'for export', HINT);
80
+ const quarter = quarterFlag(parsed);
81
+ const includeAdhoc = !booleanFlag(parsed, 'no-adhoc');
82
+ return {
83
+ year,
84
+ quarter,
85
+ completedOnly: booleanFlag(parsed, 'completed-only'),
86
+ goalIds: goalFilter(parsed, quarter),
87
+ adhocDomainIds: domainFilter(parsed, includeAdhoc),
88
+ includeAdhoc,
89
+ out: outFlag(parsed),
90
+ };
91
+ }
92
+ /** The wire request for one quarter; absent filters never reach the body. */
93
+ function quarterArgs(request, quarter) {
94
+ return omitUndefined({
95
+ year: request.year,
96
+ quarter,
97
+ goalIds: request.goalIds,
98
+ includeAdhoc: request.includeAdhoc,
99
+ adhocDomainIds: request.adhocDomainIds,
100
+ });
101
+ }
102
+ /** A summary is empty on its raw goal lists, before `--completed-only` filtering. */
103
+ function isEmpty(summary) {
104
+ return summary.quarterlyGoals.length === 0 && (summary.adhocGoals?.length ?? 0) === 0;
105
+ }
106
+ async function fetchQuarter(ctx, identity, request, quarter) {
107
+ const result = await ctx.api.call(identity.credential, 'export.quarterSummary', quarterArgs(request, quarter));
108
+ return result.summary;
109
+ }
110
+ function renderOptions(request, now) {
111
+ return { omitIncomplete: request.completedOnly, now };
112
+ }
113
+ /** One quarter's document; an empty summary still prints the document plus a stderr note. */
114
+ async function exportQuarter(ctx, identity, request, quarter, now) {
115
+ const summary = await fetchQuarter(ctx, identity, request, quarter);
116
+ return {
117
+ markdown: generateMultipleQuarterlyGoalsMarkdown(summary, renderOptions(request, now)),
118
+ ...(isEmpty(summary) ? { emptyNote: `No goals found for Q${quarter} ${request.year}\n` } : {}),
119
+ };
120
+ }
121
+ /** Every quarter in ascending order, then the year document over the same single `now`. */
122
+ async function exportYear(ctx, identity, request, now) {
123
+ const quarters = [];
124
+ for (const quarter of YEAR_QUARTERS) {
125
+ quarters.push({ quarter, summary: await fetchQuarter(ctx, identity, request, quarter) });
126
+ }
127
+ const allEmpty = quarters.every(({ summary }) => isEmpty(summary));
128
+ return {
129
+ markdown: generateYearMarkdown(request.year, quarters, renderOptions(request, now)),
130
+ ...(allEmpty ? { emptyNote: `No goals found for ${request.year}\n` } : {}),
131
+ };
132
+ }
133
+ /** True when the value is a Node filesystem error carrying an errno `code`. */
134
+ function isErrnoError(error) {
135
+ return (typeof error === 'object' && error !== null && 'code' in error && typeof error.code === 'string');
136
+ }
137
+ function writeFailureReason(error) {
138
+ if (isErrnoError(error))
139
+ return error.code;
140
+ return safeMessage(error instanceof Error ? error.message : undefined, 'unknown error');
141
+ }
142
+ /**
143
+ * Writes `text` beside `path` and renames it into place, so a failure never leaves a partial
144
+ * file: the destination keeps its old content until the rename succeeds. Parent directories
145
+ * are never created.
146
+ */
147
+ async function writeFileAtomically(path, text) {
148
+ const tmp = join(dirname(path), `.${basename(path)}.${randomUUID()}.tmp`);
149
+ let created = false;
150
+ try {
151
+ const handle = await open(tmp, 'wx');
152
+ created = true;
153
+ try {
154
+ await handle.writeFile(text);
155
+ await handle.sync();
156
+ }
157
+ finally {
158
+ await handle.close();
159
+ }
160
+ await rename(tmp, path);
161
+ }
162
+ catch (error) {
163
+ if (created)
164
+ await unlink(tmp).catch(() => { });
165
+ throw new CliError(`Could not write ${path}: ${writeFailureReason(error)}`);
166
+ }
167
+ }
168
+ /** Markdown to stdout by default, or the file with `--out`; diagnostics always to stderr. */
169
+ async function emitExport(ctx, request, result) {
170
+ if (request.out === undefined) {
171
+ ctx.deps.stdout.write(result.markdown);
172
+ }
173
+ else {
174
+ await writeFileAtomically(request.out, result.markdown);
175
+ ctx.deps.stderr.write(`Wrote ${request.out}\n`);
176
+ }
177
+ if (result.emptyNote !== undefined)
178
+ ctx.deps.stderr.write(result.emptyNote);
179
+ }
180
+ /** `goals export markdown` — the webapp's quarterly summary markdown, for one quarter or a year. */
181
+ async function runExportMarkdown(args, ctx) {
182
+ const parsed = parseFlags(args, FLAGS, HINT);
183
+ const request = parseExportRequest(parsed);
184
+ const identity = await selectIdentity(parsed, ctx);
185
+ const now = ctx.deps.now();
186
+ const result = request.quarter === undefined
187
+ ? await exportYear(ctx, identity, request, now)
188
+ : await exportQuarter(ctx, identity, request, request.quarter, now);
189
+ await emitExport(ctx, request, result);
190
+ }
191
+ const ACTIONS = { markdown: runExportMarkdown };
192
+ export async function runExportCommand(args, ctx) {
193
+ await runFamilyAction('export', ACTIONS, args, ctx);
194
+ }
@@ -0,0 +1,111 @@
1
+ import { stringFlag, usageFailure } from '../args.js';
2
+ /** The four goal families, in the order the CLI documents them. */
3
+ const SCOPES = ['quarterly', 'weekly', 'daily', 'adhoc'];
4
+ const SCOPES_TEXT = SCOPES.join(', ');
5
+ /** Integer flags and their inclusive range; mirrors the gateway's zod limits. */
6
+ const INTEGER_RANGES = {
7
+ year: { min: 2000, max: 2100 },
8
+ quarter: { min: 1, max: 4 },
9
+ week: { min: 1, max: 53 },
10
+ limit: { min: 1, max: 500 },
11
+ };
12
+ /** Every accepted `--day` spelling; Monday is 1 and Sunday is 7 (the backend's `DayOfWeek`). */
13
+ const DAY_ALIASES = {
14
+ '1': 1,
15
+ '2': 2,
16
+ '3': 3,
17
+ '4': 4,
18
+ '5': 5,
19
+ '6': 6,
20
+ '7': 7,
21
+ mon: 1,
22
+ monday: 1,
23
+ tue: 2,
24
+ tuesday: 2,
25
+ wed: 3,
26
+ wednesday: 3,
27
+ thu: 4,
28
+ thursday: 4,
29
+ fri: 5,
30
+ friday: 5,
31
+ sat: 6,
32
+ saturday: 6,
33
+ sun: 7,
34
+ sunday: 7,
35
+ };
36
+ function integerText(name) {
37
+ const { min, max } = INTEGER_RANGES[name];
38
+ return `--${name} must be an integer from ${min} to ${max}`;
39
+ }
40
+ /** The number `raw` names, or `undefined` when it is not an integer inside the flag's range. */
41
+ function inRange(name, raw) {
42
+ const { min, max } = INTEGER_RANGES[name];
43
+ if (!/^\d+$/.test(raw))
44
+ return undefined;
45
+ const value = Number(raw);
46
+ return value >= min && value <= max ? value : undefined;
47
+ }
48
+ /** A numeric flag, or `undefined` when absent; its range is checked here, not by the server. */
49
+ export function intFlag(parsed, name, hint) {
50
+ const raw = stringFlag(parsed, name);
51
+ if (raw === undefined)
52
+ return undefined;
53
+ const value = inRange(name, raw);
54
+ if (value === undefined)
55
+ throw usageFailure(integerText(name), hint);
56
+ return value;
57
+ }
58
+ /** The required numeric flag, with the scope-specific `is required for …` message. */
59
+ export function requiredInt(parsed, name, subject, hint) {
60
+ const value = intFlag(parsed, name, hint);
61
+ if (value === undefined)
62
+ throw usageFailure(`--${name} is required ${subject}`, hint);
63
+ return value;
64
+ }
65
+ /** `--scope`, defaulted when the command has one; unknown values are a usage error. */
66
+ export function scopeFlag(parsed, hint, fallback) {
67
+ const raw = stringFlag(parsed, 'scope');
68
+ if (raw === undefined) {
69
+ if (fallback !== undefined)
70
+ return fallback;
71
+ throw usageFailure('--scope is required', hint);
72
+ }
73
+ const scope = SCOPES.find((candidate) => candidate === raw);
74
+ if (scope === undefined)
75
+ throw usageFailure(`--scope must be one of ${SCOPES_TEXT}`, hint);
76
+ return scope;
77
+ }
78
+ /** `--day` as 1-7 (Monday first), accepting `mon`/`monday`… and rejecting everything else. */
79
+ export function dayFlag(parsed, hint) {
80
+ const raw = stringFlag(parsed, 'day');
81
+ if (raw === undefined)
82
+ return undefined;
83
+ const day = DAY_ALIASES[raw.trim().toLowerCase()];
84
+ if (day === undefined)
85
+ throw usageFailure('--day must be 1-7 or mon..sun', hint);
86
+ return day;
87
+ }
88
+ /** A required text flag, trimmed; empty is a usage error, never an empty request value. */
89
+ export function requiredText(parsed, name, hint) {
90
+ const raw = stringFlag(parsed, name);
91
+ if (raw === undefined)
92
+ throw usageFailure(`--${name} is required`, hint);
93
+ const value = raw.trim();
94
+ if (value === '')
95
+ throw usageFailure(`--${name} must not be empty`, hint);
96
+ return value;
97
+ }
98
+ /** An optional text flag; an explicitly empty value is a usage error. */
99
+ export function optionalText(parsed, name, hint) {
100
+ const raw = stringFlag(parsed, name);
101
+ if (raw === undefined)
102
+ return undefined;
103
+ const value = raw.trim();
104
+ if (value === '')
105
+ throw usageFailure(`--${name} must not be empty`, hint);
106
+ return value;
107
+ }
108
+ /** Drops keys whose value is `undefined`, so request bodies never carry absent flags. */
109
+ export function omitUndefined(input) {
110
+ return Object.fromEntries(Object.entries(input).filter(([, value]) => value !== undefined));
111
+ }
@@ -0,0 +1,95 @@
1
+ import { formatKeyValues, formatTable } from '../output.js';
2
+ import { htmlToPlainText } from '../vendor/quarterly-markdown/index.js';
3
+ const DAY_NAMES = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
4
+ /** `YYYY-MM-DD` in UTC; the wire contract stores instants, the CLI prints calendar dates. */
5
+ export function isoDate(ms) {
6
+ return new Date(ms).toISOString().slice(0, 10);
7
+ }
8
+ /** ` Q3`, ` W31`… or an empty string when the part is absent. */
9
+ function periodPart(value, prefix) {
10
+ return value === undefined ? '' : ` ${prefix}${value}`;
11
+ }
12
+ function dayPart(dayOfWeek) {
13
+ if (dayOfWeek === undefined)
14
+ return '';
15
+ return ` ${DAY_NAMES[dayOfWeek - 1] ?? ''}`;
16
+ }
17
+ /** e.g. `2026 Q3 W31 Wed` for a daily goal, `2026 W31` for an adhoc one. */
18
+ function periodOf(row) {
19
+ return `${row.year}${periodPart(row.quarter, 'Q')}${periodPart(row.week, 'W')}${dayPart(row.dayOfWeek)}`;
20
+ }
21
+ function statusText(row) {
22
+ if (!row.isComplete)
23
+ return 'incomplete';
24
+ return row.completedAt === undefined ? 'complete' : `complete (${isoDate(row.completedAt)})`;
25
+ }
26
+ function parentText(detail) {
27
+ if (detail.parentId === undefined)
28
+ return undefined;
29
+ return detail.parentTitle === undefined
30
+ ? detail.parentId
31
+ : `${detail.parentTitle} (${detail.parentId})`;
32
+ }
33
+ function domainText(detail) {
34
+ if (detail.domainId === undefined)
35
+ return undefined;
36
+ return detail.domainName === undefined
37
+ ? detail.domainId
38
+ : `${detail.domainName} (${detail.domainId})`;
39
+ }
40
+ /** Appends one row only when the value is present. */
41
+ function withRow(rows, key, value) {
42
+ if (value !== undefined)
43
+ rows.push([key, value]);
44
+ return rows;
45
+ }
46
+ /** The `Key: value` block of `goal get`, with absent rows omitted. */
47
+ function detailRows(detail) {
48
+ const rows = [
49
+ ['ID', detail.id],
50
+ ['Title', detail.title],
51
+ ['Scope', detail.scope],
52
+ ['Status', statusText(detail)],
53
+ ['Period', periodOf(detail)],
54
+ ];
55
+ withRow(rows, 'Parent', parentText(detail));
56
+ withRow(rows, 'Domain', domainText(detail));
57
+ withRow(rows, 'Initiative', detail.initiativeId);
58
+ withRow(rows, 'Due', detail.dueDate === undefined ? undefined : isoDate(detail.dueDate));
59
+ return rows;
60
+ }
61
+ /** A blank line, a title, then the plain text of `html` indented two spaces; empty → no lines. */
62
+ export function plainTextBlock(title, html) {
63
+ const lines = htmlToPlainText(html)
64
+ .split('\n')
65
+ .filter((line) => line !== '');
66
+ if (lines.length === 0)
67
+ return [];
68
+ return ['', title, ...lines.map((line) => ` ${line}`)];
69
+ }
70
+ function childLines(detail) {
71
+ if (detail.children.length === 0)
72
+ return [];
73
+ return [
74
+ '',
75
+ 'Children:',
76
+ ...detail.children.map((child) => ` ${child.isComplete ? '[x]' : '[ ]'} ${child.id} ${child.title}`),
77
+ ];
78
+ }
79
+ /** The full `goal get` text: key/values, then plain-text details, then children. */
80
+ export function formatGoalDetail(detail) {
81
+ const blocks = [
82
+ formatKeyValues(detailRows(detail)).trimEnd(),
83
+ ...plainTextBlock('Details:', detail.details ?? ''),
84
+ ...childLines(detail),
85
+ ];
86
+ return `${blocks.join('\n')}\n`;
87
+ }
88
+ /** The `goal list` table: one row per goal, status marker first. */
89
+ export function formatGoalTable(rows) {
90
+ return formatTable(['ID', 'STATUS', 'PERIOD', 'TITLE'], rows.map((row) => [row.id, row.isComplete ? '[x]' : '[ ]', periodOf(row), row.title]), []);
91
+ }
92
+ /** stderr note when the server capped a list. */
93
+ export function truncationNote(noun, shown) {
94
+ return `Showing the first ${shown} ${noun}; more exist. Use --limit to raise the cap (max 500).\n`;
95
+ }