@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.
Files changed (52) hide show
  1. package/README.md +131 -39
  2. package/dist/bin/kodly.js +23 -38
  3. package/dist/commands/auth.js +73 -78
  4. package/dist/commands/code.js +238 -0
  5. package/dist/commands/completion.js +33 -76
  6. package/dist/commands/delivery.js +218 -0
  7. package/dist/commands/harness.js +68 -0
  8. package/dist/commands/local-qa.js +96 -0
  9. package/dist/commands/mcp.js +399 -0
  10. package/dist/commands/misc.js +58 -0
  11. package/dist/commands/org.js +43 -100
  12. package/dist/commands/plan.js +157 -0
  13. package/dist/commands/project.js +88 -86
  14. package/dist/commands/review.js +237 -0
  15. package/dist/commands/scaffold.js +20 -230
  16. package/dist/commands/story-write.js +210 -0
  17. package/dist/commands/story.js +154 -0
  18. package/dist/core/api.js +89 -0
  19. package/dist/core/browser.js +17 -0
  20. package/dist/core/checkout.js +58 -0
  21. package/dist/core/config.js +36 -0
  22. package/dist/core/confirm.js +36 -0
  23. package/dist/core/context.js +64 -0
  24. package/dist/core/credentials.js +62 -0
  25. package/dist/core/device-login.js +44 -0
  26. package/dist/core/errors.js +32 -0
  27. package/dist/core/format.js +32 -0
  28. package/dist/core/git.js +29 -0
  29. package/dist/core/keychain.js +9 -0
  30. package/dist/core/memberships.js +10 -0
  31. package/dist/core/output.js +31 -0
  32. package/dist/core/prompt.js +47 -0
  33. package/dist/core/push-checks.js +60 -0
  34. package/dist/core/story-file.js +120 -0
  35. package/dist/core/story.js +34 -0
  36. package/dist/program.js +48 -0
  37. package/dist/utils/update-check.js +9 -9
  38. package/llm.txt +47 -83
  39. package/package.json +21 -11
  40. package/dist/api/client.js +0 -96
  41. package/dist/commands/docs.js +0 -152
  42. package/dist/commands/man.js +0 -93
  43. package/dist/commands/push.js +0 -51
  44. package/dist/commands/status.js +0 -52
  45. package/dist/commands/task.js +0 -155
  46. package/dist/utils/changes.js +0 -90
  47. package/dist/utils/checkout.js +0 -168
  48. package/dist/utils/config.js +0 -34
  49. package/dist/utils/org.js +0 -138
  50. package/dist/utils/project.js +0 -21
  51. package/dist/utils/session.js +0 -28
  52. package/dist/utils/task.js +0 -25
