@kodly.dev/kodly-cli 1.0.18 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +131 -39
- package/dist/bin/kodly.js +23 -38
- package/dist/commands/auth.js +73 -78
- package/dist/commands/code.js +238 -0
- package/dist/commands/completion.js +33 -76
- package/dist/commands/delivery.js +218 -0
- package/dist/commands/harness.js +68 -0
- package/dist/commands/local-qa.js +96 -0
- package/dist/commands/mcp.js +399 -0
- package/dist/commands/misc.js +58 -0
- package/dist/commands/org.js +43 -100
- package/dist/commands/plan.js +157 -0
- package/dist/commands/project.js +88 -86
- package/dist/commands/review.js +237 -0
- package/dist/commands/scaffold.js +20 -230
- package/dist/commands/story-write.js +210 -0
- package/dist/commands/story.js +154 -0
- package/dist/core/api.js +89 -0
- package/dist/core/browser.js +17 -0
- package/dist/core/checkout.js +58 -0
- package/dist/core/config.js +36 -0
- package/dist/core/confirm.js +36 -0
- package/dist/core/context.js +64 -0
- package/dist/core/credentials.js +62 -0
- package/dist/core/device-login.js +44 -0
- package/dist/core/errors.js +32 -0
- package/dist/core/format.js +32 -0
- package/dist/core/git.js +29 -0
- package/dist/core/keychain.js +9 -0
- package/dist/core/memberships.js +10 -0
- package/dist/core/output.js +31 -0
- package/dist/core/prompt.js +47 -0
- package/dist/core/push-checks.js +60 -0
- package/dist/core/story-file.js +120 -0
- package/dist/core/story.js +34 -0
- package/dist/program.js +48 -0
- package/dist/utils/update-check.js +9 -9
- package/llm.txt +47 -83
- package/package.json +21 -11
- package/dist/api/client.js +0 -96
- package/dist/commands/docs.js +0 -152
- package/dist/commands/man.js +0 -93
- package/dist/commands/push.js +0 -51
- package/dist/commands/status.js +0 -52
- package/dist/commands/task.js +0 -155
- package/dist/utils/changes.js +0 -90
- package/dist/utils/checkout.js +0 -168
- package/dist/utils/config.js +0 -34
- package/dist/utils/org.js +0 -138
- package/dist/utils/project.js +0 -21
- package/dist/utils/session.js +0 -28
- package/dist/utils/task.js +0 -25
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import chalk from 'chalk';
|
|
6
|
+
import { configDir } from '../core/config.js';
|
|
7
|
+
import { buildContext } from '../core/context.js';
|
|
8
|
+
import { ApiError, CliError, ExitCode } from '../core/errors.js';
|
|
9
|
+
import { projectPath, storyPath } from '../core/format.js';
|
|
10
|
+
import { emit, run } from '../core/output.js';
|
|
11
|
+
import { confirm, editText, interactive } from '../core/prompt.js';
|
|
12
|
+
import { findStory, requestId } from '../core/story.js';
|
|
13
|
+
import { CREATE_TEMPLATE, isEmpty, parseStory, storyYaml, toDocument, toFields, } from '../core/story-file.js';
|
|
14
|
+
/** Reads a file, or stdin for "-". */
|
|
15
|
+
const readInput = (file) => {
|
|
16
|
+
try {
|
|
17
|
+
return file === '-' ? fs.readFileSync(0, 'utf8') : fs.readFileSync(file, 'utf8');
|
|
18
|
+
}
|
|
19
|
+
catch (e) {
|
|
20
|
+
throw new CliError(`Could not read ${file}: ${e.message}`, ExitCode.USAGE);
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
/** Shows the change from `before` to `after` with git, which every kodly user has. */
|
|
24
|
+
const showDiff = (before, after) => {
|
|
25
|
+
const dir = fs.mkdtempSync(path.join(tmpdir(), 'kodly-diff-'));
|
|
26
|
+
try {
|
|
27
|
+
fs.writeFileSync(path.join(dir, 'current.yaml'), before);
|
|
28
|
+
fs.writeFileSync(path.join(dir, 'edited.yaml'), after);
|
|
29
|
+
spawnSync('git', ['--no-pager', 'diff', '--no-index', '--color=auto', 'current.yaml', 'edited.yaml'], { cwd: dir, stdio: ['ignore', 'inherit', 'inherit'] });
|
|
30
|
+
}
|
|
31
|
+
finally {
|
|
32
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
/** Keeps an edit that the server refused, so the person does not lose it. */
|
|
36
|
+
const keepDraft = (text, story) => {
|
|
37
|
+
const dir = path.join(configDir() ?? path.join(tmpdir(), 'kodly'), 'drafts');
|
|
38
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
39
|
+
const file = path.join(dir, `${story}-${Date.now()}.yaml`);
|
|
40
|
+
fs.writeFileSync(file, text, { mode: 0o600 });
|
|
41
|
+
return file;
|
|
42
|
+
};
|
|
43
|
+
export const currentStory = (api, project, slug) => api.request(storyPath(project, slug, '/story'));
|
|
44
|
+
/** Saves a new story version from the scope document of a file, and the version header in it. */
|
|
45
|
+
export const saveStoryVersion = (api, project, slug, h, change, dryRun = false) => api.request(storyPath(project, slug, '/revisions/local'), {
|
|
46
|
+
method: 'POST',
|
|
47
|
+
query: dryRun ? { validateOnly: true } : undefined,
|
|
48
|
+
body: {
|
|
49
|
+
requestId: requestId(), expectedVersion: h.version, storyFingerprint: h.fingerprint, story: change.story, edits: change.edits,
|
|
50
|
+
reason: change.reason, harness: change.harness ?? 'cli', model: change.model,
|
|
51
|
+
},
|
|
52
|
+
});
|
|
53
|
+
/** Creates a story with a pending scope, or with an approved scope after the browser confirmation. */
|
|
54
|
+
export const createStory = (api, project, fields, options) => api.request(projectPath(project, '/requirements/local'), {
|
|
55
|
+
method: 'POST',
|
|
56
|
+
query: options.dryRun ? { validateOnly: true } : undefined,
|
|
57
|
+
body: { requestId: requestId(), story: fields, approveScope: options.approve === true, reason: options.reason, harness: options.harness ?? 'cli', model: options.model },
|
|
58
|
+
});
|
|
59
|
+
const disabled = (e) => {
|
|
60
|
+
if (e instanceof ApiError && e.status === 404 && /cli\.feature\.disabled/.test(JSON.stringify(e.data ?? e.message))) {
|
|
61
|
+
throw new CliError('Story create and edit from the CLI are off on this Kodly server. Ask an administrator to turn on kodly.cli.story-write.', ExitCode.ERROR);
|
|
62
|
+
}
|
|
63
|
+
throw e;
|
|
64
|
+
};
|
|
65
|
+
export const storyWriteCommands = (story, cliVersion) => {
|
|
66
|
+
story
|
|
67
|
+
.command('create')
|
|
68
|
+
.description('Create a story. Its scope waits for approval, unless you add --approve (needs your approval in the browser)')
|
|
69
|
+
.option('-f, --file <path>', 'a YAML or JSON story file, or - for stdin')
|
|
70
|
+
.option('--title <text>', 'the title')
|
|
71
|
+
.option('--goal <text>', 'the goal')
|
|
72
|
+
.option('--summary <text>', 'a short summary')
|
|
73
|
+
.option('--criterion <text>', 'an acceptance criterion (repeat it for more)', (value, all = []) => [...all, value])
|
|
74
|
+
.option('--kind <kind>', 'STORY or EPIC')
|
|
75
|
+
.option('--codebase <slug>', 'the codebase of the story')
|
|
76
|
+
.option('--approve', 'also approve the scope, so that Kodly starts the plan')
|
|
77
|
+
.option('--dry-run', 'check the story on the server and save nothing')
|
|
78
|
+
.action(run(async (options, command) => {
|
|
79
|
+
const ctx = buildContext(command, cliVersion);
|
|
80
|
+
const project = ctx.project();
|
|
81
|
+
const flags = options.title !== undefined || options.goal !== undefined || options.criterion !== undefined;
|
|
82
|
+
if (options.file && flags)
|
|
83
|
+
throw new CliError('Give the story with -f or with --title, --goal and --criterion, not both.', ExitCode.USAGE);
|
|
84
|
+
let values;
|
|
85
|
+
let source = options.file ?? 'the command line';
|
|
86
|
+
if (options.file) {
|
|
87
|
+
values = parseStory(readInput(options.file), source, 'create').values;
|
|
88
|
+
}
|
|
89
|
+
else if (flags) {
|
|
90
|
+
values = { title: options.title, goal: options.goal, summary: options.summary, acceptanceCriteria: options.criterion, kind: options.kind, targetProjectSlug: options.codebase };
|
|
91
|
+
}
|
|
92
|
+
else if (interactive()) {
|
|
93
|
+
source = 'the story';
|
|
94
|
+
const text = editText(CREATE_TEMPLATE, 'story.yaml');
|
|
95
|
+
if (isEmpty(text))
|
|
96
|
+
throw new CliError('The file is empty, so no story was created.', ExitCode.USAGE);
|
|
97
|
+
values = parseStory(text, source, 'create').values;
|
|
98
|
+
}
|
|
99
|
+
else {
|
|
100
|
+
throw new CliError('Give the story with -f <file>, -f - for stdin, or --title, --goal and --criterion.', ExitCode.USAGE);
|
|
101
|
+
}
|
|
102
|
+
const fields = toFields(values, source);
|
|
103
|
+
const created = await createStory(ctx.api, project, fields, { approve: options.approve, dryRun: options.dryRun }).catch(disabled);
|
|
104
|
+
emit(ctx.json, created, () => {
|
|
105
|
+
if (options.dryRun) {
|
|
106
|
+
console.log(chalk.green(created.next));
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
const id = created.story?.identifier ?? created.story?.slug ?? '?';
|
|
110
|
+
console.log(chalk.green(`Created ${id}: ${fields.title}`));
|
|
111
|
+
console.log(created.scopeApproved ? created.next : chalk.yellow(created.next));
|
|
112
|
+
});
|
|
113
|
+
}));
|
|
114
|
+
story
|
|
115
|
+
.command('edit')
|
|
116
|
+
.argument('<story>', 'the story identifier or slug')
|
|
117
|
+
.description('Edit the scope of a story in your editor or from a file. The new version waits for a scope approval')
|
|
118
|
+
.option('-f, --file <path>', 'a story file with the kodly-story header line (from --print), or - for stdin')
|
|
119
|
+
.option('--print', 'print the current story with its header line, for an edit in a file')
|
|
120
|
+
.option('--reason <text>', 'why the scope changes')
|
|
121
|
+
.option('-y, --yes', 'do not ask before the save')
|
|
122
|
+
.option('--dry-run', 'check the edit on the server and save nothing')
|
|
123
|
+
.action(run(async (id, options, command) => {
|
|
124
|
+
const ctx = buildContext(command, cliVersion);
|
|
125
|
+
const project = ctx.project();
|
|
126
|
+
const item = await findStory(ctx.api, project, id);
|
|
127
|
+
const current = await currentStory(ctx.api, project, item.slug).catch(disabled);
|
|
128
|
+
const name = current.identifier ?? item.identifier ?? item.slug;
|
|
129
|
+
const h = { story: name, version: current.version, fingerprint: current.storyFingerprint };
|
|
130
|
+
const before = storyYaml(h, current.story);
|
|
131
|
+
if (options.print) {
|
|
132
|
+
if (ctx.json)
|
|
133
|
+
emit(true, current, () => undefined);
|
|
134
|
+
else
|
|
135
|
+
process.stdout.write(before);
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
let text;
|
|
139
|
+
if (options.file) {
|
|
140
|
+
text = readInput(options.file);
|
|
141
|
+
}
|
|
142
|
+
else {
|
|
143
|
+
text = editText(before, `${name}.yaml`);
|
|
144
|
+
if (isEmpty(text))
|
|
145
|
+
throw new CliError('The file is empty, so nothing was saved.', ExitCode.USAGE);
|
|
146
|
+
}
|
|
147
|
+
const parsed = parseStory(text, options.file ?? name, 'edit');
|
|
148
|
+
if (!parsed.header) {
|
|
149
|
+
throw new CliError(`The file has no "# kodly-story:" header line, so kodly cannot tell which version you edited. Get one with: kodly story edit ${name} --print`, ExitCode.USAGE);
|
|
150
|
+
}
|
|
151
|
+
if (parsed.header.story.toLowerCase() !== name.toLowerCase() && parsed.header.story.toLowerCase() !== item.slug.toLowerCase()) {
|
|
152
|
+
throw new CliError(`The file is for ${parsed.header.story}, not ${name}.`, ExitCode.USAGE);
|
|
153
|
+
}
|
|
154
|
+
const document = toDocument(parsed.values, options.file ?? name);
|
|
155
|
+
const after = storyYaml(parsed.header, document);
|
|
156
|
+
if (JSON.stringify(document) === JSON.stringify(toDocument(parseStory(before, name, 'edit').values, name))) {
|
|
157
|
+
emit(ctx.json, { changed: false }, () => console.log('No change, so nothing was saved.'));
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
if (!ctx.json)
|
|
161
|
+
showDiff(before, after);
|
|
162
|
+
if (!options.dryRun && !(await confirm(`Save this as a new version of ${name}? The new scope then needs an approval.`, options.yes === true))) {
|
|
163
|
+
throw new CliError('Nothing was saved.', ExitCode.USAGE);
|
|
164
|
+
}
|
|
165
|
+
let saved;
|
|
166
|
+
try {
|
|
167
|
+
saved = await saveStoryVersion(ctx.api, project, item.slug, parsed.header, { story: document, reason: options.reason }, options.dryRun);
|
|
168
|
+
}
|
|
169
|
+
catch (e) {
|
|
170
|
+
if (e instanceof ApiError && e.status === 409) {
|
|
171
|
+
const kept = keepDraft(text, name);
|
|
172
|
+
throw new CliError(`${name} changed after you started the edit, so nothing was saved. Your edit is in ${kept}.\n`
|
|
173
|
+
+ `Run kodly story edit ${name} --print to see the new version, merge your change into ${kept}, and update its header line. Then: kodly story edit ${name} -f ${kept}`, ExitCode.CONFLICT);
|
|
174
|
+
}
|
|
175
|
+
throw e;
|
|
176
|
+
}
|
|
177
|
+
emit(ctx.json, saved, () => {
|
|
178
|
+
if (options.dryRun)
|
|
179
|
+
console.log(chalk.green(`The edit is valid. It would be version ${saved.version}. Nothing was saved.`));
|
|
180
|
+
else
|
|
181
|
+
console.log(chalk.green(`Saved ${name} version ${saved.version}.`) + ` Approve the new scope: kodly scope approve ${name}`);
|
|
182
|
+
});
|
|
183
|
+
}));
|
|
184
|
+
const archive = (archived) => run(async (id, options, command) => {
|
|
185
|
+
const ctx = buildContext(command, cliVersion);
|
|
186
|
+
const project = ctx.project();
|
|
187
|
+
const item = await findStory(ctx.api, project, id);
|
|
188
|
+
const name = item.identifier ?? item.slug;
|
|
189
|
+
const revision = item.archive?.revision ?? 0;
|
|
190
|
+
const question = archived
|
|
191
|
+
? `Archive ${name}? Kodly stops its work and closes its code.`
|
|
192
|
+
: `Restore ${name}?`;
|
|
193
|
+
if (!(await confirm(question, options.yes === true)))
|
|
194
|
+
throw new CliError('Nothing was changed.', ExitCode.USAGE);
|
|
195
|
+
const view = await ctx.api.request(storyPath(project, item.slug, '/archive'), { method: 'PUT', body: { archived, expectedRevision: revision } });
|
|
196
|
+
emit(ctx.json, view, () => console.log(chalk.green(`${archived ? 'Archived' : 'Restored'} ${name}.`)));
|
|
197
|
+
});
|
|
198
|
+
story
|
|
199
|
+
.command('archive')
|
|
200
|
+
.argument('<story>', 'the story identifier or slug')
|
|
201
|
+
.option('-y, --yes', 'do not ask first')
|
|
202
|
+
.description('Archive a story (needs your approval in the browser). Restore it with kodly story restore')
|
|
203
|
+
.action(archive(true));
|
|
204
|
+
story
|
|
205
|
+
.command('restore')
|
|
206
|
+
.argument('<story>', 'the story identifier or slug')
|
|
207
|
+
.option('-y, --yes', 'do not ask first')
|
|
208
|
+
.description('Restore an archived story (needs your approval in the browser)')
|
|
209
|
+
.action(archive(false));
|
|
210
|
+
};
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import chalk from 'chalk';
|
|
2
|
+
import { Option } from 'commander';
|
|
3
|
+
import { buildContext } from '../core/context.js';
|
|
4
|
+
import { CliError, ExitCode } from '../core/errors.js';
|
|
5
|
+
import { ago, flag, projectPath, storyPath, table } from '../core/format.js';
|
|
6
|
+
import { emit, run } from '../core/output.js';
|
|
7
|
+
import { storyWriteCommands } from './story-write.js';
|
|
8
|
+
import { blockedReasons, deliveryOf, findStory } from '../core/story.js';
|
|
9
|
+
const LANES = ['needs-review', 'planning', 'ready-to-start', 'in-progress', 'ready-for-release', 'closed'];
|
|
10
|
+
const STAGES = ['UNDERSTAND', 'PLAN', 'TEST_PLAN', 'BUILD', 'TEST', 'REVIEW', 'RELEASE'];
|
|
11
|
+
const owner = (card) => card.ownership?.person?.name ?? (card.ownership?.teamName ? `team ${card.ownership.teamName}` : '');
|
|
12
|
+
export const storyCommands = (program, cliVersion) => {
|
|
13
|
+
const listStories = (list) => list
|
|
14
|
+
.description('List the stories of the active project')
|
|
15
|
+
.option('--mine', 'only the stories where you are involved')
|
|
16
|
+
.option('--team', 'only the stories of your team')
|
|
17
|
+
.addOption(new Option('--lane <lane>', 'only one lane').choices(LANES))
|
|
18
|
+
.option('-q, --search <text>', 'search the stories')
|
|
19
|
+
.option('--closed', 'include the closed stories')
|
|
20
|
+
.option('--limit <n>', 'the number of stories (1 to 100)', '25')
|
|
21
|
+
.action(run(async (options, command) => {
|
|
22
|
+
const ctx = buildContext(command, cliVersion);
|
|
23
|
+
const project = ctx.project();
|
|
24
|
+
const query = { layout: 'list', limit: options.limit, q: options.search, includeClosed: options.closed === true, me: options.mine, team: options.team };
|
|
25
|
+
const board = await ctx.api.request(projectPath(project, '/backlog/lanes'), { query });
|
|
26
|
+
const page = options.lane
|
|
27
|
+
? await ctx.api.request(projectPath(project, '/backlog/pages'), { query: { ...query, snapshot: board.snapshot, lane: options.lane } })
|
|
28
|
+
: board.list;
|
|
29
|
+
const items = page?.items ?? [];
|
|
30
|
+
emit(ctx.json, { items, total: page?.total ?? 0 }, () => {
|
|
31
|
+
if (items.length === 0)
|
|
32
|
+
console.log('No stories.');
|
|
33
|
+
table(items.map((s) => [chalk.cyan(s.identifier ?? s.slug), s.title ?? '', s.lane ?? '', (s.kind ?? '').toLowerCase(), owner(s)]), ['STORY', 'TITLE', 'LANE', 'KIND', 'OWNER']);
|
|
34
|
+
const total = page?.total ?? items.length;
|
|
35
|
+
if (total > items.length)
|
|
36
|
+
console.log(chalk.dim(`${items.length} of ${total}. Use --limit or --search for more.`));
|
|
37
|
+
});
|
|
38
|
+
}));
|
|
39
|
+
listStories(program.command('backlog'));
|
|
40
|
+
const story = program.command('story').description('One story of the active project');
|
|
41
|
+
listStories(story.command('list'));
|
|
42
|
+
storyWriteCommands(story, cliVersion);
|
|
43
|
+
story
|
|
44
|
+
.command('local')
|
|
45
|
+
.argument('<story>', 'the story identifier or slug')
|
|
46
|
+
.argument('[mode]', 'local, hosted or project; leave it out to show the setting')
|
|
47
|
+
.description('Show or change local work for one story (a change needs your approval in the browser)')
|
|
48
|
+
.action(run(async (id, mode, _options, command) => {
|
|
49
|
+
const ctx = buildContext(command, cliVersion);
|
|
50
|
+
const project = ctx.project();
|
|
51
|
+
const item = await findStory(ctx.api, project, id);
|
|
52
|
+
const path = storyPath(project, item.slug, '/local-work');
|
|
53
|
+
const modes = { local: 'LOCAL', hosted: 'HOSTED', project: 'PROJECT' };
|
|
54
|
+
if (mode !== undefined && !modes[mode])
|
|
55
|
+
throw new CliError('Choose local, hosted or project.', ExitCode.USAGE);
|
|
56
|
+
const view = mode === undefined
|
|
57
|
+
? await ctx.api.request(path)
|
|
58
|
+
: await ctx.api.request(path, { method: 'PUT', body: { mode: modes[mode] } });
|
|
59
|
+
emit(ctx.json, view, () => {
|
|
60
|
+
const source = view.story === null || view.story === undefined ? 'follows the project' : 'set on the story';
|
|
61
|
+
console.log(`${item.identifier ?? item.slug}: ${view.effective ? chalk.green('local work') : 'hosted runs'} (${source})`);
|
|
62
|
+
if (view.effective)
|
|
63
|
+
console.log(chalk.dim('Kodly starts no automatic hosted plan, test plan or build runs for this story.'));
|
|
64
|
+
});
|
|
65
|
+
}));
|
|
66
|
+
story
|
|
67
|
+
.command('show')
|
|
68
|
+
.argument('<story>', 'the story identifier or slug')
|
|
69
|
+
.description('Show a story and where it is in the workflow')
|
|
70
|
+
.action(run(async (id, _options, command) => {
|
|
71
|
+
const ctx = buildContext(command, cliVersion);
|
|
72
|
+
const project = ctx.project();
|
|
73
|
+
const item = await findStory(ctx.api, project, id);
|
|
74
|
+
const delivery = await deliveryOf(ctx.api, project, item.slug);
|
|
75
|
+
emit(ctx.json, { story: item, delivery }, () => {
|
|
76
|
+
const workflow = delivery.workflow ?? {};
|
|
77
|
+
console.log(`${chalk.bold(item.identifier ?? item.slug)} ${item.title ?? ''}`);
|
|
78
|
+
console.log(chalk.dim(`${(item.kind ?? '').toLowerCase()}, stage ${workflow.stage ?? '?'}, owner ${owner(item) || 'none'}`));
|
|
79
|
+
if (item.summary)
|
|
80
|
+
console.log(`\n${item.summary}`);
|
|
81
|
+
if (item.acceptanceCriteria?.length) {
|
|
82
|
+
console.log(chalk.bold('\nAcceptance criteria'));
|
|
83
|
+
item.acceptanceCriteria.forEach((criterion, i) => console.log(` ${i + 1}. ${criterion}`));
|
|
84
|
+
}
|
|
85
|
+
const plan = delivery.implementation?.plan;
|
|
86
|
+
const testPlan = delivery.testPreparation?.plan;
|
|
87
|
+
console.log(chalk.bold('\nDelivery'));
|
|
88
|
+
table([
|
|
89
|
+
['Plan', plan ? `v${plan.version}, ${delivery.implementation?.approval ? 'approved' : 'not approved'}${delivery.implementation?.outdated ? ', outdated' : ''}` : 'none'],
|
|
90
|
+
['Test plan', testPlan ? `v${testPlan.version}, ${delivery.testPreparation?.approval ? 'approved' : 'not approved'}${delivery.testPreparation?.outdated ? ', outdated' : ''}` : 'none'],
|
|
91
|
+
['Build', delivery.build ? `${delivery.build.state?.toLowerCase()} ${ago(delivery.build.createdAt)}${delivery.buildCurrent ? '' : ', outdated'}` : 'none'],
|
|
92
|
+
['QA run', delivery.testRun ? `${delivery.testRun.state?.toLowerCase()} ${ago(delivery.testRun.createdAt)}` : 'none'],
|
|
93
|
+
['Review', delivery.review ? `${delivery.review.decision?.toLowerCase()} by ${delivery.review.reviewedByEmail ?? '?'}${delivery.review.merge ? ', merged' : ''}` : 'none'],
|
|
94
|
+
['Can build', flag(delivery.canBuild)],
|
|
95
|
+
['Can send to QA', flag(workflow.canSendToQa)],
|
|
96
|
+
['Can release', flag(delivery.canReview)],
|
|
97
|
+
]);
|
|
98
|
+
for (const step of ['build', 'qa', 'release']) {
|
|
99
|
+
const reasons = blockedReasons(delivery, step);
|
|
100
|
+
if (reasons)
|
|
101
|
+
console.log(chalk.dim(`${step}: ${reasons}`));
|
|
102
|
+
}
|
|
103
|
+
if (delivery.codebaseIssue?.message)
|
|
104
|
+
console.log(chalk.yellow(delivery.codebaseIssue.message));
|
|
105
|
+
});
|
|
106
|
+
}));
|
|
107
|
+
story
|
|
108
|
+
.command('activity')
|
|
109
|
+
.argument('<story>', 'the story identifier or slug')
|
|
110
|
+
.description('The latest events of a story')
|
|
111
|
+
.action(run(async (id, _options, command) => {
|
|
112
|
+
const ctx = buildContext(command, cliVersion);
|
|
113
|
+
const project = ctx.project();
|
|
114
|
+
const item = await findStory(ctx.api, project, id);
|
|
115
|
+
const activity = await ctx.api.request(storyPath(project, item.slug, '/activity'));
|
|
116
|
+
const events = activity?.events ?? [];
|
|
117
|
+
emit(ctx.json, activity, () => table(events.map((e) => [ago(e.at), e.kind ?? '', [e.stage, e.state].filter(Boolean).join(' ').toLowerCase(), e.actorName ?? e.agentName ?? '', e.detail ?? '']), ['WHEN', 'EVENT', 'STATE', 'BY', 'DETAIL']));
|
|
118
|
+
}));
|
|
119
|
+
story
|
|
120
|
+
.command('history')
|
|
121
|
+
.argument('<story>', 'the story identifier or slug')
|
|
122
|
+
.addOption(new Option('--of <output>', 'which output').choices(['STORY', 'IMPLEMENTATION', 'TEST_PLAN']).default('STORY'))
|
|
123
|
+
.description('The versions of the story, the plan or the test plan')
|
|
124
|
+
.action(run(async (id, options, command) => {
|
|
125
|
+
const ctx = buildContext(command, cliVersion);
|
|
126
|
+
const project = ctx.project();
|
|
127
|
+
const item = await findStory(ctx.api, project, id);
|
|
128
|
+
const history = await ctx.api.request(storyPath(project, item.slug, '/history'), { query: { output: options.of } });
|
|
129
|
+
const revisions = history?.revisions ?? [];
|
|
130
|
+
emit(ctx.json, history, () => table(revisions.map((r) => [`v${r.version}`, ago(r.createdAt), r.createdByEmail ?? '', r.approval ? `approved by ${r.approval.approvedByEmail ?? '?'}` : '']), ['VERSION', 'WHEN', 'BY', 'APPROVAL']));
|
|
131
|
+
}));
|
|
132
|
+
story
|
|
133
|
+
.command('claim')
|
|
134
|
+
.argument('<story>', 'the story identifier or slug')
|
|
135
|
+
.addOption(new Option('--stage <stage>', 'the stage to own (default: the current stage)').choices(STAGES))
|
|
136
|
+
.description('Make yourself the owner of a stage of the story (needs your approval in the browser)')
|
|
137
|
+
.action(run(async (id, options, command) => {
|
|
138
|
+
const ctx = buildContext(command, cliVersion);
|
|
139
|
+
const project = ctx.project();
|
|
140
|
+
const item = await findStory(ctx.api, project, id);
|
|
141
|
+
const path = projectPath(project, `/backlog/${encodeURIComponent(item.slug)}/ownership`);
|
|
142
|
+
const view = await ctx.api.request(path);
|
|
143
|
+
const me = await ctx.api.request('/auth/user/validate-token', { method: 'POST' });
|
|
144
|
+
const userId = me?.data?.id;
|
|
145
|
+
if (!userId || !view.people?.some((p) => p.id === userId)) {
|
|
146
|
+
throw new CliError('You are not a member of this project, so you cannot own a stage.', ExitCode.USAGE);
|
|
147
|
+
}
|
|
148
|
+
const stage = options.stage ?? view.currentStage;
|
|
149
|
+
if (!stage)
|
|
150
|
+
throw new CliError('The story has no current stage. Name one with --stage.', ExitCode.USAGE);
|
|
151
|
+
await ctx.api.request(path, { method: 'PUT', body: { revision: view.revision, teamRevision: view.teamRevision, stage, useDefault: false, userId } });
|
|
152
|
+
emit(ctx.json, { story: item.identifier ?? item.slug, stage, owner: me?.data?.email }, () => console.log(`You own ${stage.toLowerCase()} of ${item.identifier ?? item.slug}.`));
|
|
153
|
+
}));
|
|
154
|
+
};
|
package/dist/core/api.js
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { ApiError, CliError } from './errors.js';
|
|
2
|
+
export const CONFIRMATION_HEADER = 'X-Kodly-Confirmation';
|
|
3
|
+
export const CONFIRMATION_REQUIRED = 'auth.cli.confirmation.required';
|
|
4
|
+
const TARGET = /^\/api\/v1\/workspace\/([^/]+)(?:\/(?:requirements|backlog)\/([^/]+))?/;
|
|
5
|
+
/**
|
|
6
|
+
* The line that names the organisation, the project and the story of a write, or undefined when
|
|
7
|
+
* the path names no project. The person sees what a command changes before it changes it.
|
|
8
|
+
*/
|
|
9
|
+
export const targetLine = (orgSlug, pathname) => {
|
|
10
|
+
const match = TARGET.exec(pathname);
|
|
11
|
+
if (!match)
|
|
12
|
+
return undefined;
|
|
13
|
+
const story = match[2] ? `, story ${decodeURIComponent(match[2])}` : '';
|
|
14
|
+
return `Kodly target: org ${orgSlug || '(your default)'}, project ${decodeURIComponent(match[1])}${story}`;
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* The kodly-api client. It sends `X-AUTH-TOKEN` and `X-ORG-SLUG`, and it unwraps the
|
|
18
|
+
* `RestResponse` envelope. A human-only route refuses a CLI token with 403
|
|
19
|
+
* `auth.cli.confirmation.required`. The client then gets a browser confirmation for the same
|
|
20
|
+
* request and sends it once more, with the same bytes, because the proof binds the body hash.
|
|
21
|
+
*/
|
|
22
|
+
export class Api {
|
|
23
|
+
constructor(session, confirmer, fetchImpl = fetch) {
|
|
24
|
+
this.session = session;
|
|
25
|
+
this.confirmer = confirmer;
|
|
26
|
+
this.fetchImpl = fetchImpl;
|
|
27
|
+
}
|
|
28
|
+
async request(path, options = {}) {
|
|
29
|
+
const method = options.method ?? 'GET';
|
|
30
|
+
const url = new URL(`/api/v1${path}`, this.session.apiUrl);
|
|
31
|
+
for (const [key, value] of Object.entries(options.query ?? {})) {
|
|
32
|
+
if (value !== undefined)
|
|
33
|
+
url.searchParams.set(key, String(value));
|
|
34
|
+
}
|
|
35
|
+
const body = options.bytes ?? (options.body === undefined ? undefined : JSON.stringify(options.body));
|
|
36
|
+
if (method !== 'GET' && !options.anonymous && !options.quiet) {
|
|
37
|
+
// stderr, so that --json output on stdout stays clean.
|
|
38
|
+
const line = targetLine(this.session.orgSlug, url.pathname);
|
|
39
|
+
if (line)
|
|
40
|
+
process.stderr.write(line + '\n');
|
|
41
|
+
}
|
|
42
|
+
try {
|
|
43
|
+
return await this.send(method, url, body, options);
|
|
44
|
+
}
|
|
45
|
+
catch (error) {
|
|
46
|
+
if (!(error instanceof ApiError) || error.code !== CONFIRMATION_REQUIRED || options.confirm === false || !this.confirmer
|
|
47
|
+
|| typeof body !== 'string' && body !== undefined) {
|
|
48
|
+
throw error;
|
|
49
|
+
}
|
|
50
|
+
const proof = await this.confirmer({ method, path: url.pathname, query: url.search.replace(/^\?/, ''), orgSlug: this.session.orgSlug ?? '', body: body ?? '' }, this);
|
|
51
|
+
return this.send(method, url, body, options, proof);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
async send(method, url, body, options, proof) {
|
|
55
|
+
const headers = { Accept: 'application/json', 'User-Agent': `kodly-cli/${this.session.cliVersion}` };
|
|
56
|
+
if (body !== undefined)
|
|
57
|
+
headers['Content-Type'] = typeof body === 'string' ? 'application/json' : 'application/octet-stream';
|
|
58
|
+
if (!options.anonymous && this.session.token)
|
|
59
|
+
headers['X-AUTH-TOKEN'] = this.session.token;
|
|
60
|
+
if (this.session.orgSlug)
|
|
61
|
+
headers['X-ORG-SLUG'] = this.session.orgSlug;
|
|
62
|
+
if (proof)
|
|
63
|
+
headers[CONFIRMATION_HEADER] = proof;
|
|
64
|
+
let response;
|
|
65
|
+
try {
|
|
66
|
+
response = await this.fetchImpl(url, { method, headers, body: body });
|
|
67
|
+
}
|
|
68
|
+
catch (error) {
|
|
69
|
+
throw new CliError(`Kodly is not reachable at ${this.session.apiUrl}: ${error.message}`);
|
|
70
|
+
}
|
|
71
|
+
const text = await response.text();
|
|
72
|
+
let json;
|
|
73
|
+
try {
|
|
74
|
+
json = text ? JSON.parse(text) : undefined;
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
json = undefined;
|
|
78
|
+
}
|
|
79
|
+
if (!response.ok) {
|
|
80
|
+
const envelope = (json ?? {});
|
|
81
|
+
const message = typeof envelope.message === 'string' && envelope.message ? envelope.message
|
|
82
|
+
: typeof envelope.error === 'string' ? envelope.error : `Kodly refused the call (HTTP ${response.status}).`;
|
|
83
|
+
throw new ApiError(message, response.status, envelope.data ?? json ?? null);
|
|
84
|
+
}
|
|
85
|
+
if (options.raw)
|
|
86
|
+
return json;
|
|
87
|
+
return json?.data;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
/** Opens a link in the default browser. A failure is silent, because the CLI also prints the link. */
|
|
3
|
+
export const openBrowser = (url) => {
|
|
4
|
+
if (process.env.KODLY_NO_BROWSER === '1')
|
|
5
|
+
return;
|
|
6
|
+
const [command, args] = process.platform === 'darwin' ? ['open', [url]]
|
|
7
|
+
: process.platform === 'win32' ? ['cmd', ['/c', 'start', '""', url]]
|
|
8
|
+
: ['xdg-open', [url]];
|
|
9
|
+
try {
|
|
10
|
+
const child = spawn(command, args, { stdio: 'ignore', detached: true });
|
|
11
|
+
child.on('error', () => { });
|
|
12
|
+
child.unref();
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
// The person opens the printed link.
|
|
16
|
+
}
|
|
17
|
+
};
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { CliError, ExitCode } from './errors.js';
|
|
4
|
+
/** The file at the root of a CLI checkout. It holds names and URLs only: never a token. */
|
|
5
|
+
export const CONTEXT_FILE = path.join('.kodly', 'story.json');
|
|
6
|
+
/** Finds the checkout that contains `start`, walking up to the file system root. */
|
|
7
|
+
export const findCheckout = (start = process.cwd()) => {
|
|
8
|
+
let dir = path.resolve(start);
|
|
9
|
+
for (;;) {
|
|
10
|
+
const file = path.join(dir, CONTEXT_FILE);
|
|
11
|
+
if (fs.existsSync(file))
|
|
12
|
+
return { root: dir, context: JSON.parse(fs.readFileSync(file, 'utf8')) };
|
|
13
|
+
const parent = path.dirname(dir);
|
|
14
|
+
if (parent === dir)
|
|
15
|
+
throw new CliError('This folder is not a kodly checkout. Run "kodly checkout <story>" first.', ExitCode.USAGE);
|
|
16
|
+
dir = parent;
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* The checkout that contains `start` when it is a checkout of `story`, or undefined when there is no
|
|
21
|
+
* checkout. A checkout of another story is an error: a command must never give the agent a story
|
|
22
|
+
* that the user did not name. The story matches by its slug or by its identifier, in any case.
|
|
23
|
+
*/
|
|
24
|
+
export const checkoutOf = (story, start) => {
|
|
25
|
+
let found;
|
|
26
|
+
try {
|
|
27
|
+
found = findCheckout(start);
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
return undefined;
|
|
31
|
+
}
|
|
32
|
+
const named = story.trim().toLowerCase();
|
|
33
|
+
if ([found.context.story, found.context.identifier].some((value) => value?.toLowerCase() === named))
|
|
34
|
+
return found;
|
|
35
|
+
const current = found.context.identifier ?? found.context.story;
|
|
36
|
+
throw new CliError(`The folder ${found.root} is a checkout of ${current}, but the command names ${story}. `
|
|
37
|
+
+ `Run the command outside this checkout, or name another folder with --dir.`, ExitCode.USAGE);
|
|
38
|
+
};
|
|
39
|
+
export const writeContext = (root, context) => {
|
|
40
|
+
fs.mkdirSync(path.join(root, '.kodly'), { recursive: true });
|
|
41
|
+
fs.writeFileSync(path.join(root, CONTEXT_FILE), JSON.stringify(context, null, 2) + '\n', { mode: 0o600 });
|
|
42
|
+
};
|
|
43
|
+
/**
|
|
44
|
+
* The absolute path of `relative` inside `base`, or an error when the path leaves `base` (security
|
|
45
|
+
* review S-1: the old CLI wrote any path that the server sent).
|
|
46
|
+
*/
|
|
47
|
+
export const insideDir = (base, relative) => {
|
|
48
|
+
if (!relative || path.isAbsolute(relative) || relative.split(/[\\/]/).some((part) => part === '..' || part === '.git')) {
|
|
49
|
+
throw new CliError(`Kodly sent a file path that is not allowed: ${relative}`);
|
|
50
|
+
}
|
|
51
|
+
const target = path.resolve(base, relative);
|
|
52
|
+
if (target !== path.resolve(base) && !target.startsWith(path.resolve(base) + path.sep)) {
|
|
53
|
+
throw new CliError(`Kodly sent a file path outside the checkout: ${relative}`);
|
|
54
|
+
}
|
|
55
|
+
return target;
|
|
56
|
+
};
|
|
57
|
+
/** A folder name that is safe on every platform. */
|
|
58
|
+
export const safeName = (value) => value.replace(/[^A-Za-z0-9._-]/g, '-').replace(/^[-.]+/, '') || 'story';
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import Conf from 'conf';
|
|
2
|
+
/** The production API. `--api` or `KODLY_API_URL` choose another one (fixes F-2 of the security review). */
|
|
3
|
+
export const DEFAULT_API_URL = 'https://api.app.kodly.dev';
|
|
4
|
+
let store;
|
|
5
|
+
/** The folder of the settings and credentials files. `KODLY_CONFIG_DIR` overrides it, for CI and tests. */
|
|
6
|
+
export const configDir = () => process.env.KODLY_CONFIG_DIR || undefined;
|
|
7
|
+
/** The settings file. It holds no token: the token is in the OS keychain (see credentials.ts). */
|
|
8
|
+
export const settings = () => {
|
|
9
|
+
store ?? (store = new Conf({ projectName: 'kodly', cwd: configDir(), configFileMode: 0o600 }));
|
|
10
|
+
return store;
|
|
11
|
+
};
|
|
12
|
+
/** The API base URL: the flag, then the environment, then the saved value, then production. */
|
|
13
|
+
export const resolveApiUrl = (flag) => {
|
|
14
|
+
const value = flag || process.env.KODLY_API_URL || settings().get('apiUrl') || DEFAULT_API_URL;
|
|
15
|
+
let url;
|
|
16
|
+
try {
|
|
17
|
+
url = new URL(value);
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
throw new Error(`The API URL is not valid: ${value}`);
|
|
21
|
+
}
|
|
22
|
+
const local = url.hostname === 'localhost' || url.hostname === '127.0.0.1';
|
|
23
|
+
if (url.protocol !== 'https:' && !(local && url.protocol === 'http:')) {
|
|
24
|
+
throw new Error(`The API URL must use https (http only for localhost): ${value}`);
|
|
25
|
+
}
|
|
26
|
+
return url.origin;
|
|
27
|
+
};
|
|
28
|
+
/** The web app that belongs to an API: api.app.kodly.dev to app.kodly.dev, localhost:8081 to localhost:3000. */
|
|
29
|
+
export const webUrlFor = (apiUrl) => {
|
|
30
|
+
const url = new URL(apiUrl);
|
|
31
|
+
if (url.hostname === 'localhost' || url.hostname === '127.0.0.1')
|
|
32
|
+
return `${url.protocol}//${url.hostname}:3000`;
|
|
33
|
+
if (url.hostname.startsWith('api.'))
|
|
34
|
+
return `${url.protocol}//${url.hostname.slice(4)}`;
|
|
35
|
+
return url.origin;
|
|
36
|
+
};
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import chalk from 'chalk';
|
|
2
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
3
|
+
import { openBrowser } from './browser.js';
|
|
4
|
+
import { CliError, ExitCode } from './errors.js';
|
|
5
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
6
|
+
/**
|
|
7
|
+
* The browser confirmation of a human-only step (docs/kodly-cli-v2-plan-2026-11-04.md). The CLI
|
|
8
|
+
* keeps a random secret in memory and sends only its SHA-256. The person approves the step on the
|
|
9
|
+
* Kodly web page. A local agent can run the CLI, but it cannot approve there.
|
|
10
|
+
*/
|
|
11
|
+
export const browserConfirmer = (options) => async (request, api) => {
|
|
12
|
+
const log = options.log ?? ((line) => process.stderr.write(line + '\n'));
|
|
13
|
+
const secret = randomBytes(32).toString('base64url');
|
|
14
|
+
const verifier = createHash('sha256').update(secret).digest('base64url');
|
|
15
|
+
const created = await api.request('/auth/cli/confirmations', {
|
|
16
|
+
method: 'POST',
|
|
17
|
+
body: { ...request, verifier },
|
|
18
|
+
confirm: false,
|
|
19
|
+
});
|
|
20
|
+
log(chalk.yellow(`This step needs your approval in the browser: ${chalk.bold(created.label)}`));
|
|
21
|
+
log(` Open: ${chalk.cyan(created.verificationUri)}`);
|
|
22
|
+
if (options.openBrowser)
|
|
23
|
+
openBrowser(created.verificationUri);
|
|
24
|
+
const deadline = new Date(created.expiresAt).getTime();
|
|
25
|
+
while (Date.now() < deadline) {
|
|
26
|
+
await sleep(options.pollMs ?? 2000);
|
|
27
|
+
const view = await api.request(`/auth/cli/confirmations/${encodeURIComponent(created.id)}`, { confirm: false });
|
|
28
|
+
if (view.state === 'APPROVED')
|
|
29
|
+
return `${created.id}.${secret}`;
|
|
30
|
+
if (view.state === 'DENIED')
|
|
31
|
+
throw new CliError('The step was denied in the browser.', ExitCode.NOT_APPROVED);
|
|
32
|
+
if (view.state !== 'PENDING')
|
|
33
|
+
break;
|
|
34
|
+
}
|
|
35
|
+
throw new CliError('The confirmation expired. Run the command again.', ExitCode.NOT_APPROVED);
|
|
36
|
+
};
|