@kodly.dev/kodly-cli 2.1.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -5,8 +5,9 @@ The terminal client of [Kodly](https://kodly.dev). With it you can:
5
5
  - take a story through scope, plan, test plan, build, QA, review and release;
6
6
  - check out the code of a story, change it with your own tools, and push it back as a build;
7
7
  - get a read-only snapshot of the main code of a whole project;
8
- - connect your own agent (Claude Code and others) through MCP. The agent can plan, implement, review
9
- and test a story, and it can read the project requirements, wireframes, documents and stories;
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;
10
11
  - scaffold Spring Boot projects, with no login.
11
12
 
12
13
  The CLI signs in with your browser, so it never asks for your password. The steps that are a
@@ -27,8 +28,8 @@ Node.js 20 or later is necessary.
27
28
  ```bash
28
29
  kodly login # opens the browser; approve the code that the terminal shows
29
30
  kodly whoami
30
- kodly org list
31
- kodly org switch <slug> # also: kodly org current
31
+ kodly org list # the name, then the slug
32
+ kodly org switch <name> # the name or the slug; also: kodly org current
32
33
  kodly sessions # your CLI sessions; revoke them in Settings > Security of the web app
33
34
  kodly logout # revokes the session of this device
34
35
  ```
@@ -39,8 +40,8 @@ you can read, and the CLI tells you where.
39
40
  ## Work on stories
40
41
 
41
42
  ```bash
42
- kodly project list
43
- kodly project use <slug> # also: kodly project current
43
+ kodly project list # the name, then the slug
44
+ kodly project use <name> # the name or the slug; also: kodly project current
44
45
  kodly members # the members of the active project
45
46
  kodly backlog --mine # --team, --lane, --search, --closed, --limit; also: kodly story list
46
47
  kodly story create -f story.yaml # its scope waits for approval; also: kodly story edit KOD-12
@@ -75,8 +76,9 @@ kodly doctor
75
76
 
76
77
  ```bash
77
78
  kodly checkout KOD-12 # one git repository for each codebase, under ./KOD-12/
78
- cd KOD-12/web
79
+ cd "KOD-12/Web app" # each codebase folder has the codebase name
79
80
  # edit, test and commit with your own tools and agents
81
+ kodly pull --from-main # bring the project's published main into the local story
80
82
  kodly push # sends your commits as a new build; Kodly runs the build checks in its sandbox
81
83
  kodly watch KOD-12
82
84
  kodly qa send KOD-12 # when the checks pass
@@ -86,10 +88,15 @@ kodly diff
86
88
  ```
87
89
 
88
90
  - Kodly writes the generated dataType and skill files into the checkout, and git ignores them.
89
- - Kodly never writes or deletes a generated file through a symbolic link. When the code has a file or a
90
- link at a generated path, the checkout writes no generated file of that codebase and exits with code 4.
91
+ - When the code has its own file or link at a generated path, for example a skill in `.agents/skills/`,
92
+ the file of the code wins. Kodly writes the other generated files and prints a warning for each path
93
+ that it keeps. Kodly never writes or deletes a generated file through a symbolic link.
94
+ - When a local file that git does not track is at a generated path, Kodly keeps it, writes no generated
95
+ file of that codebase and exits with code 4. Move the file, then run `kodly pull`.
91
96
  - git asks Kodly for a one-hour token each time it needs one. No token goes into a file.
92
- - `kodly push` keeps your commit messages. It refuses merge commits, symbolic links, files of more
97
+ - If the merge reports conflicts, resolve them in the named codebase, run `git merge --continue`,
98
+ then repeat `kodly pull --from-main`. Use `git merge --abort` to abandon a conflicting merge.
99
+ - `kodly push` keeps your commit messages. It accepts merges of verified project main and rejects other merge commits, symbolic links, files of more
93
100
  than 8 MiB, files that look like secrets (`.env`, keys), generated files and `Kodly-` trailers.
94
101
  - QA runs in the Kodly sandbox. When a project admin turns on local QA (`kodly project local-qa on`),
95
102
  `kodly qa local` runs it with your agent instead, and the results count only after a person runs
@@ -100,11 +107,11 @@ kodly diff
100
107
  ## Read the code of the whole project
101
108
 
102
109
  ```bash
103
- kodly project checkout # main of each application codebase, read-only, under ./<project>/
104
- cd shop/web # for the project shop and its codebase web
110
+ kodly project checkout # main of each application codebase, read-only, under ./<project name>/
111
+ cd "Shop/Web app" # for the project Shop and its codebase Web app
105
112
  kodly pull # bring the newer main into the snapshot
106
113
 
107
- kodly project checkout --codebase web --dir ./shop-web # one codebase, in ./shop-web/web/
114
+ kodly project checkout --codebase PRJ00000330 --dir ./shop-web # one codebase, in "./shop-web/Web app/"
108
115
  ```
109
116
 
110
117
  - The snapshot is read-only. `git push`, `kodly push`, `kodly status` and `kodly diff` stop there.
@@ -117,18 +124,24 @@ kodly project checkout --codebase web --dir ./shop-web # one codebase, in ./sh
117
124
  not update that codebase, and exits with code 4.
118
125
  - A link in place of a generated file or of its folder is a local change too. Kodly never writes or
119
126
  deletes through a link, so the files outside the snapshot stay as they are.
127
+ - The folders have the names in Kodly. The characters that Windows or macOS refuse in a file name become
128
+ `-`, for example `Demo: Shop` gives `Demo- Shop`. When two codebase names differ only in case, each
129
+ folder gets the codebase ID added. With a Kodly server that does not give the names, the folders have
130
+ the IDs. `--dir` sets the snapshot folder. A story checkout keeps the story identifier as its folder.
131
+ - When main has its own file at a generated path, the file of main wins, and the pull still moves to
132
+ the new main.
120
133
  - A codebase with no code on main yet is left out, and the command says why.
121
134
  - A local agent can work in a snapshot. It can read the code and use the project knowledge tools
122
135
  of `kodly mcp` (see below). The `push` tool stops there.
123
136
 
124
- ## Use your own agent (Claude Code and others)
137
+ ## Use your own agent (Claude Code, Codex, OpenCode, Antigravity and others)
125
138
 
126
139
  ```bash
127
- kodly harness install # registers "kodly mcp" with Claude Code (--tool other prints the setting)
140
+ kodly harness install # registers "kodly mcp" with Claude Code; see --tool below
128
141
  kodly project local on # optional: Kodly starts no automatic hosted plan, test plan or build runs
129
142
  kodly story local KOD-12 local # or for one story (local, hosted, or project to follow the project)
130
143
 
131
- kodly plan draft KOD-12 # checks out the story and tells you the next step
144
+ kodly plan draft KOD-12 # checks out the story and tells you the next step for your tool
132
145
  claude "/mcp__kodly__plan KOD-12"
133
146
  kodly plan approve KOD-12 # you approve the plan in the browser
134
147
  kodly test-plan draft KOD-12 # the same for the test plan: /mcp__kodly__test_plan
@@ -158,6 +171,18 @@ kodly review approve KOD-12 # the report is evidence; a person still approv
158
171
  - Project knowledge, as the hosted agents read it: `read_published_requirements` (requirement
159
172
  documents and wireframes by ID, such as S0001), `read_project_documents`, `read_codebases` and
160
173
  `search_stories`.
174
+ - `flow_instructions`: the text of a prompt, for a tool that has no MCP prompts. It only reads.
175
+
176
+ `kodly harness install --tool <tool>` sets up the agent tool, and the commands then print the next
177
+ step for that tool:
178
+
179
+ | `--tool` | Setup | Next step in a checkout |
180
+ |---|---|---|
181
+ | `claude` (default) | `claude mcp add --scope user kodly -- ...` (`--scope` changes the scope) | `claude "/mcp__kodly__implement KOD-12"` |
182
+ | `codex` | `codex mcp add kodly -- ...` | Send: Call the kodly tool flow_instructions with flow "implement" and story "KOD-12", then follow the instructions. |
183
+ | `opencode` | `opencode mcp add --global kodly -- ...` | Start `opencode`, then type `/kodly:implement KOD-12` |
184
+ | `antigravity` | adds `mcpServers.kodly` to `~/.gemini/config/mcp_config.json`, and keeps the other servers | The same sentence as Codex |
185
+ | `other` | prints the setting to add | The same sentence as Codex |
161
186
 
162
187
  Its prompts are `implement`, `plan`, `test_plan`, `story`, `code_review` and `qa` (in Claude Code:
163
188
  `/mcp__kodly__story`). A context holds the story, the plans, the Kodly agent instructions for
@@ -214,8 +239,8 @@ catalog. See the scaffolder README.
214
239
  | Option or variable | Use |
215
240
  |---|---|
216
241
  | `--api <url>`, `KODLY_API_URL` | Another Kodly API (https, or http for localhost) |
217
- | `--org <slug>`, `KODLY_ORG` | The organisation for one command |
218
- | `--project <slug>`, `KODLY_PROJECT` | The project for one command |
242
+ | `--org <slug>`, `KODLY_ORG` | The organisation for one command (the slug only) |
243
+ | `--project <slug>`, `KODLY_PROJECT` | The project for one command (the slug only) |
219
244
  | `--json` | JSON output for scripts and agents. An error is `{"error": {...}}` |
220
245
  | `--no-browser`, `KODLY_NO_BROWSER=1` | Print links, but do not open the browser |
221
246
  | `KODLY_TOKEN` | Use this token, and do not read the stored one |
@@ -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,7 +3,7 @@ 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, findFolder, findSnapshot, insideDir, safeName, SNAPSHOT_READ_ONLY, writeContext, writeSnapshot, } 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
9
  import { ApiError, CliError, ExitCode } from '../core/errors.js';