@@ -0,0 +1,238 @@
1
+ import chalk from 'chalk';
2
+ import { randomUUID } from 'node:crypto';
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { Api } from '../core/api.js';
6
+ import { findCheckout, insideDir, safeName, writeContext } from '../core/checkout.js';
7
+ import { buildContext } from '../core/context.js';
8
+ import { readToken } from '../core/credentials.js';
9
+ import { CliError, ExitCode } from '../core/errors.js';
10
+ import { storyPath, table } from '../core/format.js';
11
+ import { git, gitTry } from '../core/git.js';
12
+ import { emit, run } from '../core/output.js';
13
+ import { blobId, checkPush } from '../core/push-checks.js';
14
+ import { deliveryOf, findStory } from '../core/story.js';
15
+ /**
16
+ * True when git asks for the credentials of the push URL (the inbox), else it asks for the fetch URL
17
+ * (the story fork). With credential.useHttpPath, git sends the path of the URL.
18
+ */
19
+ export const isPushRequest = (fields, pushRemote) => {
20
+ if (fields.path === undefined)
21
+ return false;
22
+ const want = new URL(pushRemote);
23
+ return fields.path.replace(/^\//, '') === want.pathname.replace(/^\//, '') && (!fields.host || fields.host === want.host);
24
+ };
25
+ const EXCLUDE_MARK = '# kodly: generated files, written by kodly checkout';
26
+ /** Writes the generated files of a codebase and makes git ignore them. Returns their blob ids. */
27
+ const writeGenerated = async (api, context, codebase, dir) => {
28
+ const files = (await api.request(`${storyPath(context.project, context.story, '/code/generated')}`, { query: { codebase: codebase.codebase } })) ?? [];
29
+ const ids = {};
30
+ for (const file of files) {
31
+ const target = insideDir(dir, file.path);
32
+ const bytes = Buffer.from(file.contentBase64, 'base64');
33
+ fs.mkdirSync(path.dirname(target), { recursive: true });
34
+ fs.writeFileSync(target, bytes);
35
+ ids[file.path] = blobId(bytes);
36
+ }
37
+ const exclude = path.join(dir, '.git', 'info', 'exclude');
38
+ const kept = fs.existsSync(exclude) ? fs.readFileSync(exclude, 'utf8').split(EXCLUDE_MARK)[0].trimEnd() : '';
39
+ fs.mkdirSync(path.dirname(exclude), { recursive: true });
40
+ fs.writeFileSync(exclude, `${kept}\n${EXCLUDE_MARK}\n${Object.keys(ids).sort().map((p) => '/' + p).join('\n')}\n`);
41
+ return ids;
42
+ };
43
+ /** The API client of a checkout: the API, the organisation and the project that the checkout names. */
44
+ const checkoutApi = (command, cliVersion, context) => checkoutApiFor(buildContext(command, cliVersion).api.session, context);
45
+ /**
46
+ * Clones the code of a story into `dir`: one git repository for each codebase of its build. A story
47
+ * with no saved build gets its story base: main as a hosted first build reads it.
48
+ */
49
+ export const checkoutStory = async (ctx, id, dir) => {
50
+ const project = ctx.project();
51
+ const item = await findStory(ctx.api, project, id);
52
+ const root = path.resolve(dir ?? safeName(item.identifier ?? item.slug));
53
+ if (fs.existsSync(root) && fs.readdirSync(root).length > 0) {
54
+ throw new CliError(`${root} is not empty. Choose another folder with --dir.`, ExitCode.USAGE);
55
+ }
56
+ const views = (await ctx.api.request(storyPath(project, item.slug, '/code/checkout'), { method: 'POST', quiet: true })) ?? [];
57
+ if (views.length === 0)
58
+ throw new CliError('The build of this story has no codebases.', ExitCode.CONFLICT);
59
+ const context = {
60
+ api: ctx.apiUrl, org: ctx.api.session.orgSlug, project, story: item.slug, identifier: item.identifier, codebases: [], baseBuildId: views[0].baseBuildId,
61
+ };
62
+ fs.mkdirSync(root, { recursive: true });
63
+ writeContext(root, context);
64
+ const self = process.argv[1] ? `"${process.execPath}" "${path.resolve(process.argv[1])}"` : 'kodly';
65
+ for (const view of views) {
66
+ if (!view.commit)
67
+ throw new CliError(`${view.codebase}: ${view.reasons.join(' ')}`, ExitCode.CONFLICT);
68
+ const dir = insideDir(root, safeName(view.codebase));
69
+ fs.mkdirSync(dir, { recursive: true });
70
+ const codebase = { codebase: view.codebase, dir: path.relative(root, dir), remote: view.remote, pushRemote: view.pushRemote, generated: {} };
71
+ // The credential helper reads the codebase from the context file. Write it before the first
72
+ // fetch, so the helper can ask Kodly for a token. A later failure keeps the codebases set up so far.
73
+ context.codebases.push(codebase);
74
+ writeContext(root, context);
75
+ await git(dir, ['init', '--quiet', '--initial-branch', 'story']);
76
+ await git(dir, ['remote', 'add', 'origin', view.remote]);
77
+ await git(dir, ['config', 'remote.origin.pushurl', view.pushRemote]);
78
+ // The helper asks Kodly for a 1 h token each time git needs one. No token goes into a file.
79
+ // The empty value clears the helpers of the user and system config, such as osxkeychain.
80
+ // Otherwise git asks them first, gets an expired token, and also stores each new token there.
81
+ await git(dir, ['config', 'credential.helper', '']);
82
+ await git(dir, ['config', '--add', 'credential.helper', `!${self} git-credential --checkout "${root}" --codebase ${view.codebase}`]);
83
+ await git(dir, ['config', 'credential.useHttpPath', 'true']);
84
+ await git(dir, ['fetch', '--quiet', 'origin', 'main']);
85
+ await git(dir, ['reset', '--quiet', '--hard', view.commit]);
86
+ await git(dir, ['branch', '--quiet', '--set-upstream-to', 'origin/main']).catch(() => undefined);
87
+ codebase.generated = await writeGenerated(ctx.api, context, codebase, dir);
88
+ writeContext(root, context);
89
+ }
90
+ return { root, context, item };
91
+ };
92
+ /**
93
+ * Checks the commits of each codebase, pushes them to a staging ref of its inbox, and asks Kodly to
94
+ * import them as a new build. `kodly push` and the push tool of `kodly mcp` both use it.
95
+ */
96
+ export const pushCheckout = async (api, root, context, options) => {
97
+ const commits = {};
98
+ const problems = [];
99
+ for (const codebase of context.codebases) {
100
+ const dir = path.join(root, codebase.dir);
101
+ await git(dir, ['fetch', '--quiet', 'origin', 'main']);
102
+ const plan = await checkPush(dir, codebase.codebase, codebase.generated);
103
+ problems.push(...plan.problems);
104
+ if (plan.head)
105
+ commits[codebase.codebase] = plan.head;
106
+ }
107
+ if (problems.length)
108
+ throw new CliError(`The push stops:\n ${problems.join('\n ')}`, ExitCode.USAGE);
109
+ if (Object.keys(commits).length === 0)
110
+ throw new CliError('Nothing to push: no codebase has new commits.', ExitCode.USAGE);
111
+ // A story with a build pushes on it. A first push builds on the story base that the checkout started from.
112
+ const build = (await deliveryOf(api, context.project, context.story)).build;
113
+ const baseBuildId = build?.id ?? context.baseBuildId;
114
+ if (!baseBuildId)
115
+ throw new CliError('The story has no story code yet. Run "kodly checkout <story>" again, then push.', ExitCode.CONFLICT);
116
+ const pushId = randomUUID();
117
+ for (const [codebase, head] of Object.entries(commits)) {
118
+ const dir = path.join(root, context.codebases.find((c) => c.codebase === codebase).dir);
119
+ await git(dir, ['push', '--quiet', 'origin', `${head}:refs/kodly/cli/${pushId}`]);
120
+ }
121
+ const result = await api.request(storyPath(context.project, context.story, '/code/pushes'), {
122
+ method: 'POST', body: { pushId, baseBuildId, commits, reportedModel: options.model, reportedHarness: options.harness },
123
+ });
124
+ return { commits, result };
125
+ };
126
+ /** The API client of a checkout: the API, the organisation and the project that the checkout names. */
127
+ export const checkoutApiFor = (session, context) => {
128
+ const stored = readToken(context.api);
129
+ if (!stored)
130
+ throw new CliError(`You are not signed in to ${context.api}. Run "kodly --api ${context.api} login".`);
131
+ return new Api({ ...session, apiUrl: context.api, token: stored.token, orgSlug: context.org ?? session.orgSlug });
132
+ };
133
+ export const codeCommands = (program, cliVersion) => {
134
+ program
135
+ .command('checkout')
136
+ .argument('<story>', 'the story identifier or slug')
137
+ .option('--dir <path>', 'the folder for the checkout (default: the story identifier)')
138
+ .description('Clone the code of a story: one git repository for each codebase')
139
+ .action(run(async (id, options, command) => {
140
+ const ctx = buildContext(command, cliVersion);
141
+ const { root, context, item } = await checkoutStory(ctx, id, options.dir);
142
+ emit(ctx.json, { root, codebases: context.codebases.map((c) => ({ codebase: c.codebase, dir: path.join(root, c.dir) })) }, () => {
143
+ console.log(chalk.green(`Checked out ${item.identifier ?? item.slug} in ${root}`));
144
+ for (const c of context.codebases)
145
+ console.log(` ${c.codebase}: ${path.join(root, c.dir)}${Object.keys(c.generated).length ? chalk.dim(` (${Object.keys(c.generated).length} generated files, ignored by git)`) : ''}`);
146
+ console.log(chalk.dim('Commit your changes, then run kodly push.'));
147
+ });
148
+ }));
149
+ program
150
+ .command('git-credential', { hidden: true })
151
+ .argument('<operation>', 'get, store or erase (git calls this)')
152
+ .requiredOption('--checkout <root>', 'the root of the checkout')
153
+ .requiredOption('--codebase <codebase>', 'the codebase of this repository')
154
+ .description('The git credential helper of a kodly checkout')
155
+ .action(run(async (operation, options, command) => {
156
+ if (operation !== 'get')
157
+ return;
158
+ const input = fs.readFileSync(0, 'utf8');
159
+ const fields = Object.fromEntries(input.split('\n').filter((l) => l.includes('=')).map((l) => [l.slice(0, l.indexOf('=')), l.slice(l.indexOf('=') + 1)]));
160
+ const { context } = findCheckout(options.checkout);
161
+ const codebase = context.codebases.find((c) => c.codebase === options.codebase);
162
+ if (!codebase)
163
+ throw new CliError(`The checkout has no codebase ${options.codebase}.`);
164
+ const push = isPushRequest(fields, codebase.pushRemote);
165
+ const api = checkoutApi(command, cliVersion, context);
166
+ const token = await api.request(storyPath(context.project, context.story, push ? '/code/credentials/push' : '/code/credentials/read'), { method: 'POST', body: { codebase: codebase.codebase }, quiet: true });
167
+ process.stdout.write(`username=${token.username}\npassword=${token.password}\n`);
168
+ }));
169
+ program
170
+ .command('pull')
171
+ .description('Bring the latest story code into the checkout (fast-forward only)')
172
+ .action(run(async (_options, command) => {
173
+ const { root, context } = findCheckout();
174
+ const api = checkoutApi(command, cliVersion, context);
175
+ const json = command.optsWithGlobals().json === true;
176
+ const rows = [];
177
+ for (const codebase of context.codebases) {
178
+ const dir = path.join(root, codebase.dir);
179
+ await git(dir, ['fetch', '--quiet', 'origin', 'main']);
180
+ const merged = await gitTry(dir, ['merge', '--ff-only', '--quiet', 'origin/main']);
181
+ codebase.generated = await writeGenerated(api, context, codebase, dir);
182
+ rows.push({ codebase: codebase.codebase, result: merged === null ? 'not a fast-forward: rebase your commits on origin/main' : 'up to date' });
183
+ }
184
+ writeContext(root, context);
185
+ emit(json, rows, () => table(rows.map((r) => [r.codebase, r.result])));
186
+ if (rows.some((r) => r.result !== 'up to date'))
187
+ process.exitCode = ExitCode.CONFLICT;
188
+ }));
189
+ program
190
+ .command('push')
191
+ .option('--model <name>', 'the model of your local agent, for your usage view (never billed)')
192
+ .option('--harness <name>', 'the local agent tool, for example claude-code')
193
+ .description('Send your commits to Kodly as a new build. Kodly then runs the build checks in its sandbox.')
194
+ .action(run(async (options, command) => {
195
+ const { root, context } = findCheckout();
196
+ const api = checkoutApi(command, cliVersion, context);
197
+ const json = command.optsWithGlobals().json === true;
198
+ const { commits, result } = await pushCheckout(api, root, context, options);
199
+ emit(json, result, () => {
200
+ console.log(chalk.green(`Pushed ${Object.keys(commits).join(', ')} as a new build.`));
201
+ if (result.checksRun)
202
+ console.log(`Kodly runs the build checks in its sandbox. Follow them: kodly watch ${context.identifier ?? context.story}`);
203
+ else if (result.checksError)
204
+ console.log(chalk.yellow(`The build checks did not start: ${result.checksError}`));
205
+ });
206
+ }));
207
+ program
208
+ .command('status')
209
+ .description('The local state of the checkout and the state of the story in Kodly')
210
+ .action(run(async (_options, command) => {
211
+ const { root, context } = findCheckout();
212
+ const api = checkoutApi(command, cliVersion, context);
213
+ const json = command.optsWithGlobals().json === true;
214
+ const rows = [];
215
+ for (const codebase of context.codebases) {
216
+ const dir = path.join(root, codebase.dir);
217
+ const ahead = await gitTry(dir, ['rev-list', '--count', 'origin/main..HEAD']);
218
+ const changed = (await git(dir, ['status', '--porcelain'])).split('\n').filter(Boolean).length;
219
+ rows.push({ codebase: codebase.codebase, commitsToPush: Number(ahead ?? 0), uncommittedFiles: changed });
220
+ }
221
+ const delivery = await deliveryOf(api, context.project, context.story);
222
+ emit(json, { story: context.identifier ?? context.story, codebases: rows, stage: delivery.workflow?.stage, build: delivery.build?.state }, () => {
223
+ console.log(`${chalk.bold(context.identifier ?? context.story)} stage ${delivery.workflow?.stage ?? '?'}, build ${delivery.build?.state?.toLowerCase() ?? 'none'}`);
224
+ table(rows.map((r) => [r.codebase, `${r.commitsToPush} commits to push`, `${r.uncommittedFiles} changed files`]));
225
+ });
226
+ }));
227
+ program
228
+ .command('diff')
229
+ .description('Your changes against the story code in Kodly')
230
+ .action(run(async () => {
231
+ const { root, context } = findCheckout();
232
+ for (const codebase of context.codebases) {
233
+ const out = await git(path.join(root, codebase.dir), ['diff', '--stat', 'origin/main']);
234
+ if (out.trim())
235
+ process.stdout.write(`${chalk.bold(codebase.codebase)}\n${out}`);
236
+ }
237
+ }));
238
+ };
@@ -1,84 +1,41 @@
1
- export const completionCommands = (program) => {
2
- program
3
- .command('completion [shell]')
4
- .description('Generate shell completion script (options: zsh, bash, fish)')
5
- .action((shell = 'zsh') => {
6
- let script = '';
7
- if (shell === 'fish') {
8
- script = `
9
- ###-begin-kodly-completion-###
10
- #
11
- # kodly command completion script for fish
12
- #
13
- # Installation: kodly completion fish > ~/.config/fish/completions/kodly.fish
14
- #
15
-
16
- complete -c kodly -f -n '__fish_use_subcommand' -a 'login logout whoami task push status man help completion project docs org scaffold'
17
- complete -c kodly -f -n '__fish_seen_subcommand_from scaffold' -a 'init create list'
18
- complete -c kodly -f -n '__fish_seen_subcommand_from task' -a 'list checkout create'
19
- complete -c kodly -f -n '__fish_seen_subcommand_from project' -a 'checkout list'
20
- complete -c kodly -f -n '__fish_seen_subcommand_from docs' -a 'checkout push status'
21
- complete -c kodly -f -n '__fish_seen_subcommand_from org' -a 'list current switch unset'
22
-
23
- ###-end-kodly-completion-###
24
- `;
25
- }
26
- else {
27
- // Default to Zsh/Bash compatible
28
- script = `
29
- ###-begin-kodly-completion-###
30
- #
31
- # kodly command completion script
32
- #
33
- # Installation: kodly completion >> ~/.zshrc (or ~/.bashrc)
34
- #
35
-
1
+ /** The visible commands and their subcommands, read from the command tree, so the list never goes stale. */
2
+ export const commandTree = (program) => {
3
+ const tree = new Map();
4
+ const visible = (command) => !command._hidden;
5
+ for (const command of program.commands.filter(visible)) {
6
+ tree.set(command.name(), command.commands.filter(visible).map((sub) => sub.name()));
7
+ }
8
+ return tree;
9
+ };
10
+ const bashScript = (tree) => {
11
+ const cases = [...tree].filter(([, subs]) => subs.length > 0)
12
+ .map(([name, subs]) => ` ${name}) COMPREPLY=( $(compgen -W "${subs.join(' ')}" -- "$cur") ); return 0 ;;`).join('\n');
13
+ return `###-begin-kodly-completion-###
14
+ # Installation: kodly completion bash >> ~/.bashrc (zsh: kodly completion zsh >> ~/.zshrc)
36
15
  _kodly_completion() {
37
- local cur prev opts
38
- COMPREPLY=()
39
- cur="\${COMP_WORDS[COMP_CWORD]}"
40
- prev="\${COMP_WORDS[COMP_CWORD-1]}"
41
- opts="login logout whoami task push status man help completion project docs org scaffold"
42
-
43
- case "\${prev}" in
44
- kodly)
45
- COMPREPLY=( $(compgen -W "\${opts}" -- \${cur}) )
46
- return 0
47
- ;;
48
- task)
49
- local task_opts="list checkout create"
50
- COMPREPLY=( $(compgen -W "\${task_opts}" -- \${cur}) )
51
- return 0
52
- ;;
53
- project)
54
- local project_opts="checkout list"
55
- COMPREPLY=( $(compgen -W "\${project_opts}" -- \${cur}) )
56
- return 0
57
- ;;
58
- docs)
59
- local docs_opts="checkout push status"
60
- COMPREPLY=( $(compgen -W "\${docs_opts}" -- \${cur}) )
61
- return 0
62
- ;;
63
- org)
64
- local org_opts="list current switch unset"
65
- COMPREPLY=( $(compgen -W "\${org_opts}" -- \${cur}) )
66
- return 0
67
- ;;
68
- scaffold)
69
- local scaffold_opts="init create list"
70
- COMPREPLY=( $(compgen -W "\${scaffold_opts}" -- \${cur}) )
71
- return 0
72
- ;;
73
- *)
74
- ;;
16
+ local cur="\${COMP_WORDS[COMP_CWORD]}" prev="\${COMP_WORDS[COMP_CWORD-1]}"
17
+ case "$prev" in
18
+ kodly) COMPREPLY=( $(compgen -W "${[...tree.keys()].join(' ')}" -- "$cur") ); return 0 ;;
19
+ ${cases}
75
20
  esac
