@kodly.dev/kodly-cli 2.0.0 → 2.2.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 CHANGED
@@ -1,7 +1,18 @@
1
1
  # @kodly.dev/kodly-cli
2
2
 
3
- The CLI for the [Kodly](https://kodly.dev) 2.0 story workflow. Version 2 replaces the task commands
4
- of version 1. It signs in with your browser, so it never asks for your password.
3
+ The terminal client of [Kodly](https://kodly.dev). With it you can:
4
+
5
+ - take a story through scope, plan, test plan, build, QA, review and release;
6
+ - check out the code of a story, change it with your own tools, and push it back as a build;
7
+ - get a read-only snapshot of the main code of a whole project;
8
+ - connect your own agent (Claude Code, Codex, OpenCode, Antigravity and others) through MCP. The
9
+ agent can plan, implement, review and test a story, and it can read the project requirements,
10
+ wireframes, documents and stories;
11
+ - scaffold Spring Boot projects, with no login.
12
+
13
+ The CLI signs in with your browser, so it never asks for your password. The steps that are a
14
+ person's decision, such as an approval or a release, also need your approval in the browser.
15
+ Version 2 replaces the task commands of version 1.
5
16
 
6
17
  ## Install
7
18
 
@@ -17,8 +28,8 @@ Node.js 20 or later is necessary.
17
28
  ```bash
18
29
  kodly login # opens the browser; approve the code that the terminal shows
19
30
  kodly whoami
20
- kodly org list
21
- kodly org switch <slug>
31
+ kodly org list # the name, then the slug
32
+ kodly org switch <name> # the name or the slug; also: kodly org current
22
33
  kodly sessions # your CLI sessions; revoke them in Settings > Security of the web app
23
34
  kodly logout # revokes the session of this device
24
35
  ```
@@ -29,24 +40,32 @@ you can read, and the CLI tells you where.
29
40
  ## Work on stories
30
41
 
31
42
  ```bash
32
- kodly project list
33
- kodly project use <slug>
34
- kodly backlog --mine # --lane, --search, --closed, --limit
43
+ kodly project list # the name, then the slug
44
+ kodly project use <name> # the name or the slug; also: kodly project current
45
+ kodly members # the members of the active project
46
+ kodly backlog --mine # --team, --lane, --search, --closed, --limit; also: kodly story list
47
+ kodly story create -f story.yaml # its scope waits for approval; also: kodly story edit KOD-12
35
48
  kodly story show KOD-12 # where the story is, and what blocks the next step
36
49
  kodly story activity KOD-12
50
+ kodly story history KOD-12 # the versions; --of IMPLEMENTATION or TEST_PLAN for the plans
37
51
  kodly story claim KOD-12 # own the current stage
52
+ kodly story archive KOD-12 # also: kodly story restore KOD-12
38
53
 
39
54
  kodly plan show KOD-12
40
55
  kodly plan approve KOD-12 # also: kodly test-plan show|approve, kodly scope approve
41
56
  kodly run build KOD-12 # a build in the Kodly cloud; --checks-only for the checks
57
+ kodly run test KOD-12 # the QA agent on the current build
58
+ kodly runs KOD-12 # the Kodly runs of the story
42
59
  kodly watch KOD-12 # follow the runs until they end
43
60
  kodly checks show KOD-12 # also: kodly checks logs KOD-12 --follow
44
- kodly qa send KOD-12 # QA always runs in the Kodly sandbox
61
+ kodly qa send KOD-12 # QA in the Kodly sandbox; see local QA below
45
62
  kodly qa show KOD-12
63
+ kodly qa triage KOD-12 --category PRODUCT --reason "The total is wrong" # route a failed QA run
46
64
  kodly review request KOD-12
47
65
  kodly review show KOD-12
48
66
  kodly review comment KOD-12 -m "Check the null case" --file src/Login.java --line 42
49
- kodly review approve KOD-12
67
+ kodly review reply KOD-12 <review> -m "Fixed" --resolve # --index for one comment
68
+ kodly review approve KOD-12 # or: kodly review request-changes KOD-12 -m "Add a test"
50
69
  kodly release KOD-12 --notes "Login is live"
51
70
  kodly brief KOD-12
52
71
  kodly usage
@@ -57,7 +76,7 @@ kodly doctor
57
76
 
58
77
  ```bash
59
78
  kodly checkout KOD-12 # one git repository for each codebase, under ./KOD-12/
60
- cd KOD-12/web
79
+ cd "KOD-12/Web app" # each codebase folder has the codebase name
61
80
  # edit, test and commit with your own tools and agents
62
81
  kodly push # sends your commits as a new build; Kodly runs the build checks in its sandbox
63
82
  kodly watch KOD-12
@@ -68,21 +87,58 @@ kodly diff
68
87
  ```
69
88
 
70
89
  - Kodly writes the generated dataType and skill files into the checkout, and git ignores them.
90
+ - When the code has its own file or link at a generated path, for example a skill in `.agents/skills/`,
91
+ the file of the code wins. Kodly writes the other generated files and prints a warning for each path
92
+ that it keeps. Kodly never writes or deletes a generated file through a symbolic link.
93
+ - When a local file that git does not track is at a generated path, Kodly keeps it, writes no generated
94
+ file of that codebase and exits with code 4. Move the file, then run `kodly pull`.
71
95
  - git asks Kodly for a one-hour token each time it needs one. No token goes into a file.
72
96
  - `kodly push` keeps your commit messages. It refuses merge commits, symbolic links, files of more
73
97
  than 8 MiB, files that look like secrets (`.env`, keys), generated files and `Kodly-` trailers.
74
- - A local test never replaces Kodly QA: QA always runs in the Kodly sandbox.
98
+ - QA runs in the Kodly sandbox. When a project admin turns on local QA (`kodly project local-qa on`),
99
+ `kodly qa local` runs it with your agent instead, and the results count only after a person runs
100
+ `kodly qa accept`.
75
101
  - A story with no build can be checked out too. Kodly gives you its story base: main, as a hosted
76
102
  first build would read it. Your first `kodly push` becomes the first build of the story.
77
103
 
78
- ## Use your own agent (Claude Code and others)
104
+ ## Read the code of the whole project
79
105
 
80
106
  ```bash
81
- kodly harness install # registers "kodly mcp" with Claude Code (--tool other prints the setting)
107
+ kodly project checkout # main of each application codebase, read-only, under ./<project name>/
108
+ cd "Shop/Web app" # for the project Shop and its codebase Web app
109
+ kodly pull # bring the newer main into the snapshot
110
+
111
+ kodly project checkout --codebase PRJ00000330 --dir ./shop-web # one codebase, in "./shop-web/Web app/"
112
+ ```
113
+
114
+ - The snapshot is read-only. `git push`, `kodly push`, `kodly status` and `kodly diff` stop there.
115
+ To change code, start a story: `kodly checkout <story>`.
116
+ - Kodly writes the generated files of main into the snapshot, and git ignores them. They come from
117
+ the current project settings (for example the enabled skills), so a pull at the same commit can change
118
+ them. A pull deletes a generated file that Kodly no longer generates.
119
+ - `kodly pull` updates a codebase only when it has no local commit and no changed tracked or generated
120
+ file, and when no local file is at a path that Kodly now generates. Otherwise it keeps your files, does
121
+ not update that codebase, and exits with code 4.
122
+ - A link in place of a generated file or of its folder is a local change too. Kodly never writes or
123
+ deletes through a link, so the files outside the snapshot stay as they are.
124
+ - The folders have the names in Kodly. The characters that Windows or macOS refuse in a file name become
125
+ `-`, for example `Demo: Shop` gives `Demo- Shop`. When two codebase names differ only in case, each
126
+ folder gets the codebase ID added. With a Kodly server that does not give the names, the folders have
127
+ the IDs. `--dir` sets the snapshot folder. A story checkout keeps the story identifier as its folder.
128
+ - When main has its own file at a generated path, the file of main wins, and the pull still moves to
129
+ the new main.
130
+ - A codebase with no code on main yet is left out, and the command says why.
131
+ - A local agent can work in a snapshot. It can read the code and use the project knowledge tools
132
+ of `kodly mcp` (see below). The `push` tool stops there.
133
+
134
+ ## Use your own agent (Claude Code, Codex, OpenCode, Antigravity and others)
135
+
136
+ ```bash
137
+ kodly harness install # registers "kodly mcp" with Claude Code; see --tool below
82
138
  kodly project local on # optional: Kodly starts no automatic hosted plan, test plan or build runs
83
139
  kodly story local KOD-12 local # or for one story (local, hosted, or project to follow the project)
84
140
 
85
- kodly plan draft KOD-12 # checks out the story and tells you the next step
141
+ kodly plan draft KOD-12 # checks out the story and tells you the next step for your tool
86
142
  claude "/mcp__kodly__plan KOD-12"
87
143
  kodly plan approve KOD-12 # you approve the plan in the browser
88
144
  kodly test-plan draft KOD-12 # the same for the test plan: /mcp__kodly__test_plan
@@ -90,11 +146,43 @@ kodly test-plan draft KOD-12 # the same for the test plan: /mcp__kodly__test
90
146
  kodly implement KOD-12 # then implement it
91
147
  cd KOD-12
92
148
  claude "/mcp__kodly__implement KOD-12"
149
+ kodly push
150
+
151
+ kodly project local-qa on # optional: a project admin turns on local QA once
152
+ kodly qa local KOD-12 # in the checkout: the build goes to local QA
153
+ claude "/mcp__kodly__qa KOD-12"
154
+ kodly qa accept KOD-12 # the results count only after a person accepts them
155
+
156
+ kodly review request KOD-12
157
+ kodly review local KOD-12 # in the checkout of the current build: your agent reviews it
158
+ claude "/mcp__kodly__code_review KOD-12"
159
+ kodly review approve KOD-12 # the report is evidence; a person still approves or requests changes
93
160
  ```
94
161
 
95
- `kodly mcp` gives the agent these tools: `story_context`, `plan_context`, `test_plan_context`,
96
- `save_plan`, `save_test_plan`, `story_status`, `read_plan`, `read_test_plan`, `build_checks`,
97
- `push` and `report_usage`. A context holds the story, the plans, the Kodly agent instructions for
162
+ `kodly mcp` gives the agent these tools:
163
+ - Story work: `story_context`, `story_status`, `plan_context`, `test_plan_context`, `save_plan`,
164
+ `save_test_plan`, `read_plan`, `read_test_plan`, `build_checks`, `push` and `report_usage`.
165
+ - Stories: `story_schema` and `save_story` (the scope waits for your approval).
166
+ - Local review and QA: `code_review_context`, `save_review_findings`, `qa_context` and
167
+ `save_qa_results`.
168
+ - Project knowledge, as the hosted agents read it: `read_published_requirements` (requirement
169
+ documents and wireframes by ID, such as S0001), `read_project_documents`, `read_codebases` and
170
+ `search_stories`.
171
+ - `flow_instructions`: the text of a prompt, for a tool that has no MCP prompts. It only reads.
172
+
173
+ `kodly harness install --tool <tool>` sets up the agent tool, and the commands then print the next
174
+ step for that tool:
175
+
176
+ | `--tool` | Setup | Next step in a checkout |
177
+ |---|---|---|
178
+ | `claude` (default) | `claude mcp add --scope user kodly -- ...` (`--scope` changes the scope) | `claude "/mcp__kodly__implement KOD-12"` |
179
+ | `codex` | `codex mcp add kodly -- ...` | Send: Call the kodly tool flow_instructions with flow "implement" and story "KOD-12", then follow the instructions. |
180
+ | `opencode` | `opencode mcp add --global kodly -- ...` | Start `opencode`, then type `/kodly:implement KOD-12` |
181
+ | `antigravity` | adds `mcpServers.kodly` to `~/.gemini/config/mcp_config.json`, and keeps the other servers | The same sentence as Codex |
182
+ | `other` | prints the setting to add | The same sentence as Codex |
183
+
184
+ Its prompts are `implement`, `plan`, `test_plan`, `story`, `code_review` and `qa` (in Claude Code:
185
+ `/mcp__kodly__story`). A context holds the story, the plans, the Kodly agent instructions for
98
186
  the phase and the local rules, and only the names of the secrets. A plan that the agent saves is a
99
187
  draft: you approve it in the browser. Under the project's independent review policy, another
100
188
  member must approve a plan that you drafted; project admins can choose single-person review.
@@ -135,19 +223,21 @@ kodly scaffold redis-cache
135
223
  Unversioned skeletons and recipes use the latest stable published Git tag.
136
224
  `--skeleton-version <version>` and `recipe@<version>` pin a specific release.
137
225
 
226
+ `kodly scaffold apply <recipe>` is the long form of `kodly scaffold <recipe>`. Add `--dry-run` to
227
+ see the changes and write nothing.
228
+
138
229
  The scaffold commands load no keychain module and need no login, so servers can run them. They
139
230
  run the same code as the `kodly-scaffold` bin of `@kodly.dev/scaffolder`, which servers should
140
- install in place of the full CLI. The test `test/scaffold-contract.test.ts` pins the command lines
141
- and the `list` output of both bins. Change them only together with kodly-api.
142
- The scaffolder accepts only the recipe tags in its qualified catalog. See the scaffolder README.
231
+ install in place of the full CLI. The scaffolder accepts only the recipe tags in its qualified
232
+ catalog. See the scaffolder README.
143
233
 
144
234
  ## Options and environment
145
235
 
146
236
  | Option or variable | Use |
147
237
  |---|---|
148
238
  | `--api <url>`, `KODLY_API_URL` | Another Kodly API (https, or http for localhost) |
149
- | `--org <slug>`, `KODLY_ORG` | The organisation for one command |
150
- | `--project <slug>`, `KODLY_PROJECT` | The project for one command |
239
+ | `--org <slug>`, `KODLY_ORG` | The organisation for one command (the slug only) |
240
+ | `--project <slug>`, `KODLY_PROJECT` | The project for one command (the slug only) |
151
241
  | `--json` | JSON output for scripts and agents. An error is `{"error": {...}}` |
152
242
  | `--no-browser`, `KODLY_NO_BROWSER=1` | Print links, but do not open the browser |
153
243
  | `KODLY_TOKEN` | Use this token, and do not read the stored one |
@@ -156,12 +246,14 @@ The scaffolder accepts only the recipe tags in its qualified catalog. See the sc
156
246
  | `KODLY_DISABLE_UPDATE_CHECK=1` | No check for a newer version on npm |
157
247
 
158
248
  Inside a checkout, `.kodly/story.json` gives the API, the organisation and the project of every
159
- command. A flag or a variable that names another value stops the command with exit code 2. Before
160
- a command changes data in a project, the CLI writes the target on stderr, for example
249
+ command. Inside a project snapshot, `.kodly/project.json` does the same. A flag or a variable that
250
+ names another value stops the command with exit code 2. Before a command changes data in a
251
+ project, the CLI writes the target on stderr, for example
161
252
  `Kodly target: org <org>, project <project>, story <story>`.
162
253
 
163
- Exit codes: 0 done, 1 error, 2 usage error, 3 a login or step was denied or expired, 4 the state
164
- changed on the server (do the step that the message names, then try again).
254
+ Exit codes: 0 done, 1 error, 2 usage error, 3 a login or step was denied or expired, 4 a conflict:
255
+ the state changed on the server, or a local file blocks the step (do the step that the message
256
+ names, then try again).
165
257
 
166
258
  ## Shell completion
167
259
 
@@ -34,7 +34,7 @@ export const authCommands = (program, cliVersion) => {
34
34
  if (org)
35
35
  console.log(`Organisation: ${chalk.cyan(org)}`);
36
36
  else if (memberships.length > 1)
37
- console.log('Choose an organisation: kodly org list, then kodly org switch <slug>.');
37
+ console.log('Choose an organisation: kodly org list, then kodly org switch <name>.');
38
38
  });
39
39
  }));
40
40
  program
@@ -60,7 +60,7 @@ export const authCommands = (program, cliVersion) => {
60
60
  emit(ctx.json, result, () => {
61
61
  console.log(`${chalk.bold(user.name ?? '')} <${user.email ?? ''}>`);
62
62
  console.log(chalk.dim(`API: ${ctx.apiUrl}`));
63
- console.log(chalk.dim(`Organisation: ${result.org ?? 'none (kodly org switch <slug>)'}`));
63
+ console.log(chalk.dim(`Organisation: ${result.org ?? 'none (kodly org switch <name>)'}`));
64
64
  });
65
65
  }));
66
66
  program
@@ -3,14 +3,15 @@ import { randomUUID } from 'node:crypto';
3
3
  import fs from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import { Api } from '../core/api.js';
6
- import { findCheckout, insideDir, safeName, writeContext } from '../core/checkout.js';
6
+ import { codebaseFolders, findCheckout, findFolder, findSnapshot, folderName, insideDir, makeFolders, safeName, SNAPSHOT_READ_ONLY, writeContext, writeSnapshot, } from '../core/checkout.js';
7
7
  import { buildContext } from '../core/context.js';
8
8
  import { readToken } from '../core/credentials.js';
9
- import { CliError, ExitCode } from '../core/errors.js';
10
- import { storyPath, table } from '../core/format.js';
9
+ import { ApiError, CliError, ExitCode } from '../core/errors.js';
10
+ import { projectPath, storyPath, table } from '../core/format.js';
11
+ import { applyGenerated, changedGenerated, generatedConflicts } from '../core/generated-files.js';
11
12
  import { git, gitTry } from '../core/git.js';
12
13
  import { emit, run } from '../core/output.js';
13
- import { blobId, checkPush } from '../core/push-checks.js';
14
+ import { checkPush } from '../core/push-checks.js';
14
15
  import { deliveryOf, findStory } from '../core/story.js';
15
16
  /**
16
17
  * True when git asks for the credentials of the push URL (the inbox), else it asks for the fetch URL
@@ -22,26 +23,49 @@ export const isPushRequest = (fields, pushRemote) => {
22
23
  const want = new URL(pushRemote);
23
24
  return fields.path.replace(/^\//, '') === want.pathname.replace(/^\//, '') && (!fields.host || fields.host === want.host);
24
25
  };
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);
26
+ /** The generated files of a codebase of the story build. */
27
+ const storyGenerated = async (api, context, codebase) => (await api.request(storyPath(context.project, context.story, '/code/generated'), { query: { codebase } })) ?? [];
28
+ /** The generated files of a codebase of a project snapshot, for a main commit. 409 when main is no longer that commit. */
29
+ const snapshotGenerated = async (api, context, codebase, commit) => (await api.request(projectPath(context.project, '/code/generated'), { query: { codebase, commit } })) ?? [];
30
+ /**
31
+ * The name of a project and the names of its codebases, by codebase ID. When the call fails, for example
32
+ * on an older server, both are empty, and the folders get the IDs.
33
+ */
34
+ const namesOf = async (api, project) => {
35
+ try {
36
+ const view = await api.request(projectPath(project, '/codebases'));
37
+ return { project: view?.name, codebases: new Map((view?.codebases ?? []).filter((c) => c.name).map((c) => [c.slug, c.name])) };
38
+ }
39
+ catch (error) {
40
+ if (error instanceof CliError)
41
+ return { codebases: new Map() };
42
+ throw error;
36
43
  }
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
44
  };
45
+ /**
46
+ * `value` as one word for the shell that runs a git credential helper. A folder name can now hold "$" or
47
+ * "`", and the shell must not run them.
48
+ */
49
+ const shellWord = (value) => `'${value.replace(/'/g, "'\\''")}'`;
43
50
  /** The API client of a checkout: the API, the organisation and the project that the checkout names. */
44
51
  const checkoutApi = (command, cliVersion, context) => checkoutApiFor(buildContext(command, cliVersion).api.session, context);
52
+ /**
53
+ * The error of a checkout that git finished, but where a local file is at a generated path. kodly writes
54
+ * no generated file of that codebase, so it never writes over a local change.
55
+ */
56
+ const notWritten = (root, conflicts) => new CliError(`kodly checked out the code in ${root}, but did not write the generated files of these codebases:\n ${conflicts.join('\n ')}\nMove these files out of the way, then run kodly pull in the codebase folder.`, ExitCode.CONFLICT);
57
+ /** The conflicts that stop the generated files of a codebase: the local changes. */
58
+ const blocking = (found) => found.filter((c) => c.kind !== 'main').map((c) => c.message);
59
+ /**
60
+ * The generated files without the paths where the code has its own file. The file of the code wins.
61
+ * kodly prints one warning for each path that it leaves out.
62
+ */
63
+ const withoutMain = (files, found) => {
64
+ const kept = new Set(found.filter((c) => c.kind === 'main').map((c) => c.path));
65
+ for (const file of kept)
66
+ process.stderr.write(chalk.yellow(`${file}: the code has its own file here. Kodly keeps it.`) + '\n');
67
+ return files.filter((file) => !kept.has(file.path));
68
+ };
45
69
  /**
46
70
  * Clones the code of a story into `dir`: one git repository for each codebase of its build. A story
47
71
  * with no saved build gets its story base: main as a hosted first build reads it.
@@ -59,13 +83,15 @@ export const checkoutStory = async (ctx, id, dir) => {
59
83
  const context = {
60
84
  api: ctx.apiUrl, org: ctx.api.session.orgSlug, project, story: item.slug, identifier: item.identifier, codebases: [], baseBuildId: views[0].baseBuildId,
61
85
  };
62
- fs.mkdirSync(root, { recursive: true });
86
+ const folders = codebaseFolders(views.map((view) => view.codebase), (await namesOf(ctx.api, project)).codebases);
87
+ makeFolders(root, folders.values());
63
88
  writeContext(root, context);
64
89
  const self = process.argv[1] ? `"${process.execPath}" "${path.resolve(process.argv[1])}"` : 'kodly';
90
+ const conflicts = [];
65
91
  for (const view of views) {
66
92
  if (!view.commit)
67
93
  throw new CliError(`${view.codebase}: ${view.reasons.join(' ')}`, ExitCode.CONFLICT);
68
- const dir = insideDir(root, safeName(view.codebase));
94
+ const dir = insideDir(root, folders.get(view.codebase));
69
95
  fs.mkdirSync(dir, { recursive: true });
70
96
  const codebase = { codebase: view.codebase, dir: path.relative(root, dir), remote: view.remote, pushRemote: view.pushRemote, generated: {} };
71
97
  // The credential helper reads the codebase from the context file. Write it before the first
@@ -79,14 +105,26 @@ export const checkoutStory = async (ctx, id, dir) => {
79
105
  // The empty value clears the helpers of the user and system config, such as osxkeychain.
80
106
  // Otherwise git asks them first, gets an expired token, and also stores each new token there.
81
107
  await git(dir, ['config', 'credential.helper', '']);
82
- await git(dir, ['config', '--add', 'credential.helper', `!${self} git-credential --checkout "${root}" --codebase ${view.codebase}`]);
108
+ await git(dir, ['config', '--add', 'credential.helper', `!${self} git-credential --checkout ${shellWord(root)} --codebase ${view.codebase}`]);
83
109
  await git(dir, ['config', 'credential.useHttpPath', 'true']);
84
110
  await git(dir, ['fetch', '--quiet', 'origin', 'main']);
85
111
  await git(dir, ['reset', '--quiet', '--hard', view.commit]);
86
112
  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);
113
+ const files = await storyGenerated(ctx.api, context, codebase.codebase);
114
+ const found = await generatedConflicts(dir, files, codebase.generated, 'HEAD');
115
+ if (blocking(found).length) {
116
+ conflicts.push(`${codebase.codebase}: ${blocking(found).join('; ')}`);
117
+ continue;
118
+ }
119
+ try {
120
+ await applyGenerated(dir, withoutMain(files, found), codebase.generated);
121
+ }
122
+ finally {
123
+ writeContext(root, context);
124
+ }
89
125
  }
126
+ if (conflicts.length)
127
+ throw notWritten(root, conflicts);
90
128
  return { root, context, item };
91
129
  };
92
130
  /**
@@ -123,6 +161,139 @@ export const pushCheckout = async (api, root, context, options) => {
123
161
  });
124
162
  return { commits, result };
125
163
  };
164
+ /** The push URL of a snapshot repository. It is not a URL, so git push stops before it asks for a token. */
165
+ export const SNAPSHOT_PUSH_URL = 'kodly-project-snapshot-is-read-only';
166
+ /**
167
+ * Clones the main code of a project into `dir`, read-only: one git repository for each application
168
+ * codebase, at the main commit that Kodly shows. A codebase with no code on main is left out with its reason.
169
+ */
170
+ export const checkoutProject = async (ctx, options) => {
171
+ const project = ctx.project();
172
+ const views = (await ctx.api.request(projectPath(project, '/code/main'))) ?? [];
173
+ const chosen = options.codebase ? views.filter((view) => view.codebase === options.codebase) : views;
174
+ if (options.codebase && chosen.length === 0) {
175
+ throw new CliError(`The project has no application codebase ${options.codebase}. Run kodly project checkout with no --codebase to see them.`, ExitCode.USAGE);
176
+ }
177
+ const skipped = chosen.filter((view) => !view.commit || !view.remote).map((view) => ({ codebase: view.codebase, reasons: view.reasons }));
178
+ const ready = chosen.filter((view) => view.commit && view.remote);
179
+ if (ready.length === 0) {
180
+ throw new CliError(`No codebase of the project has code on main yet. ${skipped.map((s) => s.reasons.join(' ')).join(' ')}`.trim(), ExitCode.CONFLICT);
181
+ }
182
+ const names = await namesOf(ctx.api, project);
183
+ const root = path.resolve(options.dir ?? folderName(names.project, project));
184
+ if (fs.existsSync(root) && fs.readdirSync(root).length > 0) {
185
+ throw new CliError(`${root} is not empty. Choose another folder with --dir.`, ExitCode.USAGE);
186
+ }
187
+ const context = { kind: 'project', api: ctx.apiUrl, org: ctx.api.session.orgSlug, project, codebases: [] };
188
+ const folders = codebaseFolders(ready.map((view) => view.codebase), names.codebases);
189
+ makeFolders(root, folders.values());
190
+ writeSnapshot(root, context);
191
+ const self = process.argv[1] ? `"${process.execPath}" "${path.resolve(process.argv[1])}"` : 'kodly';
192
+ const conflicts = [];
193
+ for (const view of ready) {
194
+ const dir = insideDir(root, folders.get(view.codebase));
195
+ fs.mkdirSync(dir, { recursive: true });
196
+ const codebase = { codebase: view.codebase, dir: path.relative(root, dir), remote: view.remote, commit: view.commit, generated: {} };
197
+ // The credential helper reads the codebase from the snapshot file, so write it before the first fetch.
198
+ context.codebases.push(codebase);
199
+ writeSnapshot(root, context);
200
+ await git(dir, ['init', '--quiet', '--initial-branch', 'main']);
201
+ await git(dir, ['remote', 'add', 'origin', codebase.remote]);
202
+ await git(dir, ['config', 'remote.origin.pushurl', SNAPSHOT_PUSH_URL]);
203
+ // As in a story checkout: a 1 h READ token each time git needs one, and no token in a file.
204
+ await git(dir, ['config', 'credential.helper', '']);
205
+ await git(dir, ['config', '--add', 'credential.helper', `!${self} git-credential --snapshot ${shellWord(root)} --codebase ${view.codebase}`]);
206
+ await git(dir, ['config', 'credential.useHttpPath', 'true']);
207
+ await git(dir, ['fetch', '--quiet', 'origin', 'main']);
208
+ await git(dir, ['reset', '--quiet', '--hard', codebase.commit]);
209
+ await git(dir, ['branch', '--quiet', '--set-upstream-to', 'origin/main']).catch(() => undefined);
210
+ const files = await snapshotGenerated(ctx.api, context, codebase.codebase, codebase.commit);
211
+ const found = await generatedConflicts(dir, files, codebase.generated, 'HEAD');
212
+ if (blocking(found).length) {
213
+ conflicts.push(`${codebase.codebase}: ${blocking(found).join('; ')}`);
214
+ continue;
215
+ }
216
+ try {
217
+ await applyGenerated(dir, withoutMain(files, found), codebase.generated);
218
+ }
219
+ finally {
220
+ writeSnapshot(root, context);
221
+ }
222
+ }
223
+ if (conflicts.length)
224
+ throw notWritten(root, conflicts);
225
+ return { root, context, skipped };
226
+ };
227
+ /**
228
+ * Why a codebase of a snapshot is not the main commit that `project.json` records, or undefined when it
229
+ * is: a local commit, a changed tracked file or a changed generated file. Untracked files are allowed.
230
+ */
231
+ const snapshotChanges = async (dir, codebase) => {
232
+ const head = await gitTry(dir, ['rev-parse', 'HEAD']);
233
+ if (head !== codebase.commit)
234
+ return `HEAD is ${head?.slice(0, 12) ?? 'missing'}, but the snapshot is main ${codebase.commit.slice(0, 12)}`;
235
+ if ((await git(dir, ['status', '--porcelain', '--untracked-files=no'])).trim())
236
+ return 'tracked files have local changes';
237
+ const changed = changedGenerated(dir, codebase.generated);
238
+ if (changed.length)
239
+ return `generated files have local changes: ${changed.join(', ')}`;
240
+ return undefined;
241
+ };
242
+ /**
243
+ * Brings each codebase of a project snapshot to the main commit that Kodly shows now (fast-forward only).
244
+ * A codebase with local changes is not updated, and its changes stay. All checks run before the merge:
245
+ * the local changes, the generated files of the new commit (a 409 "Main moved" changes nothing) and
246
+ * their conflicts with local files. project.json is saved after each codebase that git moved.
247
+ */
248
+ const pullSnapshot = async (api, root, context) => {
249
+ const views = new Map(((await api.request(projectPath(context.project, '/code/main'))) ?? []).map((view) => [view.codebase, view]));
250
+ const rows = [];
251
+ for (const codebase of context.codebases) {
252
+ const view = views.get(codebase.codebase);
253
+ if (!view?.commit) {
254
+ rows.push({ codebase: codebase.codebase, result: `not updated: ${view?.reasons.join(' ') || 'the project has no such codebase now'}` });
255
+ continue;
256
+ }
257
+ const dir = path.join(root, codebase.dir);
258
+ const changes = await snapshotChanges(dir, codebase);
259
+ if (changes) {
260
+ rows.push({ codebase: codebase.codebase, result: `not updated: ${changes}. Kodly keeps your changes. To change code, start a story; to read main, check out again into a new folder` });
261
+ continue;
262
+ }
263
+ let files;
264
+ try {
265
+ files = await snapshotGenerated(api, context, codebase.codebase, view.commit);
266
+ }
267
+ catch (error) {
268
+ if (!(error instanceof ApiError) || error.status !== 409)
269
+ throw error;
270
+ rows.push({ codebase: codebase.codebase, result: `not updated: ${error.message}` });
271
+ continue;
272
+ }
273
+ await git(dir, ['fetch', '--quiet', 'origin', 'main']);
274
+ // A path that main tracks does not stop the merge: the file of main wins.
275
+ const found = await generatedConflicts(dir, files, codebase.generated, view.commit);
276
+ if (blocking(found).length) {
277
+ rows.push({ codebase: codebase.codebase, result: `not updated: ${blocking(found).join('; ')}. Kodly keeps your files. Move them, then run kodly pull again` });
278
+ continue;
279
+ }
280
+ await gitTry(dir, ['merge', '--ff-only', '--quiet', view.commit]);
281
+ if ((await gitTry(dir, ['rev-parse', 'HEAD'])) !== view.commit) {
282
+ rows.push({ codebase: codebase.codebase, result: `not updated: git cannot fast-forward to main ${view.commit.slice(0, 12)}. A local file can be in the way. Check out again into a new folder` });
283
+ continue;
284
+ }
285
+ codebase.commit = view.commit;
286
+ try {
287
+ await applyGenerated(dir, withoutMain(files, found), codebase.generated);
288
+ }
289
+ finally {
290
+ // Save after git moved, also when a file write fails, so project.json always names the commit of HEAD.
291
+ writeSnapshot(root, context);
292
+ }
293
+ rows.push({ codebase: codebase.codebase, result: 'up to date' });
294
+ }
295
+ return rows;
296
+ };
126
297
  /** The API client of a checkout: the API, the organisation and the project that the checkout names. */
127
298
  export const checkoutApiFor = (session, context) => {
128
299
  const stored = readToken(context.api);
@@ -135,7 +306,7 @@ export const codeCommands = (program, cliVersion) => {
135
306
  .command('checkout')
136
307
  .argument('<story>', 'the story identifier or slug')
137
308
  .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')
309
+ .description('Clone the code of a story: one git repository for each codebase, in a folder with the codebase name')
139
310
  .action(run(async (id, options, command) => {
140
311
  const ctx = buildContext(command, cliVersion);
141
312
  const { root, context, item } = await checkoutStory(ctx, id, options.dir);
@@ -149,14 +320,30 @@ export const codeCommands = (program, cliVersion) => {
149
320
  program
150
321
  .command('git-credential', { hidden: true })
151
322
  .argument('<operation>', 'get, store or erase (git calls this)')
152
- .requiredOption('--checkout <root>', 'the root of the checkout')
323
+ .option('--checkout <root>', 'the root of the story checkout')
324
+ .option('--snapshot <root>', 'the root of the project snapshot')
153
325
  .requiredOption('--codebase <codebase>', 'the codebase of this repository')
154
- .description('The git credential helper of a kodly checkout')
326
+ .description('The git credential helper of a kodly checkout or project snapshot')
155
327
  .action(run(async (operation, options, command) => {
156
328
  if (operation !== 'get')
157
329
  return;
158
330
  const input = fs.readFileSync(0, 'utf8');
159
331
  const fields = Object.fromEntries(input.split('\n').filter((l) => l.includes('=')).map((l) => [l.slice(0, l.indexOf('=')), l.slice(l.indexOf('=') + 1)]));
332
+ if (options.snapshot) {
333
+ const { context } = findSnapshot(options.snapshot);
334
+ const codebase = context.codebases.find((c) => c.codebase === options.codebase);
335
+ if (!codebase)
336
+ throw new CliError(`The snapshot has no codebase ${options.codebase}.`);
337
+ // A snapshot only reads: git may ask for the main repository of the codebase, and for nothing else.
338
+ if (fields.path !== undefined && !isPushRequest(fields, codebase.remote))
339
+ throw new CliError(SNAPSHOT_READ_ONLY);
340
+ const api = checkoutApi(command, cliVersion, context);
341
+ const token = await api.request(projectPath(context.project, '/code/credentials/read'), { method: 'POST', body: { codebase: codebase.codebase }, quiet: true });
342
+ process.stdout.write(`username=${token.username}\npassword=${token.password}\n`);
343
+ return;
344
+ }
345
+ if (!options.checkout)
346
+ throw new CliError('Name the checkout with --checkout or the snapshot with --snapshot.', ExitCode.USAGE);
160
347
  const { context } = findCheckout(options.checkout);
161
348
  const codebase = context.codebases.find((c) => c.codebase === options.codebase);
162
349
  if (!codebase)
@@ -168,20 +355,39 @@ export const codeCommands = (program, cliVersion) => {
168
355
  }));
169
356
  program
170
357
  .command('pull')
171
- .description('Bring the latest story code into the checkout (fast-forward only)')
358
+ .description('Bring the latest story code into the checkout, or the latest main into a project snapshot (fast-forward only)')
172
359
  .action(run(async (_options, command) => {
360
+ const json = command.optsWithGlobals().json === true;
361
+ const folder = findFolder();
362
+ if (folder?.kind === 'project') {
363
+ const rows = await pullSnapshot(checkoutApi(command, cliVersion, folder.context), folder.root, folder.context);
364
+ emit(json, rows, () => table(rows.map((r) => [r.codebase, r.result])));
365
+ if (rows.some((r) => r.result !== 'up to date'))
366
+ process.exitCode = ExitCode.CONFLICT;
367
+ return;
368
+ }
173
369
  const { root, context } = findCheckout();
174
370
  const api = checkoutApi(command, cliVersion, context);
175
- const json = command.optsWithGlobals().json === true;
176
371
  const rows = [];
177
372
  for (const codebase of context.codebases) {
178
373
  const dir = path.join(root, codebase.dir);
179
374
  await git(dir, ['fetch', '--quiet', 'origin', 'main']);
180
375
  const merged = await gitTry(dir, ['merge', '--ff-only', '--quiet', 'origin/main']);
181
- codebase.generated = await writeGenerated(api, context, codebase, dir);
376
+ const files = await storyGenerated(api, context, codebase.codebase);
377
+ const found = await generatedConflicts(dir, files, codebase.generated, 'HEAD');
378
+ if (blocking(found).length) {
379
+ rows.push({ codebase: codebase.codebase, result: `generated files not written: ${blocking(found).join('; ')}. Move these files, then run kodly pull again` });
380
+ continue;
381
+ }
382
+ try {
383
+ await applyGenerated(dir, withoutMain(files, found), codebase.generated);
384
+ }
385
+ finally {
386
+ // Save after each codebase, also when a write fails, so story.json names the files that kodly wrote.
387
+ writeContext(root, context);
388
+ }
182
389
  rows.push({ codebase: codebase.codebase, result: merged === null ? 'not a fast-forward: rebase your commits on origin/main' : 'up to date' });
183
390
  }
184
- writeContext(root, context);
185
391
  emit(json, rows, () => table(rows.map((r) => [r.codebase, r.result])));
186
392
  if (rows.some((r) => r.result !== 'up to date'))
187
393
  process.exitCode = ExitCode.CONFLICT;