@@ -12,6 +12,7 @@ import { applyGenerated, changedGenerated, generatedConflicts } from '../core/ge
12
12
  import { git, gitTry } from '../core/git.js';
13
13
  import { emit, run } from '../core/output.js';
14
14
  import { checkPush } from '../core/push-checks.js';
15
+ import { pullProjectMain, shellWord } from '../core/project-main.js';
15
16
  import { deliveryOf, findStory } from '../core/story.js';
16
17
  /**
17
18
  * True when git asks for the credentials of the push URL (the inbox), else it asks for the fetch URL
@@ -27,13 +28,40 @@ export const isPushRequest = (fields, pushRemote) => {
27
28
  const storyGenerated = async (api, context, codebase) => (await api.request(storyPath(context.project, context.story, '/code/generated'), { query: { codebase } })) ?? [];
28
29
  /** The generated files of a codebase of a project snapshot, for a main commit. 409 when main is no longer that commit. */
29
30
  const snapshotGenerated = async (api, context, codebase, commit) => (await api.request(projectPath(context.project, '/code/generated'), { query: { codebase, commit } })) ?? [];
31
+ /**
32
+ * The name of a project and the names of its codebases, by codebase ID. When the call fails, for example
33
+ * on an older server, both are empty, and the folders get the IDs.
34
+ */
35
+ const namesOf = async (api, project) => {
36
+ try {
37
+ const view = await api.request(projectPath(project, '/codebases'));
38
+ return { project: view?.name, codebases: new Map((view?.codebases ?? []).filter((c) => c.name).map((c) => [c.slug, c.name])) };
39
+ }
40
+ catch (error) {
41
+ if (error instanceof CliError)
42
+ return { codebases: new Map() };
43
+ throw error;
44
+ }
45
+ };
30
46
  /** The API client of a checkout: the API, the organisation and the project that the checkout names. */
