@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,64 @@
|
|
|
1
|
+
import { Api } from './api.js';
|
|
2
|
+
import { findCheckout } from './checkout.js';
|
|
3
|
+
import { browserConfirmer } from './confirm.js';
|
|
4
|
+
import { resolveApiUrl, settings, webUrlFor } from './config.js';
|
|
5
|
+
import { readToken } from './credentials.js';
|
|
6
|
+
import { CliError, ExitCode } from './errors.js';
|
|
7
|
+
/** The checkout that holds the current folder, or undefined outside a checkout. */
|
|
8
|
+
const currentCheckout = () => {
|
|
9
|
+
try {
|
|
10
|
+
return findCheckout().context;
|
|
11
|
+
}
|
|
12
|
+
catch (error) {
|
|
13
|
+
if (error instanceof CliError)
|
|
14
|
+
return undefined;
|
|
15
|
+
throw error;
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* The value that the checkout names. A flag or a variable that names a different value stops the
|
|
20
|
+
* command: it never wins silently. `same` compares two values (the API URLs need a normal form).
|
|
21
|
+
*/
|
|
22
|
+
const fromCheckout = (kind, value, flag, given, variable, same = (a, b) => a === b) => {
|
|
23
|
+
const explicit = given || process.env[variable];
|
|
24
|
+
if (explicit && !same(explicit, value)) {
|
|
25
|
+
const source = given ? flag : variable;
|
|
26
|
+
const current = value ? `${kind} ${value}` : `your default ${kind}`;
|
|
27
|
+
throw new CliError(`This folder is a checkout of ${current}, but ${source} names ${explicit}. Remove ${source}, or run the command outside the checkout.`, ExitCode.USAGE);
|
|
28
|
+
}
|
|
29
|
+
return value;
|
|
30
|
+
};
|
|
31
|
+
export const buildContext = (command, cliVersion, confirmer) => {
|
|
32
|
+
const options = command.optsWithGlobals();
|
|
33
|
+
// Inside a checkout, the checkout names the API, the organisation and the project. Every command
|
|
34
|
+
// then acts on the same story code as kodly push. The saved defaults do not apply there.
|
|
35
|
+
const checkout = currentCheckout();
|
|
36
|
+
const apiUrl = checkout ? fromCheckout('API', checkout.api, '--api', options.api, 'KODLY_API_URL', (a, b) => resolveApiUrl(a) === b)
|
|
37
|
+
: resolveApiUrl(options.api);
|
|
38
|
+
const stored = readToken(apiUrl);
|
|
39
|
+
const openBrowser = options.browser !== false;
|
|
40
|
+
const orgSlug = checkout ? fromCheckout('organisation', checkout.org, '--org', options.org, 'KODLY_ORG')
|
|
41
|
+
: options.org || process.env.KODLY_ORG || settings().get('orgSlug');
|
|
42
|
+
const projectSlug = checkout ? fromCheckout('project', checkout.project, '--project', options.project, 'KODLY_PROJECT')
|
|
43
|
+
: options.project || process.env.KODLY_PROJECT || settings().get('projectSlug');
|
|
44
|
+
const api = new Api({ apiUrl, token: stored?.token, orgSlug, cliVersion }, confirmer ?? browserConfirmer({ openBrowser }));
|
|
45
|
+
return {
|
|
46
|
+
api,
|
|
47
|
+
apiUrl,
|
|
48
|
+
webUrl: webUrlFor(apiUrl),
|
|
49
|
+
json: options.json === true,
|
|
50
|
+
openBrowser,
|
|
51
|
+
tokenSource: stored?.source,
|
|
52
|
+
requireLogin() {
|
|
53
|
+
if (!stored)
|
|
54
|
+
throw new CliError(`You are not signed in to ${apiUrl}. Run "kodly login" first.`);
|
|
55
|
+
},
|
|
56
|
+
project() {
|
|
57
|
+
if (!stored)
|
|
58
|
+
throw new CliError(`You are not signed in to ${apiUrl}. Run "kodly login" first.`);
|
|
59
|
+
if (!projectSlug)
|
|
60
|
+
throw new CliError('No project is chosen. Run "kodly project list", then "kodly project use <slug>".', ExitCode.USAGE);
|
|
61
|
+
return projectSlug;
|
|
62
|
+
},
|
|
63
|
+
};
|
|
64
|
+
};
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import Conf from 'conf';
|
|
2
|
+
import { configDir } from './config.js';
|
|
3
|
+
import { keychainEntry } from './keychain.js';
|
|
4
|
+
const SERVICE = 'kodly-cli';
|
|
5
|
+
let fallback;
|
|
6
|
+
const file = () => {
|
|
7
|
+
fallback ?? (fallback = new Conf({ projectName: 'kodly', cwd: configDir(), configName: 'credentials', configFileMode: 0o600 }));
|
|
8
|
+
return fallback;
|
|
9
|
+
};
|
|
10
|
+
/**
|
|
11
|
+
* The CLI token of one API. It goes in the OS keychain (fixes S-4 of the security review). When
|
|
12
|
+
* the keychain is not available, for example on a server with no keyring service, it goes in a
|
|
13
|
+
* file that only the user can read, with a warning. `KODLY_CREDENTIALS=file` always uses the
|
|
14
|
+
* file, for a container. `KODLY_TOKEN` overrides both, for scripts.
|
|
15
|
+
*/
|
|
16
|
+
const keychain = (apiUrl) => {
|
|
17
|
+
if (process.env.KODLY_CREDENTIALS === 'file')
|
|
18
|
+
throw new Error('The keychain is off.');
|
|
19
|
+
return keychainEntry(SERVICE, apiUrl);
|
|
20
|
+
};
|
|
21
|
+
export const readToken = (apiUrl) => {
|
|
22
|
+
if (process.env.KODLY_TOKEN)
|
|
23
|
+
return { token: process.env.KODLY_TOKEN, source: 'env' };
|
|
24
|
+
try {
|
|
25
|
+
const token = keychain(apiUrl).getPassword();
|
|
26
|
+
if (token)
|
|
27
|
+
return { token, source: 'keychain' };
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
// No keychain on this machine. Try the file.
|
|
31
|
+
}
|
|
32
|
+
const token = file().get('tokens')?.[apiUrl];
|
|
33
|
+
return token ? { token, source: 'file' } : undefined;
|
|
34
|
+
};
|
|
35
|
+
/** Saves the token. `path` is set when the keychain was not available and the token went to a file. */
|
|
36
|
+
export const saveToken = (apiUrl, token) => {
|
|
37
|
+
try {
|
|
38
|
+
keychain(apiUrl).setPassword(token);
|
|
39
|
+
removeFileToken(apiUrl);
|
|
40
|
+
return { source: 'keychain' };
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
file().set('tokens', { ...(file().get('tokens') ?? {}), [apiUrl]: token });
|
|
44
|
+
return { source: 'file', path: file().path };
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
export const deleteToken = (apiUrl) => {
|
|
48
|
+
try {
|
|
49
|
+
keychain(apiUrl).deletePassword();
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
// No keychain, or no entry.
|
|
53
|
+
}
|
|
54
|
+
removeFileToken(apiUrl);
|
|
55
|
+
};
|
|
56
|
+
const removeFileToken = (apiUrl) => {
|
|
57
|
+
const tokens = { ...(file().get('tokens') ?? {}) };
|
|
58
|
+
if (!(apiUrl in tokens))
|
|
59
|
+
return;
|
|
60
|
+
delete tokens[apiUrl];
|
|
61
|
+
file().set('tokens', tokens);
|
|
62
|
+
};
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { hostname } from 'node:os';
|
|
2
|
+
import { ApiError, CliError, ExitCode } from './errors.js';
|
|
3
|
+
const GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:device_code';
|
|
4
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
5
|
+
export const startDeviceLogin = (api, cliVersion) => api.request('/auth/cli/device/code', {
|
|
6
|
+
method: 'POST',
|
|
7
|
+
anonymous: true,
|
|
8
|
+
raw: true,
|
|
9
|
+
body: { clientName: 'kodly-cli', host: hostname(), cliVersion },
|
|
10
|
+
});
|
|
11
|
+
/**
|
|
12
|
+
* Polls the token route until the person approves or denies the login in the browser (RFC 8628,
|
|
13
|
+
* section 3.5). `slow_down` makes the interval 5 seconds longer.
|
|
14
|
+
*/
|
|
15
|
+
export const waitForDeviceToken = async (api, code, secondMs = 1000) => {
|
|
16
|
+
let interval = Math.max(1, code.interval);
|
|
17
|
+
const deadline = Date.now() + code.expires_in * 1000;
|
|
18
|
+
while (Date.now() < deadline) {
|
|
19
|
+
await sleep(interval * secondMs);
|
|
20
|
+
try {
|
|
21
|
+
return await api.request('/auth/cli/device/token', {
|
|
22
|
+
method: 'POST',
|
|
23
|
+
anonymous: true,
|
|
24
|
+
raw: true,
|
|
25
|
+
body: { device_code: code.device_code, grant_type: GRANT_TYPE },
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
catch (error) {
|
|
29
|
+
const reason = error instanceof ApiError && error.status === 400 ? error.data?.error : undefined;
|
|
30
|
+
if (reason === 'authorization_pending')
|
|
31
|
+
continue;
|
|
32
|
+
if (reason === 'slow_down') {
|
|
33
|
+
interval += 5;
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
36
|
+
if (reason === 'access_denied')
|
|
37
|
+
throw new CliError('The login was denied in the browser.', ExitCode.NOT_APPROVED);
|
|
38
|
+
if (reason === 'expired_token')
|
|
39
|
+
break;
|
|
40
|
+
throw error;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
throw new CliError('The login code expired. Run "kodly login" again.', ExitCode.NOT_APPROVED);
|
|
44
|
+
};
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/** Exit codes of the kodly CLI. Scripts and local agents read them. */
|
|
2
|
+
export const ExitCode = {
|
|
3
|
+
OK: 0,
|
|
4
|
+
ERROR: 1,
|
|
5
|
+
USAGE: 2,
|
|
6
|
+
/** A person denied a login or a confirmation, or it expired. */
|
|
7
|
+
NOT_APPROVED: 3,
|
|
8
|
+
/** The server refused the call because the state changed. Run the next step it names, then try again. */
|
|
9
|
+
CONFLICT: 4,
|
|
10
|
+
};
|
|
11
|
+
/** An error that the CLI shows as one line of text, with its exit code. */
|
|
12
|
+
export class CliError extends Error {
|
|
13
|
+
constructor(message, exitCode = ExitCode.ERROR) {
|
|
14
|
+
super(message);
|
|
15
|
+
this.exitCode = exitCode;
|
|
16
|
+
this.name = 'CliError';
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
/** A refused call to kodly-api. `message` is the text that the server sent, else a general text. */
|
|
20
|
+
export class ApiError extends CliError {
|
|
21
|
+
constructor(message, status, data) {
|
|
22
|
+
super(message, status === 409 ? ExitCode.CONFLICT : ExitCode.ERROR);
|
|
23
|
+
this.status = status;
|
|
24
|
+
this.data = data;
|
|
25
|
+
this.name = 'ApiError';
|
|
26
|
+
}
|
|
27
|
+
/** The `code` field of the error data, for example `auth.cli.confirmation.required`. */
|
|
28
|
+
get code() {
|
|
29
|
+
const code = this.data?.code;
|
|
30
|
+
return typeof code === 'string' ? code : undefined;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import chalk from 'chalk';
|
|
2
|
+
/** Prints rows as aligned columns, with the header only when there are rows. The last column is not padded. */
|
|
3
|
+
export const table = (rows, header) => {
|
|
4
|
+
if (rows.length === 0)
|
|
5
|
+
return;
|
|
6
|
+
const all = header ? [header, ...rows] : rows;
|
|
7
|
+
const widths = all[0].map((_, column) => Math.max(...all.map((row) => visible(row[column] ?? '').length)));
|
|
8
|
+
const line = (row) => row.map((cell, column) => (column === row.length - 1 ? cell : cell + ' '.repeat(widths[column] - visible(cell).length))).join(' ');
|
|
9
|
+
if (header)
|
|
10
|
+
console.log(chalk.dim(line(header)));
|
|
11
|
+
for (const row of rows)
|
|
12
|
+
console.log(line(row));
|
|
13
|
+
};
|
|
14
|
+
const visible = (text) => text.replace(/\u001b\[[0-9;]*m/g, '');
|
|
15
|
+
/** A date as "3 min ago" or "in 2 h", else an empty string. */
|
|
16
|
+
export const ago = (value) => {
|
|
17
|
+
if (value === undefined || value === null || value === '')
|
|
18
|
+
return '';
|
|
19
|
+
const time = typeof value === 'number' ? value : new Date(value).getTime();
|
|
20
|
+
if (Number.isNaN(time))
|
|
21
|
+
return '';
|
|
22
|
+
const seconds = Math.round((Date.now() - time) / 1000);
|
|
23
|
+
const future = seconds < 0;
|
|
24
|
+
const s = Math.abs(seconds);
|
|
25
|
+
const text = s < 60 ? `${s} s` : s < 3600 ? `${Math.round(s / 60)} min` : s < 86400 ? `${Math.round(s / 3600)} h` : `${Math.round(s / 86400)} d`;
|
|
26
|
+
return future ? `in ${text}` : `${text} ago`;
|
|
27
|
+
};
|
|
28
|
+
/** "yes" in green or "no" in dim text. */
|
|
29
|
+
export const flag = (value) => (value ? chalk.green('yes') : chalk.dim('no'));
|
|
30
|
+
/** The path of a story route: /workspace/{project}/requirements/{story}{suffix}. */
|
|
31
|
+
export const storyPath = (project, story, suffix = '') => `/workspace/${encodeURIComponent(project)}/requirements/${encodeURIComponent(story)}${suffix}`;
|
|
32
|
+
export const projectPath = (project, suffix = '') => `/workspace/${encodeURIComponent(project)}${suffix}`;
|
package/dist/core/git.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import { promisify } from 'node:util';
|
|
3
|
+
import { CliError } from './errors.js';
|
|
4
|
+
const run = promisify(execFile);
|
|
5
|
+
/** Runs git in a directory and gives back its stdout. A failure shows the stderr of git. */
|
|
6
|
+
export const git = async (cwd, args, input) => {
|
|
7
|
+
try {
|
|
8
|
+
const child = run('git', args, { cwd, maxBuffer: 64 * 1024 * 1024, env: { ...process.env, GIT_TERMINAL_PROMPT: '0' } });
|
|
9
|
+
if (input !== undefined)
|
|
10
|
+
child.child.stdin?.end(input);
|
|
11
|
+
const { stdout } = await child;
|
|
12
|
+
return stdout;
|
|
13
|
+
}
|
|
14
|
+
catch (error) {
|
|
15
|
+
const e = error;
|
|
16
|
+
if (e.code === 'ENOENT')
|
|
17
|
+
throw new CliError('git is not installed, or it is not on the PATH.');
|
|
18
|
+
throw new CliError(`git ${args[0]} failed: ${(e.stderr || e.message).trim()}`);
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
/** The output of git, trimmed, or null when the command fails. For questions such as "does this ref exist". */
|
|
22
|
+
export const gitTry = async (cwd, args) => {
|
|
23
|
+
try {
|
|
24
|
+
return (await git(cwd, args)).trim();
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { createRequire } from 'node:module';
|
|
2
|
+
/**
|
|
3
|
+
* Loads the native keychain module on the first call only. Commands that need no token, such as
|
|
4
|
+
* `kodly scaffold` on a server image, then never load it. Tests mock this module.
|
|
5
|
+
*/
|
|
6
|
+
export const keychainEntry = (service, account) => {
|
|
7
|
+
const { Entry: KeychainEntry } = createRequire(import.meta.url)('@napi-rs/keyring');
|
|
8
|
+
return new KeychainEntry(service, account);
|
|
9
|
+
};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
const Membership = z.object({
|
|
3
|
+
orgSlug: z.string(),
|
|
4
|
+
orgName: z.string().nullish(),
|
|
5
|
+
roleSlug: z.string().nullish(),
|
|
6
|
+
roleName: z.string().nullish(),
|
|
7
|
+
status: z.string().nullish(),
|
|
8
|
+
});
|
|
9
|
+
/** The active organisations of the user (`GET /me/memberships`), checked against the expected shape. */
|
|
10
|
+
export const fetchMemberships = async (api) => z.array(Membership).parse((await api.request('/me/memberships')) ?? []);
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import chalk from 'chalk';
|
|
2
|
+
import { ApiError, CliError, ExitCode } from './errors.js';
|
|
3
|
+
/** Prints the JSON form in `--json` mode, else the text form. */
|
|
4
|
+
export const emit = (json, data, text) => {
|
|
5
|
+
if (json)
|
|
6
|
+
process.stdout.write(JSON.stringify(data, null, 2) + '\n');
|
|
7
|
+
else
|
|
8
|
+
text();
|
|
9
|
+
};
|
|
10
|
+
/**
|
|
11
|
+
* Wraps a command action: an error becomes one line on stderr and an exit code, with no stack
|
|
12
|
+
* trace (security review F-8: no raw server internals). In `--json` mode the error also goes to
|
|
13
|
+
* stdout as `{"error": ...}`, so a script or an agent can read it.
|
|
14
|
+
*/
|
|
15
|
+
export const run = (action) => async (...args) => {
|
|
16
|
+
try {
|
|
17
|
+
await action(...args);
|
|
18
|
+
}
|
|
19
|
+
catch (error) {
|
|
20
|
+
const command = args[args.length - 1];
|
|
21
|
+
const json = command?.optsWithGlobals?.().json === true;
|
|
22
|
+
const known = error instanceof CliError;
|
|
23
|
+
const message = known ? error.message : `Unexpected error: ${error?.message ?? String(error)}`;
|
|
24
|
+
if (json) {
|
|
25
|
+
const detail = error instanceof ApiError ? { status: error.status, code: error.code } : {};
|
|
26
|
+
process.stdout.write(JSON.stringify({ error: { message, ...detail } }, null, 2) + '\n');
|
|
27
|
+
}
|
|
28
|
+
process.stderr.write(chalk.red(message) + '\n');
|
|
29
|
+
process.exitCode = known ? error.exitCode : ExitCode.ERROR;
|
|
30
|
+
}
|
|
31
|
+
};
|
|
@@ -0,0 +1,47 @@
|
|
|
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 readline from 'node:readline/promises';
|
|
6
|
+
import { CliError, ExitCode } from './errors.js';
|
|
7
|
+
/** True when a person can answer: both stdin and stdout are a terminal. */
|
|
8
|
+
export const interactive = () => !!process.stdin.isTTY && !!process.stdout.isTTY;
|
|
9
|
+
/**
|
|
10
|
+
* Asks a y/N question on the terminal. `--yes` answers yes. With no terminal and no `--yes`, the
|
|
11
|
+
* command stops, so a script never waits for an answer. This is a local question only: a step that
|
|
12
|
+
* needs a person still needs the browser confirmation.
|
|
13
|
+
*/
|
|
14
|
+
export const confirm = async (question, yes) => {
|
|
15
|
+
if (yes)
|
|
16
|
+
return true;
|
|
17
|
+
if (!interactive())
|
|
18
|
+
throw new CliError(`${question} Add --yes to answer yes when no terminal is open.`, ExitCode.USAGE);
|
|
19
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
|
|
20
|
+
try {
|
|
21
|
+
return /^y(es)?$/i.test((await rl.question(`${question} [y/N] `)).trim());
|
|
22
|
+
}
|
|
23
|
+
finally {
|
|
24
|
+
rl.close();
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* Opens `text` in $VISUAL or $EDITOR (default vi) and gives the saved text. The file is in a new
|
|
29
|
+
* folder that only the user can read, and the folder is removed afterwards.
|
|
30
|
+
*/
|
|
31
|
+
export const editText = (text, name) => {
|
|
32
|
+
if (!interactive())
|
|
33
|
+
throw new CliError('An editor needs a terminal. Give the file with -f instead.', ExitCode.USAGE);
|
|
34
|
+
const dir = fs.mkdtempSync(path.join(tmpdir(), 'kodly-edit-'));
|
|
35
|
+
const file = path.join(dir, name);
|
|
36
|
+
try {
|
|
37
|
+
fs.writeFileSync(file, text, { mode: 0o600 });
|
|
38
|
+
const editor = process.env.VISUAL || process.env.EDITOR || 'vi';
|
|
39
|
+
const result = spawnSync(`${editor} "${file}"`, { stdio: 'inherit', shell: true });
|
|
40
|
+
if (result.status !== 0)
|
|
41
|
+
throw new CliError(`The editor (${editor}) ended with an error. Nothing was saved.`, ExitCode.USAGE);
|
|
42
|
+
return fs.readFileSync(file, 'utf8');
|
|
43
|
+
}
|
|
44
|
+
finally {
|
|
45
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
46
|
+
}
|
|
47
|
+
};
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { git, gitTry } from './git.js';
|
|
3
|
+
export const MAX_FILE_BYTES = 8 * 1024 * 1024;
|
|
4
|
+
export const MAX_COMMITS = 500;
|
|
5
|
+
/** Paths that usually hold a secret. A push with one of them stops (security review S-3). */
|
|
6
|
+
const SECRET = [/(^|\/)\.env(\.[^/]*)?$/, /\.pem$/, /\.key$/, /\.p12$/, /\.pfx$/, /(^|\/)id_(rsa|dsa|ecdsa|ed25519)$/, /(^|\/)\.npmrc$/, /(^|\/)\.netrc$/];
|
|
7
|
+
const SECRET_OK = /(^|\/)\.env\.(example|sample|template)$/;
|
|
8
|
+
const PLATFORM = /^\.kodly-(build|evidence|tests)(\/|$)|^\.env\.sandbox$/;
|
|
9
|
+
/** The git blob id of some bytes, as `git hash-object` gives it. */
|
|
10
|
+
export const blobId = (bytes) => createHash('sha1').update(`blob ${bytes.length}\0`).update(bytes).digest('hex');
|
|
11
|
+
/**
|
|
12
|
+
* Checks the commits of one codebase before a push. kodly-api checks the same rules again, but a
|
|
13
|
+
* problem found here costs no upload. `generated` maps each generated path that git must not hold
|
|
14
|
+
* to the blob id of its generated bytes.
|
|
15
|
+
*/
|
|
16
|
+
export const checkPush = async (dir, codebase, generated) => {
|
|
17
|
+
const problems = [];
|
|
18
|
+
const dirty = (await git(dir, ['status', '--porcelain', '--untracked-files=no'])).trim();
|
|
19
|
+
if (dirty)
|
|
20
|
+
problems.push(`${codebase}: you have changes that are not committed. Commit them first.`);
|
|
21
|
+
if ((await gitTry(dir, ['merge-base', '--is-ancestor', 'origin/main', 'HEAD'])) === null) {
|
|
22
|
+
problems.push(`${codebase}: your commits do not build on the story code. Run kodly pull, then rebase your commits.`);
|
|
23
|
+
return { head: null, commits: 0, problems };
|
|
24
|
+
}
|
|
25
|
+
const commits = Number((await git(dir, ['rev-list', '--count', 'origin/main..HEAD'])).trim());
|
|
26
|
+
if (commits === 0)
|
|
27
|
+
return { head: null, commits: 0, problems };
|
|
28
|
+
if (commits > MAX_COMMITS)
|
|
29
|
+
problems.push(`${codebase}: a push can bring ${MAX_COMMITS} commits at most. Squash some of them.`);
|
|
30
|
+
if ((await git(dir, ['rev-list', '--merges', 'origin/main..HEAD'])).trim()) {
|
|
31
|
+
problems.push(`${codebase}: your commits include a merge. Rebase them on the story code instead.`);
|
|
32
|
+
}
|
|
33
|
+
if (/^Kodly-[A-Za-z-]+:/m.test(await git(dir, ['log', '--format=%B', 'origin/main..HEAD']))) {
|
|
34
|
+
problems.push(`${codebase}: a commit message has a Kodly- trailer. Only Kodly writes these.`);
|
|
35
|
+
}
|
|
36
|
+
// The secret rule reads only the paths that the commits add or change. The story code can hold a
|
|
37
|
+
// file such as a scaffolded .env.dev, and that file is not part of this push.
|
|
38
|
+
const changed = new Set((await git(dir, ['diff', '--name-only', '-z', '--no-renames', '--diff-filter=AM', 'origin/main', 'HEAD']))
|
|
39
|
+
.split('\0').filter(Boolean));
|
|
40
|
+
for (const line of (await git(dir, ['ls-tree', '-r', '-l', '-z', 'HEAD'])).split('\0').filter(Boolean)) {
|
|
41
|
+
const [meta, path] = line.split('\t');
|
|
42
|
+
const [mode, , sha, size] = meta.split(/\s+/);
|
|
43
|
+
if (mode === '120000')
|
|
44
|
+
problems.push(`${codebase}: ${path} is a symbolic link. Kodly takes plain files only.`);
|
|
45
|
+
else if (mode === '160000')
|
|
46
|
+
problems.push(`${codebase}: ${path} is a submodule. Kodly takes plain files only.`);
|
|
47
|
+
else if (Number(size) > MAX_FILE_BYTES)
|
|
48
|
+
problems.push(`${codebase}: ${path} is larger than 8 MiB.`);
|
|
49
|
+
if (PLATFORM.test(path))
|
|
50
|
+
problems.push(`${codebase}: ${path} is a Kodly platform path. Remove it from git.`);
|
|
51
|
+
if (changed.has(path) && SECRET.some((pattern) => pattern.test(path)) && !SECRET_OK.test(path)) {
|
|
52
|
+
problems.push(`${codebase}: ${path} looks like a secret. Remove it from git, and keep secrets in the Kodly project settings.`);
|
|
53
|
+
}
|
|
54
|
+
if (generated[path] && generated[path] === sha) {
|
|
55
|
+
problems.push(`${codebase}: ${path} is a generated file. Remove it from git; kodly checkout writes it.`);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
const head = (await git(dir, ['rev-parse', 'HEAD'])).trim();
|
|
59
|
+
return { head, commits, problems };
|
|
60
|
+
};
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import YAML from 'yaml';
|
|
2
|
+
import { CliError, ExitCode } from './errors.js';
|
|
3
|
+
const HEADER = /^# kodly-story: (\S+) version=(\d+) fingerprint=(\S+)\s*$/m;
|
|
4
|
+
const ALIASES = { codebase: 'targetProjectSlug', criteria: 'acceptanceCriteria', brief: 'livingBrief', start: 'startDate', end: 'endDate' };
|
|
5
|
+
const SCOPE_KEYS = ['title', 'kind', 'goal', 'summary', 'acceptanceCriteria', 'targetProjectSlug', 'livingBrief'];
|
|
6
|
+
const CREATE_KEYS = [...SCOPE_KEYS, 'startDate', 'endDate'];
|
|
7
|
+
const header = (h) => `# kodly-story: ${h.story} version=${h.version} fingerprint=${h.fingerprint}\n`;
|
|
8
|
+
const HELP = [
|
|
9
|
+
'# Lines that start with # are comments. Save and close the editor to continue; an empty file stops.',
|
|
10
|
+
'# title, goal and at least one acceptance criterion are needed. kind is STORY or EPIC.',
|
|
11
|
+
'# targetProjectSlug (or codebase) is optional: the codebase slug, for example PRJ00000002.',
|
|
12
|
+
].join('\n');
|
|
13
|
+
/** The text that `kodly story create` opens in the editor. */
|
|
14
|
+
export const CREATE_TEMPLATE = `${HELP}
|
|
15
|
+
# startDate and endDate are optional dates, for example 2026-11-16.
|
|
16
|
+
title: ""
|
|
17
|
+
kind: STORY
|
|
18
|
+
goal: ""
|
|
19
|
+
summary: ""
|
|
20
|
+
acceptanceCriteria:
|
|
21
|
+
- ""
|
|
22
|
+
# targetProjectSlug: PRJ00000002
|
|
23
|
+
# startDate: 2026-11-16
|
|
24
|
+
# endDate: 2026-11-22
|
|
25
|
+
`;
|
|
26
|
+
/** The text of a story for `kodly story edit`: the version header, help, and the scope as YAML. */
|
|
27
|
+
export const storyYaml = (h, story) => {
|
|
28
|
+
const ordered = {};
|
|
29
|
+
for (const key of SCOPE_KEYS) {
|
|
30
|
+
const value = story[key];
|
|
31
|
+
if (value !== undefined && value !== null)
|
|
32
|
+
ordered[key] = value;
|
|
33
|
+
}
|
|
34
|
+
return `${header(h)}${HELP}\n${YAML.stringify(ordered, { lineWidth: 0 })}`;
|
|
35
|
+
};
|
|
36
|
+
/** True when the text has only comments and space, so the person stopped the edit. */
|
|
37
|
+
export const isEmpty = (text) => text.split('\n').every((line) => !line.trim() || line.trim().startsWith('#'));
|
|
38
|
+
/** Reads a story file (YAML or JSON) and its version header. Unknown keys stop the command, so a typo is never lost. */
|
|
39
|
+
export const parseStory = (text, source, allowed) => {
|
|
40
|
+
let parsed;
|
|
41
|
+
try {
|
|
42
|
+
parsed = YAML.parse(text);
|
|
43
|
+
}
|
|
44
|
+
catch (e) {
|
|
45
|
+
throw new CliError(`${source} is not YAML or JSON that kodly can read: ${e.message}`, ExitCode.USAGE);
|
|
46
|
+
}
|
|
47
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
48
|
+
throw new CliError(`${source} must hold the story fields.`, ExitCode.USAGE);
|
|
49
|
+
const keys = allowed === 'create' ? CREATE_KEYS : SCOPE_KEYS;
|
|
50
|
+
const values = {};
|
|
51
|
+
for (const [raw, value] of Object.entries(parsed)) {
|
|
52
|
+
const key = ALIASES[raw] ?? raw;
|
|
53
|
+
if (!keys.includes(key))
|
|
54
|
+
throw new CliError(`${source}: "${raw}" is not a story field. Use ${keys.join(', ')}.`, ExitCode.USAGE);
|
|
55
|
+
values[key] = value instanceof Date ? value.toISOString().slice(0, 10) : value;
|
|
56
|
+
}
|
|
57
|
+
const match = HEADER.exec(text);
|
|
58
|
+
return { header: match ? { story: match[1], version: Number(match[2]), fingerprint: match[3] } : undefined, values };
|
|
59
|
+
};
|
|
60
|
+
const text = (values, key, source, required) => {
|
|
61
|
+
const value = values[key];
|
|
62
|
+
if (value === undefined || value === null) {
|
|
63
|
+
if (required)
|
|
64
|
+
throw new CliError(`${source}: "${key}" is needed.`, ExitCode.USAGE);
|
|
65
|
+
return '';
|
|
66
|
+
}
|
|
67
|
+
if (typeof value !== 'string')
|
|
68
|
+
throw new CliError(`${source}: "${key}" must be text.`, ExitCode.USAGE);
|
|
69
|
+
if (required && !value.trim())
|
|
70
|
+
throw new CliError(`${source}: "${key}" is empty.`, ExitCode.USAGE);
|
|
71
|
+
return value;
|
|
72
|
+
};
|
|
73
|
+
const criteria = (values, source) => {
|
|
74
|
+
const value = values.acceptanceCriteria;
|
|
75
|
+
if (!Array.isArray(value) || value.length === 0 || value.some((c) => typeof c !== 'string' || !c.trim())) {
|
|
76
|
+
throw new CliError(`${source}: "acceptanceCriteria" must be a list with at least one criterion, and no empty item.`, ExitCode.USAGE);
|
|
77
|
+
}
|
|
78
|
+
return value;
|
|
79
|
+
};
|
|
80
|
+
const kind = (values, source) => {
|
|
81
|
+
const value = values.kind ?? 'STORY';
|
|
82
|
+
if (value !== 'STORY' && value !== 'EPIC')
|
|
83
|
+
throw new CliError(`${source}: "kind" must be STORY or EPIC.`, ExitCode.USAGE);
|
|
84
|
+
return value;
|
|
85
|
+
};
|
|
86
|
+
/** The fields of a new story, checked here so that a simple mistake costs no request. */
|
|
87
|
+
export const toFields = (values, source) => {
|
|
88
|
+
const fields = {
|
|
89
|
+
title: text(values, 'title', source, true),
|
|
90
|
+
goal: text(values, 'goal', source, true),
|
|
91
|
+
acceptanceCriteria: criteria(values, source),
|
|
92
|
+
kind: kind(values, source),
|
|
93
|
+
};
|
|
94
|
+
const summary = text(values, 'summary', source, false);
|
|
95
|
+
if (summary)
|
|
96
|
+
fields.summary = summary;
|
|
97
|
+
const codebase = text(values, 'targetProjectSlug', source, false);
|
|
98
|
+
if (codebase)
|
|
99
|
+
fields.targetProjectSlug = codebase;
|
|
100
|
+
if (values.livingBrief !== undefined)
|
|
101
|
+
fields.livingBrief = values.livingBrief;
|
|
102
|
+
for (const key of ['startDate', 'endDate']) {
|
|
103
|
+
const date = text(values, key, source, false);
|
|
104
|
+
if (date && !/^\d{4}-\d{2}-\d{2}$/.test(date))
|
|
105
|
+
throw new CliError(`${source}: "${key}" must be a date such as 2026-11-16.`, ExitCode.USAGE);
|
|
106
|
+
if (date)
|
|
107
|
+
fields[key] = date;
|
|
108
|
+
}
|
|
109
|
+
return fields;
|
|
110
|
+
};
|
|
111
|
+
/** The complete scope of an edit. A field that the file leaves out keeps no value, as in the API. */
|
|
112
|
+
export const toDocument = (values, source) => ({
|
|
113
|
+
title: text(values, 'title', source, true),
|
|
114
|
+
goal: text(values, 'goal', source, false),
|
|
115
|
+
summary: text(values, 'summary', source, false),
|
|
116
|
+
acceptanceCriteria: criteria(values, source),
|
|
117
|
+
kind: kind(values, source),
|
|
118
|
+
targetProjectSlug: text(values, 'targetProjectSlug', source, false),
|
|
119
|
+
...(values.livingBrief === undefined || values.livingBrief === null ? {} : { livingBrief: values.livingBrief }),
|
|
120
|
+
});
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { CliError, ExitCode } from './errors.js';
|
|
3
|
+
import { projectPath, storyPath } from './format.js';
|
|
4
|
+
export const ACTIVE_STATES = new Set(['QUEUED', 'STARTING', 'RUNNING']);
|
|
5
|
+
export const isActive = (run) => !!run && ACTIVE_STATES.has(run.state ?? '');
|
|
6
|
+
/** An idempotency key for one command call. The server returns the same result for a repeat. */
|
|
7
|
+
export const requestId = () => randomUUID();
|
|
8
|
+
/**
|
|
9
|
+
* Finds a story by its identifier (for example KOD-12) or its slug. The other story routes need
|
|
10
|
+
* the slug, so each command resolves it first.
|
|
11
|
+
*/
|
|
12
|
+
export const findStory = async (api, project, story) => {
|
|
13
|
+
const backlog = await api.request(projectPath(project, '/backlog'), {
|
|
14
|
+
query: { requirement: story, includeClosed: true },
|
|
15
|
+
});
|
|
16
|
+
const item = backlog?.items?.[0];
|
|
17
|
+
if (!item)
|
|
18
|
+
throw new CliError(`No story "${story}" in project ${project}.`, ExitCode.USAGE);
|
|
19
|
+
return item;
|
|
20
|
+
};
|
|
21
|
+
export const deliveryOf = (api, project, slug) => api.request(storyPath(project, slug, '/delivery'));
|
|
22
|
+
/** The build of the story, or a clear error when it has none. */
|
|
23
|
+
export const requireBuild = (delivery) => {
|
|
24
|
+
if (!delivery.build)
|
|
25
|
+
throw new CliError('The story has no build yet. Run "kodly run build <story>" first.', ExitCode.CONFLICT);
|
|
26
|
+
return delivery.build;
|
|
27
|
+
};
|
|
28
|
+
export const requireTestRun = (delivery) => {
|
|
29
|
+
if (!delivery.testRun)
|
|
30
|
+
throw new CliError('The story has no QA run yet. Run "kodly qa send <story>" first.', ExitCode.CONFLICT);
|
|
31
|
+
return delivery.testRun;
|
|
32
|
+
};
|
|
33
|
+
/** The reasons that the server gives when a step is not allowed now, as one line. */
|
|
34
|
+
export const blockedReasons = (delivery, step) => (delivery.readiness?.[step]?.reasons ?? []).join(' ');
|
package/dist/program.js
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { Command } from 'commander';
|
|
2
|
+
import { authCommands } from './commands/auth.js';
|
|
3
|
+
import { codeCommands } from './commands/code.js';
|
|
4
|
+
import { completionCommands } from './commands/completion.js';
|
|
5
|
+
import { deliveryCommands } from './commands/delivery.js';
|
|
6
|
+
import { harnessCommands } from './commands/harness.js';
|
|
7
|
+
import { mcpCommands } from './commands/mcp.js';
|
|
8
|
+
import { miscCommands } from './commands/misc.js';
|
|
9
|
+
import { orgCommands } from './commands/org.js';
|
|
10
|
+
import { planningCommands } from './commands/plan.js';
|
|
11
|
+
import { projectCommands } from './commands/project.js';
|
|
12
|
+
import { reviewCommands } from './commands/review.js';
|
|
13
|
+
import { scaffoldCommands } from './commands/scaffold.js';
|
|
14
|
+
import { storyCommands } from './commands/story.js';
|
|
15
|
+
import { ExitCode } from './core/errors.js';
|
|
16
|
+
/** The kodly command tree. The bin script parses the arguments; the tests drive it in-process. */
|
|
17
|
+
export const createProgram = (version) => {
|
|
18
|
+
const program = new Command();
|
|
19
|
+
program
|
|
20
|
+
.name('kodly')
|
|
21
|
+
.description('The Kodly CLI: your stories, plans, QA and reviews in the terminal')
|
|
22
|
+
.version(version)
|
|
23
|
+
.option('--api <url>', 'the Kodly API (default https://api.app.kodly.dev, or KODLY_API_URL)')
|
|
24
|
+
.option('--org <slug>', 'the organisation for this command (or KODLY_ORG)')
|
|
25
|
+
.option('--project <slug>', 'the project for this command (or KODLY_PROJECT)')
|
|
26
|
+
.option('--json', 'print JSON for scripts and agents')
|
|
27
|
+
.option('--no-browser', 'print links, but do not open the browser')
|
|
28
|
+
.exitOverride((error) => {
|
|
29
|
+
if (error.code === 'commander.helpDisplayed' || error.code === 'commander.version' || error.code === 'commander.help') {
|
|
30
|
+
process.exit(ExitCode.OK);
|
|
31
|
+
}
|
|
32
|
+
process.exit(ExitCode.USAGE);
|
|
33
|
+
});
|
|
34
|
+
authCommands(program, version);
|
|
35
|
+
orgCommands(program, version);
|
|
36
|
+
projectCommands(program, version);
|
|
37
|
+
storyCommands(program, version);
|
|
38
|
+
planningCommands(program, version);
|
|
39
|
+
deliveryCommands(program, version);
|
|
40
|
+
codeCommands(program, version);
|
|
41
|
+
mcpCommands(program, version);
|
|
42
|
+
harnessCommands(program, version);
|
|
43
|
+
reviewCommands(program, version);
|
|
44
|
+
miscCommands(program, version);
|
|
45
|
+
scaffoldCommands(program);
|
|
46
|
+
completionCommands(program);
|
|
47
|
+
return program;
|
|
48
|
+
};
|