76
21
  }
77
-
78
22
  complete -F _kodly_completion kodly
79
23
  ###-end-kodly-completion-###
80
24
  `;
81
- }
82
- console.log(script.trim());
25
+ };
26
+ const fishScript = (tree) => [`# Installation: kodly completion fish > ~/.config/fish/completions/kodly.fish`,
27
+ `complete -c kodly -f -n '__fish_use_subcommand' -a '${[...tree.keys()].join(' ')}'`,
28
+ ...[...tree].filter(([, subs]) => subs.length > 0)
29
+ .map(([name, subs]) => `complete -c kodly -f -n '__fish_seen_subcommand_from ${name}' -a '${subs.join(' ')}'`),
30
+ ].join('\n') + '\n';
31
+ export const completionCommands = (program) => {
32
+ program
33
+ .command('completion')
34
+ .argument('[shell]', 'bash, zsh or fish', 'bash')
35
+ .description('Print a shell completion script')
36
+ .action((shell) => {
37
+ const tree = commandTree(program);
38
+ const zsh = 'autoload -U +X bashcompinit && bashcompinit\n';
39
+ process.stdout.write(shell === 'fish' ? fishScript(tree) : (shell === 'zsh' ? zsh : '') + bashScript(tree));
83
40
  });
84
41
  };