31
47
  const checkoutApi = (command, cliVersion, context) => checkoutApiFor(buildContext(command, cliVersion).api.session, context);
32
48
  /**
33
- * The error of a checkout that git finished, but where a file of the code is at a generated path. kodly
34
- * writes no generated file of that codebase, so it never writes through a link or over source code.
49
+ * The error of a checkout that git finished, but where a local file is at a generated path. kodly writes
50
+ * no generated file of that codebase, so it never writes over a local change.
35
51
  */
36
- 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 ')}\nTell your Kodly administrator: the code must not have files at generated paths.`, ExitCode.CONFLICT);
52
+ 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);
53
+ /** The conflicts that stop the generated files of a codebase: the local changes. */
54
+ const blocking = (found) => found.filter((c) => c.kind !== 'main').map((c) => c.message);
55
+ /**
56
+ * The generated files without the paths where the code has its own file. The file of the code wins.
57
+ * kodly prints one warning for each path that it leaves out.
58
+ */
59
+ const withoutMain = (files, found) => {
60
+ const kept = new Set(found.filter((c) => c.kind === 'main').map((c) => c.path));
61
+ for (const file of kept)
62
+ process.stderr.write(chalk.yellow(`${file}: the code has its own file here. Kodly keeps it.`) + '\n');
63
+ return files.filter((file) => !kept.has(file.path));
64
+ };
37
65
  /**
38
66
  * Clones the code of a story into `dir`: one git repository for each codebase of its build. A story
39
67
  * with no saved build gets its story base: main as a hosted first build reads it.
@@ -51,14 +79,15 @@ export const checkoutStory = async (ctx, id, dir) => {
51
79
  const context = {
52
80
  api: ctx.apiUrl, org: ctx.api.session.orgSlug, project, story: item.slug, identifier: item.identifier, codebases: [], baseBuildId: views[0].baseBuildId,
53
81
  };
54
- fs.mkdirSync(root, { recursive: true });
82
+ const folders = codebaseFolders(views.map((view) => view.codebase), (await namesOf(ctx.api, project)).codebases);
83
+ makeFolders(root, folders.values());
55
84
  writeContext(root, context);
56
85
  const self = process.argv[1] ? `"${process.execPath}" "${path.resolve(process.argv[1])}"` : 'kodly';
57
86
  const conflicts = [];
58
87
  for (const view of views) {
59
88
  if (!view.commit)
60
89
  throw new CliError(`${view.codebase}: ${view.reasons.join(' ')}`, ExitCode.CONFLICT);
61
- const dir = insideDir(root, safeName(view.codebase));
90
+ const dir = insideDir(root, folders.get(view.codebase));
62
91
  fs.mkdirSync(dir, { recursive: true });
63
92
  const codebase = { codebase: view.codebase, dir: path.relative(root, dir), remote: view.remote, pushRemote: view.pushRemote, generated: {} };
64
93
  // The credential helper reads the codebase from the context file. Write it before the first
@@ -72,19 +101,19 @@ export const checkoutStory = async (ctx, id, dir) => {
72
101
  // The empty value clears the helpers of the user and system config, such as osxkeychain.
73
102
  // Otherwise git asks them first, gets an expired token, and also stores each new token there.
74
103
  await git(dir, ['config', 'credential.helper', '']);
75
- await git(dir, ['config', '--add', 'credential.helper', `!${self} git-credential --checkout "${root}" --codebase ${view.codebase}`]);
104
+ await git(dir, ['config', '--add', 'credential.helper', `!${self} git-credential --checkout ${shellWord(root)} --codebase ${view.codebase}`]);
76
105
  await git(dir, ['config', 'credential.useHttpPath', 'true']);
77
106
  await git(dir, ['fetch', '--quiet', 'origin', 'main']);
78
107
  await git(dir, ['reset', '--quiet', '--hard', view.commit]);
79
108
  await git(dir, ['branch', '--quiet', '--set-upstream-to', 'origin/main']).catch(() => undefined);
80
109
  const files = await storyGenerated(ctx.api, context, codebase.codebase);
81
110
  const found = await generatedConflicts(dir, files, codebase.generated, 'HEAD');
82
- if (found.length) {
83
- conflicts.push(`${codebase.codebase}: ${found.join('; ')}`);
111
+ if (blocking(found).length) {
112
+ conflicts.push(`${codebase.codebase}: ${blocking(found).join('; ')}`);
84
113
  continue;
85
114
  }
86
115
  try {
87
- await applyGenerated(dir, files, codebase.generated);
116
+ await applyGenerated(dir, withoutMain(files, found), codebase.generated);
88
117
  }
89
118
  finally {
90
119
  writeContext(root, context);
@@ -99,20 +128,27 @@ export const checkoutStory = async (ctx, id, dir) => {
99
128
  * import them as a new build. `kodly push` and the push tool of `kodly mcp` both use it.
100
129
  */
101
130
  export const pushCheckout = async (api, root, context, options) => {
131
+ if (context.mainSyncPending)
132
+ throw new CliError('Project main sync is incomplete. Finish kodly pull --from-main before pushing.', ExitCode.CONFLICT);
102
133
  const commits = {};
134
+ const unchanged = {};
103
135
  const problems = [];
104
136
  for (const codebase of context.codebases) {
105
137
  const dir = path.join(root, codebase.dir);
106
138
  await git(dir, ['fetch', '--quiet', 'origin', 'main']);
107
- const plan = await checkPush(dir, codebase.codebase, codebase.generated);
139
+ const plan = await checkPush(dir, codebase.codebase, codebase.generated, context.mainCommits?.[codebase.codebase]);
108
140
  problems.push(...plan.problems);
109
141
  if (plan.head)
110
142
  commits[codebase.codebase] = plan.head;
143
+ else if (context.mainCommits && !plan.problems.length)
144
+ unchanged[codebase.codebase] = (await git(dir, ['rev-parse', 'HEAD'])).trim();
111
145
  }
112
146
  if (problems.length)
113
147
  throw new CliError(`The push stops:\n ${problems.join('\n ')}`, ExitCode.USAGE);
114
148
  if (Object.keys(commits).length === 0)
115
149
  throw new CliError('Nothing to push: no codebase has new commits.', ExitCode.USAGE);
150
+ // Prove that even an unchanged repository includes its named main before the API pins the whole checkout.
151
+ Object.assign(commits, unchanged);
116
152
  // A story with a build pushes on it. A first push builds on the story base that the checkout started from.
117
153
  const build = (await deliveryOf(api, context.project, context.story)).build;
118
154
  const baseBuildId = build?.id ?? context.baseBuildId;
@@ -123,9 +159,15 @@ export const pushCheckout = async (api, root, context, options) => {
123
159
  const dir = path.join(root, context.codebases.find((c) => c.codebase === codebase).dir);
124
160
  await git(dir, ['push', '--quiet', 'origin', `${head}:refs/kodly/cli/${pushId}`]);
125
161
  }
126
- const result = await api.request(storyPath(context.project, context.story, '/code/pushes'), {
127
- method: 'POST', body: { pushId, baseBuildId, commits, reportedModel: options.model, reportedHarness: options.harness },
162
+ const endpoint = context.mainCommits ? '/code/pushes/from-main' : '/code/pushes';
163
+ const result = await api.request(storyPath(context.project, context.story, endpoint), {
164
+ method: 'POST', body: { pushId, baseBuildId, commits, reportedModel: options.model, reportedHarness: options.harness,
165
+ mainCommits: context.mainCommits },
128
166
  });
167
+ if (context.mainCommits) {
168
+ delete context.mainCommits;
169
+ writeContext(root, context);
170
+ }
129
171
  return { commits, result };
130
172
  };
131
173
  /** The push URL of a snapshot repository. It is not a URL, so git push stops before it asks for a token. */
@@ -146,17 +188,19 @@ export const checkoutProject = async (ctx, options) => {
146
188
  if (ready.length === 0) {
147
189
  throw new CliError(`No codebase of the project has code on main yet. ${skipped.map((s) => s.reasons.join(' ')).join(' ')}`.trim(), ExitCode.CONFLICT);
148
190
  }
149
- const root = path.resolve(options.dir ?? safeName(project));
191
+ const names = await namesOf(ctx.api, project);
192
+ const root = path.resolve(options.dir ?? folderName(names.project, project));
150
193
  if (fs.existsSync(root) && fs.readdirSync(root).length > 0) {
151
194
  throw new CliError(`${root} is not empty. Choose another folder with --dir.`, ExitCode.USAGE);
152
195
  }
153
196
  const context = { kind: 'project', api: ctx.apiUrl, org: ctx.api.session.orgSlug, project, codebases: [] };
154
- fs.mkdirSync(root, { recursive: true });
197
+ const folders = codebaseFolders(ready.map((view) => view.codebase), names.codebases);
198
+ makeFolders(root, folders.values());
155
199
  writeSnapshot(root, context);
156
200
  const self = process.argv[1] ? `"${process.execPath}" "${path.resolve(process.argv[1])}"` : 'kodly';
157
201
  const conflicts = [];
158
202
  for (const view of ready) {
159
- const dir = insideDir(root, safeName(view.codebase));
203
+ const dir = insideDir(root, folders.get(view.codebase));
160
204
  fs.mkdirSync(dir, { recursive: true });
161
205
  const codebase = { codebase: view.codebase, dir: path.relative(root, dir), remote: view.remote, commit: view.commit, generated: {} };
162
206
  // The credential helper reads the codebase from the snapshot file, so write it before the first fetch.
@@ -167,19 +211,19 @@ export const checkoutProject = async (ctx, options) => {
167
211
  await git(dir, ['config', 'remote.origin.pushurl', SNAPSHOT_PUSH_URL]);
168
212
  // As in a story checkout: a 1 h READ token each time git needs one, and no token in a file.
169
213
  await git(dir, ['config', 'credential.helper', '']);
170
- await git(dir, ['config', '--add', 'credential.helper', `!${self} git-credential --snapshot "${root}" --codebase ${view.codebase}`]);
214
+ await git(dir, ['config', '--add', 'credential.helper', `!${self} git-credential --snapshot ${shellWord(root)} --codebase ${view.codebase}`]);
171
215
  await git(dir, ['config', 'credential.useHttpPath', 'true']);
172
216
  await git(dir, ['fetch', '--quiet', 'origin', 'main']);
173
217
  await git(dir, ['reset', '--quiet', '--hard', codebase.commit]);
174
218
  await git(dir, ['branch', '--quiet', '--set-upstream-to', 'origin/main']).catch(() => undefined);
175
219
  const files = await snapshotGenerated(ctx.api, context, codebase.codebase, codebase.commit);
176
220
  const found = await generatedConflicts(dir, files, codebase.generated, 'HEAD');
177
- if (found.length) {
178
- conflicts.push(`${codebase.codebase}: ${found.join('; ')}`);
221
+ if (blocking(found).length) {
222
+ conflicts.push(`${codebase.codebase}: ${blocking(found).join('; ')}`);
179
223
  continue;
180
224
  }
181
225
  try {
182
- await applyGenerated(dir, files, codebase.generated);
226
+ await applyGenerated(dir, withoutMain(files, found), codebase.generated);
183
227
  }
184
228
  finally {
185
229
  writeSnapshot(root, context);
@@ -236,9 +280,10 @@ const pullSnapshot = async (api, root, context) => {
236
280
  continue;
237
281
  }
238
282
  await git(dir, ['fetch', '--quiet', 'origin', 'main']);
239
- const conflicts = await generatedConflicts(dir, files, codebase.generated, view.commit);
240
- if (conflicts.length) {
241
- rows.push({ codebase: codebase.codebase, result: `not updated: ${conflicts.join('; ')}. Kodly keeps your files. Move them, then run kodly pull again` });
283
+ // A path that main tracks does not stop the merge: the file of main wins.
284
+ const found = await generatedConflicts(dir, files, codebase.generated, view.commit);
285
+ if (blocking(found).length) {
286
+ rows.push({ codebase: codebase.codebase, result: `not updated: ${blocking(found).join('; ')}. Kodly keeps your files. Move them, then run kodly pull again` });
242
287
  continue;
243
288
  }
244
289
  await gitTry(dir, ['merge', '--ff-only', '--quiet', view.commit]);
@@ -248,7 +293,7 @@ const pullSnapshot = async (api, root, context) => {
248
293
  }
249
294
  codebase.commit = view.commit;
250
295
  try {
251
- await applyGenerated(dir, files, codebase.generated);
296
+ await applyGenerated(dir, withoutMain(files, found), codebase.generated);
252
297
  }
253
298
  finally {
254
299
  // Save after git moved, also when a file write fails, so project.json always names the commit of HEAD.
@@ -270,7 +315,7 @@ export const codeCommands = (program, cliVersion) => {
270
315
  .command('checkout')
271
316
  .argument('<story>', 'the story identifier or slug')
272
317
  .option('--dir <path>', 'the folder for the checkout (default: the story identifier)')
273
- .description('Clone the code of a story: one git repository for each codebase')
318
+ .description('Clone the code of a story: one git repository for each codebase, in a folder with the codebase name')
274
319
  .action(run(async (id, options, command) => {
275
320
  const ctx = buildContext(command, cliVersion);
276
321
  const { root, context, item } = await checkoutStory(ctx, id, options.dir);
@@ -286,6 +331,7 @@ export const codeCommands = (program, cliVersion) => {
286
331
  .argument('<operation>', 'get, store or erase (git calls this)')
287
332
  .option('--checkout <root>', 'the root of the story checkout')
288
333
  .option('--snapshot <root>', 'the root of the project snapshot')
334
+ .option('--project-main <url>', 'read-only project main remote used by pull --from-main')
289
335
  .requiredOption('--codebase <codebase>', 'the codebase of this repository')
290
336
  .description('The git credential helper of a kodly checkout or project snapshot')
291
337
  .action(run(async (operation, options, command) => {
@@ -312,6 +358,22 @@ export const codeCommands = (program, cliVersion) => {
312
358
  const codebase = context.codebases.find((c) => c.codebase === options.codebase);
313
359
  if (!codebase)
314
360
  throw new CliError(`The checkout has no codebase ${options.codebase}.`);
361
+ if (options.projectMain) {
362
+ const remote = new URL(options.projectMain);
363
+ const localHttp = remote.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(remote.hostname);
364
+ if (!fields.host || remote.protocol !== `${fields.protocol}:` || (remote.protocol !== 'https:' && !localHttp)
365
+ || !isPushRequest(fields, options.projectMain)) {
366
+ throw new CliError('Project main credentials are only available to the published repository.');
367
+ }
368
+ const api = checkoutApi(command, cliVersion, context);
369
+ const heads = await api.request(projectPath(context.project, '/code/main'));
370
+ if (!heads.some(head => head.codebase === codebase.codebase && head.remote === options.projectMain)) {
371
+ throw new CliError('This is not the published project main repository.');
372
+ }
373
+ const token = await api.request(projectPath(context.project, '/code/credentials/read'), { method: 'POST', body: { codebase: codebase.codebase }, quiet: true });
374
+ process.stdout.write(`username=${token.username}\npassword=${token.password}\n`);
375
+ return;
376
+ }
315
377
  const push = isPushRequest(fields, codebase.pushRemote);
316
378
  const api = checkoutApi(command, cliVersion, context);
317
379
  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 });
@@ -319,8 +381,9 @@ export const codeCommands = (program, cliVersion) => {
319
381
  }));
320
382
  program
321
383
  .command('pull')
384
+ .option('--from-main', 'merge published project main into the local story before pushing')
322
385
  .description('Bring the latest story code into the checkout, or the latest main into a project snapshot (fast-forward only)')
323
- .action(run(async (_options, command) => {
386
+ .action(run(async (options, command) => {
324
387
  const json = command.optsWithGlobals().json === true;
325
388
  const folder = findFolder();
326
389
  if (folder?.kind === 'project') {
@@ -332,19 +395,26 @@ export const codeCommands = (program, cliVersion) => {
332
395
  }
333
396
  const { root, context } = findCheckout();
334
397
  const api = checkoutApi(command, cliVersion, context);
398
+ if (options.fromMain) {
399
+ const rows = await pullProjectMain(api, root, context);
400
+ emit(json, rows, () => table(rows.map(r => [r.codebase, r.result])));
401
+ return;
402
+ }
335
403
  const rows = [];
336
404
  for (const codebase of context.codebases) {
337
405
  const dir = path.join(root, codebase.dir);
338
406
  await git(dir, ['fetch', '--quiet', 'origin', 'main']);
339
407
  const merged = await gitTry(dir, ['merge', '--ff-only', '--quiet', 'origin/main']);
340
- const files = await storyGenerated(api, context, codebase.codebase);
341
- const conflicts = await generatedConflicts(dir, files, codebase.generated, 'HEAD');
342
- if (conflicts.length) {
343
- rows.push({ codebase: codebase.codebase, result: `generated files not written: ${conflicts.join('; ')}. Move these files, then run kodly pull again` });
408
+ const syncedMain = context.mainCommits?.[codebase.codebase];
409
+ const files = syncedMain ? await snapshotGenerated(api, context, codebase.codebase, syncedMain)
410
+ : await storyGenerated(api, context, codebase.codebase);
411
+ const found = await generatedConflicts(dir, files, codebase.generated, 'HEAD');
412
+ if (blocking(found).length) {
413
+ rows.push({ codebase: codebase.codebase, result: `generated files not written: ${blocking(found).join('; ')}. Move these files, then run kodly pull again` });
344
414
  continue;
345
415
  }
346
416
  try {
347
- await applyGenerated(dir, files, codebase.generated);
417
+ await applyGenerated(dir, withoutMain(files, found), codebase.generated);
348
418
  }
349
419
  finally {
350
420
  // Save after each codebase, also when a write fails, so story.json names the files that kodly wrote.
@@ -1,9 +1,11 @@
1
1
  import chalk from 'chalk';
2
2
  import { Option } from 'commander';
3
3
  import { spawnSync } from 'node:child_process';
4
+ import fs from 'node:fs';
5
+ import os from 'node:os';
4
6
  import path from 'node:path';
5
7
  import { checkoutOf } from '../core/checkout.js';
6
- import { DEFAULT_API_URL } from '../core/config.js';
8
+ import { DEFAULT_API_URL, settings } from '../core/config.js';
7
9
  import { buildContext } from '../core/context.js';
8
10
  import { CliError } from '../core/errors.js';
9
11
  import { emit, run } from '../core/output.js';
@@ -13,29 +15,88 @@ export const mcpCommand = (apiUrl) => {
13
15
  const self = process.argv[1] ? [process.execPath, path.resolve(process.argv[1])] : ['kodly'];
14
16
  return [...self, ...(apiUrl === DEFAULT_API_URL ? [] : ['--api', apiUrl]), 'mcp'];
15
17
  };
18
+ /** The agent tools that `kodly harness install` sets up, with the name that people know. */
19
+ const TOOLS = { claude: 'Claude Code', codex: 'Codex', opencode: 'OpenCode', antigravity: 'Antigravity', other: 'your agent tool' };
20
+ /**
21
+ * The next step of a flow in the saved agent tool (claude when none is saved). `prompt` is the Claude Code
22
+ * prompt, as in CLI 2.1. `instruction` is what the user types in the tool. `lines` are the lines to print.
23
+ * A tool that has no MCP prompts gets a sentence that names the flow_instructions tool.
24
+ */
25
+ export const nextStep = (tool, flow, story) => {
26
+ const prompt = `/mcp__kodly__${flow} ${story}`;
27
+ if (!tool || tool === 'claude')
28
+ return { prompt, instruction: prompt, lines: [`claude "${prompt}"`] };
29
+ if (tool === 'opencode')
30
+ return { prompt, instruction: `/kodly:${flow} ${story}`, lines: ['opencode', `Then type: /kodly:${flow} ${story}`] };
31
+ const instruction = `Call the kodly tool flow_instructions with flow "${flow}" and story "${story}", then follow the instructions.`;
32
+ return { prompt, instruction, lines: [`Start ${TOOLS[tool] ?? tool}, then send: ${instruction}`] };
33
+ };
34
+ /**
35
+ * Adds the kodly server to the global MCP file of Antigravity, and returns the file. It keeps the other
36
+ * servers and keys. It refuses a file that is not a JSON object, so it never loses a setting.
37
+ */
38
+ const installAntigravity = (command, args) => {
39
+ const file = path.join(os.homedir(), '.gemini', 'config', 'mcp_config.json');
40
+ const object = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
41
+ let config = {};
42
+ if (fs.existsSync(file)) {
43
+ let parsed;
44
+ try {
45
+ parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
46
+ }
47
+ catch {
48
+ parsed = undefined;
49
+ }
50
+ if (!object(parsed) || (parsed.mcpServers !== undefined && !object(parsed.mcpServers))) {
51
+ throw new CliError(`${file} is not valid JSON with an "mcpServers" object. Correct it, then run kodly harness install --tool antigravity again.`);
52
+ }
53
+ config = parsed;
54
+ }
55
+ config.mcpServers = { ...config.mcpServers, kodly: { command, args } };
56
+ fs.mkdirSync(path.dirname(file), { recursive: true });
57
+ // The mode applies to a new file only. An existing file keeps its mode.
58
+ fs.writeFileSync(file, JSON.stringify(config, null, 2) + '\n', { mode: 0o600 });
59
+ return file;
60
+ };
16
61
  export const harnessCommands = (program, cliVersion) => {
17
62
  const harness = program.command('harness').description('Connect your local agent tool to Kodly');
18
63
  harness
19
64
  .command('install')
20
- .addOption(new Option('--tool <tool>', 'the agent tool').choices(['claude', 'other']).default('claude'))
65
+ .addOption(new Option('--tool <tool>', 'the agent tool').choices(Object.keys(TOOLS)).default('claude'))
21
66
  .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')
67
+ .description('Register the Kodly MCP server with Claude Code, Codex, OpenCode or Antigravity, or print the setting for another tool')
23
68
  .action(run(async (options, command) => {
24
69
  const ctx = buildContext(command, cliVersion);
25
70
  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' });
71
+ const name = TOOLS[options.tool];
72
+ // OpenCode: --global writes the config of the user, for every project.
73
+ const add = {
74
+ claude: ['mcp', 'add', '--scope', options.scope, 'kodly', '--', executable, ...args],
75
+ codex: ['mcp', 'add', 'kodly', '--', executable, ...args],
76
+ opencode: ['mcp', 'add', '--global', 'kodly', '--', executable, ...args],
77
+ };
78
+ if (add[options.tool]) {
79
+ const result = spawnSync(options.tool, add[options.tool], { stdio: 'inherit' });
28
80
  if (result.error)
29
- throw new CliError('Claude Code is not on the PATH. Install it, or use --tool other.');
81
+ throw new CliError(`${name} is not on the PATH. Install it, or use --tool other.`);
30
82
  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>')));
83
+ throw new CliError(`${options.tool} mcp add failed. See its message above.`);
84
+ }
85
+ const file = options.tool === 'antigravity' ? installAntigravity(executable, args) : undefined;
86
+ settings().set('agentTool', options.tool);
87
+ if (options.tool === 'other') {
88
+ const setting = { mcpServers: { kodly: { command: executable, args } } };
89
+ emit(ctx.json, setting, () => {
90
+ console.log('Add this MCP server to your agent tool:');
91
+ console.log(JSON.stringify(setting, null, 2));
92
+ });
33
93
  return;
34
94
  }
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));
95
+ const step = nextStep(options.tool, 'implement', '<story>');
96
+ emit(ctx.json, { tool: options.tool, ...(options.tool === 'claude' ? { scope: options.scope } : {}), ...(file ? { file } : {}) }, () => {
97
+ console.log(chalk.green(`${name} can now use Kodly${file ? ` (${file})` : ''}. In a checkout:`));
98
+ for (const line of step.lines)
99
+ console.log(` ${line}`);
39
100
  });
40
101
  }));
41
102
  program
@@ -57,12 +118,14 @@ export const harnessCommands = (program, cliVersion) => {
57
118
  root = created.root;
58
119
  identifier = created.item.identifier ?? created.item.slug;
59
120
  }
60
- emit(ctx.json, { root, prompt: `/mcp__kodly__implement ${identifier}` }, () => {
121
+ const step = nextStep(settings().get('agentTool'), 'implement', identifier);
122
+ emit(ctx.json, { root, prompt: step.prompt, instruction: step.instruction }, () => {
61
123
  console.log(`The code of ${identifier} is in ${root}.`);
62
124
  console.log('Next:');
63
125
  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.'));
126
+ for (const line of step.lines)
127
+ console.log(` ${line}`);
128
+ console.log(chalk.dim('Run "kodly harness install --tool <tool>" once, so that your agent tool knows the Kodly tools.'));
66
129
  });
67
130
  }));
68
131
  };
@@ -2,12 +2,14 @@ import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import chalk from 'chalk';
4
4
  import { checkoutOf } from '../core/checkout.js';
5
+ import { settings } from '../core/config.js';
5
6
  import { buildContext } from '../core/context.js';
6
7
  import { CliError, ExitCode } from '../core/errors.js';
7
8
  import { projectPath, storyPath, table } from '../core/format.js';
8
9
  import { emit, run } from '../core/output.js';
9
10
  import { confirm } from '../core/prompt.js';
10
11
  import { blockedReasons, deliveryOf, findStory, requireBuild } from '../core/story.js';
12
+ import { nextStep } from './harness.js';
11
13
  import { QA_FILES_DIR } from './mcp.js';
12
14
  import { requireCurrentCheckout } from './review.js';
13
15
  const LOCAL_MODEL = 'kodly/local-qa';
@@ -43,11 +45,13 @@ export const localQaCommands = (qa, cliVersion) => {
43
45
  await ctx.api.request(storyPath(project, item.slug, '/delivery/handoffs'), { method: 'POST', body: { destination: 'QA', buildId: build.id, mode: 'LOCAL' } });
44
46
  }
45
47
  fs.mkdirSync(path.join(found.root, QA_FILES_DIR), { recursive: true });
46
- emit(ctx.json, { root: found.root, qaFiles: path.join(found.root, QA_FILES_DIR), prompt: `/mcp__kodly__qa ${name}` }, () => {
48
+ const step = nextStep(settings().get('agentTool'), 'qa', name);
49
+ emit(ctx.json, { root: found.root, qaFiles: path.join(found.root, QA_FILES_DIR), prompt: step.prompt, instruction: step.instruction }, () => {
47
50
  console.log(`${name} is in local QA. Kodly starts no sandbox QA run for this build.`);
48
51
  console.log('Next:');
49
52
  console.log(` cd ${found.root}`);
50
- console.log(` claude "/mcp__kodly__qa ${name}"`);
53
+ for (const line of step.lines)
54
+ console.log(` ${line}`);
51
55
  console.log(`Then accept the results: kodly qa accept ${name}`);
52
56
  });
53
57
  }));