@@ -0,0 +1,218 @@
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, storyPath, table } from '../core/format.js';
6
+ import { emit, run } from '../core/output.js';
7
+ import { isLocalQa, localQaCommands } from './local-qa.js';
8
+ import { blockedReasons, deliveryOf, findStory, isActive, requestId, requireBuild, requireTestRun, } from '../core/story.js';
9
+ const TRIAGE = ['PRODUCT', 'TEST_DEFINITION', 'ENVIRONMENT', 'SCOPE', 'INVESTIGATE'];
10
+ const short = (id) => (id ? id.split(':').pop().slice(0, 8) : '');
11
+ const runLine = (r) => [short(r.id), (r.purpose ?? '').toLowerCase(), (r.state ?? '').toLowerCase(), ago(r.createdAt), r.summary?.split('\n')[0] ?? ''];
12
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
13
+ const results = (r) => {
14
+ const counts = {};
15
+ for (const result of r?.results ?? [])
16
+ counts[result.status ?? '?'] = (counts[result.status ?? '?'] ?? 0) + 1;
17
+ return Object.entries(counts).map(([status, n]) => `${n} ${status.toLowerCase()}`).join(', ');
18
+ };
19
+ export const deliveryCommands = (program, cliVersion) => {
20
+ const runCmd = program.command('run').description('Start a Kodly run in the cloud (needs your approval in the browser)');
21
+ runCmd
22
+ .command('build')
23
+ .argument('<story>', 'the story identifier or slug')
24
+ .option('--checks-only', 'run the build checks again on the current build, with no agent')
25
+ .option('-m, --message <text>', 'extra instructions for the build agent')
26
+ .description('Start the build agent, or only the build checks')
27
+ .action(run(async (id, options, command) => {
28
+ const ctx = buildContext(command, cliVersion);
29
+ const project = ctx.project();
30
+ const item = await findStory(ctx.api, project, id);
31
+ const delivery = await deliveryOf(ctx.api, project, item.slug);
32
+ const plan = delivery.implementation?.plan;
33
+ if (!plan)
34
+ throw new CliError('The story has no plan yet.', ExitCode.CONFLICT);
35
+ if (!options.checksOnly && !delivery.canBuild)
36
+ throw new CliError(`A build cannot start now. ${blockedReasons(delivery, 'build')}`.trim(), ExitCode.CONFLICT);
37
+ const body = {
38
+ purpose: 'BUILD', requestId: requestId(), planVersion: plan.version, checksOnly: options.checksOnly === true,
39
+ sourceRunId: options.checksOnly ? requireBuild(delivery).id : undefined, message: options.message,
40
+ };
41
+ const started = await ctx.api.request(storyPath(project, item.slug, '/delivery/runs'), { method: 'POST', body });
42
+ emit(ctx.json, started, () => console.log(`Started ${options.checksOnly ? 'the build checks' : 'a build'} (${short(started.id)}). Follow it: kodly watch ${item.identifier ?? item.slug}`));
43
+ }));
44
+ runCmd
45
+ .command('test')
46
+ .argument('<story>', 'the story identifier or slug')
47
+ .option('-m, --message <text>', 'a follow-up for the QA agent')
48
+ .description('Start the QA agent on the current build')
49
+ .action(run(async (id, options, command) => {
50
+ const ctx = buildContext(command, cliVersion);
51
+ const project = ctx.project();
52
+ const item = await findStory(ctx.api, project, id);
53
+ const delivery = await deliveryOf(ctx.api, project, item.slug);
54
+ const build = requireBuild(delivery);
55
+ const plan = delivery.implementation?.plan;
56
+ const testPlan = delivery.testPreparation?.plan;
57
+ if (!plan || !testPlan)
58
+ throw new CliError('The story needs a plan and a test plan first.', ExitCode.CONFLICT);
59
+ const body = { purpose: 'TEST', requestId: requestId(), planVersion: plan.version, testPlanVersion: testPlan.version, sourceRunId: build.id, message: options.message };
60
+ const started = await ctx.api.request(storyPath(project, item.slug, '/delivery/runs'), { method: 'POST', body });
61
+ emit(ctx.json, started, () => console.log(`Started a QA run (${short(started.id)}). Follow it: kodly watch ${item.identifier ?? item.slug}`));
62
+ }));
63
+ program
64
+ .command('runs')
65
+ .argument('<story>', 'the story identifier or slug')
66
+ .description('The Kodly runs of a story')
67
+ .action(run(async (id, _options, command) => {
68
+ const ctx = buildContext(command, cliVersion);
69
+ const project = ctx.project();
70
+ const item = await findStory(ctx.api, project, id);
71
+ const runs = (await ctx.api.request(storyPath(project, item.slug, '/delivery/runs'))) ?? [];
72
+ emit(ctx.json, runs, () => table(runs.map(runLine), ['RUN', 'PURPOSE', 'STATE', 'STARTED', 'SUMMARY']));
73
+ }));
74
+ program
75
+ .command('watch')
76
+ .argument('<story>', 'the story identifier or slug')
77
+ .option('--interval <seconds>', 'seconds between two checks', '5')
78
+ .description('Follow the build and QA runs of a story until no run is active')
79
+ .action(run(async (id, options, command) => {
80
+ const ctx = buildContext(command, cliVersion);
81
+ const project = ctx.project();
82
+ const item = await findStory(ctx.api, project, id);
83
+ const interval = Math.max(2, Number(options.interval) || 5) * 1000;
84
+ let last = '';
85
+ let delivery;
86
+ for (;;) {
87
+ delivery = await deliveryOf(ctx.api, project, item.slug);
88
+ const line = [`stage ${delivery.workflow?.stage ?? '?'}`,
89
+ delivery.build ? `build ${delivery.build.state?.toLowerCase()}` : 'no build',
90
+ delivery.testRun ? `QA ${delivery.testRun.state?.toLowerCase()}` : 'no QA run'].join(', ');
91
+ if (line !== last && !ctx.json)
92
+ console.log(`${new Date().toLocaleTimeString()} ${line}`);
93
+ last = line;
94
+ if (!isActive(delivery.build) && !isActive(delivery.testRun))
95
+ break;
96
+ await sleep(interval);
97
+ }
98
+ emit(ctx.json, delivery, () => {
99
+ if (delivery.workflow?.canSendToQa)
100
+ console.log(chalk.green(`Ready for QA: kodly qa send ${item.identifier ?? item.slug}`));
101
+ if (delivery.workflow?.canSendToReview)
102
+ console.log(chalk.green(`Ready for review: kodly review request ${item.identifier ?? item.slug}`));
103
+ });
104
+ }));
105
+ const checks = program.command('checks').description('The build checks of a story');
106
+ checks
107
+ .command('show')
108
+ .argument('<story>', 'the story identifier or slug')
109
+ .option('--run <id>', 'the run (default: the current build)')
110
+ .description('The results of the build checks')
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 runId = options.run ?? requireBuild(await deliveryOf(ctx.api, project, item.slug)).id;
116
+ const view = await ctx.api.request(storyPath(project, item.slug, '/delivery/checks'), { query: { runId } });
117
+ const rows = view?.results ?? [];
118
+ emit(ctx.json, view, () => {
119
+ table(rows.map((r) => [(r.status ?? '').toLowerCase(), r.check?.name ?? '', r.check?.codebaseSlug ?? '', r.check?.required ? 'required' : '', r.detail ?? '']), ['STATUS', 'CHECK', 'CODEBASE', '', 'DETAIL']);
120
+ if (view && !view.current)
121
+ console.log(chalk.yellow('The check settings changed after this run. Run the checks again: kodly run build --checks-only'));
122
+ });
123
+ }));
124
+ checks
125
+ .command('logs')
126
+ .argument('<story>', 'the story identifier or slug')
127
+ .option('--run <id>', 'the run (default: the current build)')
128
+ .option('-f, --follow', 'keep printing new output until the run ends')
129
+ .description('The output of the running build check')
130
+ .action(run(async (id, options, command) => {
131
+ const ctx = buildContext(command, cliVersion);
132
+ const project = ctx.project();
133
+ const item = await findStory(ctx.api, project, id);
134
+ const delivery = await deliveryOf(ctx.api, project, item.slug);
135
+ const runId = options.run ?? requireBuild(delivery).id;
136
+ let cursor = 0;
137
+ for (;;) {
138
+ const log = await ctx.api.request(storyPath(project, item.slug, '/delivery/checks/logs'), { query: { runId, cursor } });
139
+ if (log?.output)
140
+ process.stdout.write(log.output);
141
+ cursor = log?.cursor ?? cursor;
142
+ if (!options.follow)
143
+ break;
144
+ const current = await deliveryOf(ctx.api, project, item.slug);
145
+ if (!isActive(current.build) && !isActive(current.testRun))
146
+ break;
147
+ await sleep(3000);
148
+ }
149
+ }));
150
+ const qa = program.command('qa').description('QA of a story. QA runs in the Kodly sandbox, or locally where the project allows local QA.');
151
+ localQaCommands(qa, cliVersion);
152
+ qa
153
+ .command('send')
154
+ .argument('<story>', 'the story identifier or slug')
155
+ .option('--accept-failed-checks <reason>', 'send the build although its checks failed (needs your approval in the browser)')
156
+ .description('Send the current build to QA')
157
+ .action(run(async (id, options, command) => {
158
+ const ctx = buildContext(command, cliVersion);
159
+ const project = ctx.project();
160
+ const item = await findStory(ctx.api, project, id);
161
+ const delivery = await deliveryOf(ctx.api, project, item.slug);
162
+ const build = requireBuild(delivery);
163
+ const reason = options.acceptFailedChecks;
164
+ if (!reason && !delivery.workflow?.canSendToQa)
165
+ throw new CliError(`The build cannot go to QA now. ${blockedReasons(delivery, 'qa')}`.trim(), ExitCode.CONFLICT);
166
+ const version = reason
167
+ ? (await ctx.api.request(storyPath(project, item.slug, '/delivery/build-options')))?.version
168
+ : undefined;
169
+ const view = await ctx.api.request(storyPath(project, item.slug, '/delivery/handoffs'), {
170
+ method: 'POST', body: { destination: 'QA', buildId: build.id, reason, version },
171
+ });
172
+ emit(ctx.json, view, () => console.log(`Sent ${item.identifier ?? item.slug} to QA. Follow it: kodly watch ${item.identifier ?? item.slug}`));
173
+ }));
174
+ qa
175
+ .command('show')
176
+ .argument('<story>', 'the story identifier or slug')
177
+ .description('The latest QA run and its triage')
178
+ .action(run(async (id, _options, command) => {
179
+ const ctx = buildContext(command, cliVersion);
180
+ const project = ctx.project();
181
+ const item = await findStory(ctx.api, project, id);
182
+ const delivery = await deliveryOf(ctx.api, project, item.slug);
183
+ const triage = (await ctx.api.request(storyPath(project, item.slug, '/delivery/triage'))) ?? [];
184
+ emit(ctx.json, { testRun: delivery.testRun, testsCurrent: delivery.testsCurrent, triage }, () => {
185
+ const testRun = delivery.testRun;
186
+ if (!testRun) {
187
+ console.log('No QA run yet.');
188
+ return;
189
+ }
190
+ const where = isLocalQa(testRun.model) ? chalk.cyan(` local QA, run by ${testRun.requestedByEmail ?? '?'}`) : '';
191
+ console.log(`${chalk.bold('QA run')} ${short(testRun.id)}: ${testRun.state?.toLowerCase()} ${ago(testRun.createdAt)}${where}${delivery.testsCurrent ? '' : chalk.yellow(', outdated')}`);
192
+ if (results(testRun))
193
+ console.log(`Tests: ${results(testRun)}`);
194
+ if (testRun.summary)
195
+ console.log(`\n${testRun.summary}`);
196
+ if (triage.length) {
197
+ console.log(chalk.bold('\nTriage'));
198
+ table(triage.map((t) => [ago(t.createdAt), (t.category ?? '').toLowerCase(), t.actorEmail ?? '', t.reason ?? '']));
199
+ }
200
+ });
201
+ }));
202
+ qa
203
+ .command('triage')
204
+ .argument('<story>', 'the story identifier or slug')
205
+ .addOption(new Option('--category <category>', 'why QA failed').choices(TRIAGE).makeOptionMandatory())
206
+ .requiredOption('--reason <text>', 'the reason, for the next agent')
207
+ .description('Route a failed QA run (needs your approval in the browser)')
208
+ .action(run(async (id, options, command) => {
209
+ const ctx = buildContext(command, cliVersion);
210
+ const project = ctx.project();
211
+ const item = await findStory(ctx.api, project, id);
212
+ const testRun = requireTestRun(await deliveryOf(ctx.api, project, item.slug));
213
+ const triage = await ctx.api.request(storyPath(project, item.slug, '/delivery/triage'), {
214
+ method: 'POST', body: { requestId: requestId(), qaRunId: testRun.id, category: options.category, reason: options.reason },
215
+ });
216
+ emit(ctx.json, triage, () => console.log(`Routed the QA result of ${item.identifier ?? item.slug} as ${options.category.toLowerCase()}.`));
217
+ }));
218
+ };
@@ -0,0 +1,68 @@
1
+ import chalk from 'chalk';
2
+ import { Option } from 'commander';
3
+ import { spawnSync } from 'node:child_process';
4
+ import path from 'node:path';
5
+ import { checkoutOf } from '../core/checkout.js';
6
+ import { DEFAULT_API_URL } from '../core/config.js';
7
+ import { buildContext } from '../core/context.js';
8
+ import { CliError } from '../core/errors.js';
9
+ import { emit, run } from '../core/output.js';
10
+ import { checkoutStory } from './code.js';
11
+ /** The command that starts `kodly mcp` with this CLI, and the API when it is not production. */
12
+ export const mcpCommand = (apiUrl) => {
13
+ const self = process.argv[1] ? [process.execPath, path.resolve(process.argv[1])] : ['kodly'];
14
+ return [...self, ...(apiUrl === DEFAULT_API_URL ? [] : ['--api', apiUrl]), 'mcp'];
15
+ };
16
+ export const harnessCommands = (program, cliVersion) => {
17
+ const harness = program.command('harness').description('Connect your local agent tool to Kodly');
18
+ harness
19
+ .command('install')
20
+ .addOption(new Option('--tool <tool>', 'the agent tool').choices(['claude', 'other']).default('claude'))
21
+ .addOption(new Option('--scope <scope>', 'the Claude Code scope').choices(['local', 'project', 'user']).default('user'))
22
+ .description('Register the Kodly MCP server with Claude Code, or print the setting for another tool')
23
+ .action(run(async (options, command) => {
24
+ const ctx = buildContext(command, cliVersion);
25
+ const [executable, ...args] = mcpCommand(ctx.apiUrl);
26
+ if (options.tool === 'claude') {
27
+ const result = spawnSync('claude', ['mcp', 'add', '--scope', options.scope, 'kodly', '--', executable, ...args], { stdio: 'inherit' });
28
+ if (result.error)
29
+ throw new CliError('Claude Code is not on the PATH. Install it, or use --tool other.');
30
+ if (result.status !== 0)
31
+ throw new CliError('claude mcp add failed. See its message above.');
32
+ emit(ctx.json, { tool: 'claude', scope: options.scope }, () => console.log(chalk.green('Claude Code can now use Kodly. In a checkout, run: /mcp__kodly__implement <story>')));
33
+ return;
34
+ }
35
+ const setting = { mcpServers: { kodly: { command: executable, args } } };
36
+ emit(ctx.json, setting, () => {
37
+ console.log('Add this MCP server to your agent tool:');
38
+ console.log(JSON.stringify(setting, null, 2));
39
+ });
40
+ }));
41
+ program
42
+ .command('implement')
43
+ .argument('<story>', 'the story identifier or slug')
44
+ .option('--dir <path>', 'the folder for the checkout')
45
+ .description('Prepare a story for your local agent: check it out, then tell the agent to implement it')
46
+ .action(run(async (id, options, command) => {
47
+ const ctx = buildContext(command, cliVersion);
48
+ let root;
49
+ let identifier;
50
+ const existing = checkoutOf(id, options.dir);
51
+ if (existing) {
52
+ root = existing.root;
53
+ identifier = existing.context.identifier ?? existing.context.story;
54
+ }
55
+ else {
56
+ const created = await checkoutStory(ctx, id, options.dir);
57
+ root = created.root;
58
+ identifier = created.item.identifier ?? created.item.slug;
59
+ }
60
+ emit(ctx.json, { root, prompt: `/mcp__kodly__implement ${identifier}` }, () => {
61
+ console.log(`The code of ${identifier} is in ${root}.`);
62
+ console.log('Next:');
63
+ console.log(` cd ${root}`);
64
+ console.log(` claude "/mcp__kodly__implement ${identifier}"`);
65
+ console.log(chalk.dim('Run "kodly harness install" once, so that Claude Code knows the Kodly tools.'));
66
+ });
67
+ }));
68
+ };