@kodly.dev/kodly-cli 2.2.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
@@ -78,6 +78,7 @@ kodly doctor
78
78
  kodly checkout KOD-12 # one git repository for each codebase, under ./KOD-12/
79
79
  cd "KOD-12/Web app" # each codebase folder has the codebase name
80
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
81
82
  kodly push # sends your commits as a new build; Kodly runs the build checks in its sandbox
82
83
  kodly watch KOD-12
83
84
  kodly qa send KOD-12 # when the checks pass
@@ -93,7 +94,9 @@ kodly diff
93
94
  - When a local file that git does not track is at a generated path, Kodly keeps it, writes no generated
94
95
  file of that codebase and exits with code 4. Move the file, then run `kodly pull`.
95
96
  - git asks Kodly for a one-hour token each time it needs one. No token goes into a file.
96
- - `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
97
100
  than 8 MiB, files that look like secrets (`.env`, keys), generated files and `Kodly-` trailers.
98
101
  - QA runs in the Kodly sandbox. When a project admin turns on local QA (`kodly project local-qa on`),
99
102
  `kodly qa local` runs it with your agent instead, and the results count only after a person runs
@@ -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
@@ -42,11 +43,6 @@ const namesOf = async (api, project) => {
42
43
  throw error;
43
44
  }
44
45
  };
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, "'\\''")}'`;
50
46
  /** The API client of a checkout: the API, the organisation and the project that the checkout names. */
51
47
  const checkoutApi = (command, cliVersion, context) => checkoutApiFor(buildContext(command, cliVersion).api.session, context);
52
48
  /**
@@ -132,20 +128,27 @@ export const checkoutStory = async (ctx, id, dir) => {
132
128
  * import them as a new build. `kodly push` and the push tool of `kodly mcp` both use it.
133
129
  */
134
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);
135
133
  const commits = {};
134
+ const unchanged = {};
136
135
  const problems = [];
137
136
  for (const codebase of context.codebases) {
138
137
  const dir = path.join(root, codebase.dir);
139
138
  await git(dir, ['fetch', '--quiet', 'origin', 'main']);
140
- const plan = await checkPush(dir, codebase.codebase, codebase.generated);
139
+ const plan = await checkPush(dir, codebase.codebase, codebase.generated, context.mainCommits?.[codebase.codebase]);
141
140
  problems.push(...plan.problems);
142
141
  if (plan.head)
143
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();
144
145
  }
145
146
  if (problems.length)
146
147
  throw new CliError(`The push stops:\n ${problems.join('\n ')}`, ExitCode.USAGE);
147
148
  if (Object.keys(commits).length === 0)
148
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);
149
152
  // A story with a build pushes on it. A first push builds on the story base that the checkout started from.
150
153
  const build = (await deliveryOf(api, context.project, context.story)).build;
151
154
  const baseBuildId = build?.id ?? context.baseBuildId;
@@ -156,9 +159,15 @@ export const pushCheckout = async (api, root, context, options) => {
156
159
  const dir = path.join(root, context.codebases.find((c) => c.codebase === codebase).dir);
157
160
  await git(dir, ['push', '--quiet', 'origin', `${head}:refs/kodly/cli/${pushId}`]);
158
161
  }
159
- const result = await api.request(storyPath(context.project, context.story, '/code/pushes'), {
160
- 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 },
161
166
  });
167
+ if (context.mainCommits) {
168
+ delete context.mainCommits;
169
+ writeContext(root, context);
170
+ }
162
171
  return { commits, result };
163
172
  };
164
173
  /** The push URL of a snapshot repository. It is not a URL, so git push stops before it asks for a token. */
@@ -322,6 +331,7 @@ export const codeCommands = (program, cliVersion) => {
322
331
  .argument('<operation>', 'get, store or erase (git calls this)')
323
332
  .option('--checkout <root>', 'the root of the story checkout')
324
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')
325
335
  .requiredOption('--codebase <codebase>', 'the codebase of this repository')
326
336
  .description('The git credential helper of a kodly checkout or project snapshot')
327
337
  .action(run(async (operation, options, command) => {
@@ -348,6 +358,22 @@ export const codeCommands = (program, cliVersion) => {
348
358
  const codebase = context.codebases.find((c) => c.codebase === options.codebase);
349
359
  if (!codebase)
350
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
+ }
351
377
  const push = isPushRequest(fields, codebase.pushRemote);
352
378
  const api = checkoutApi(command, cliVersion, context);
353
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 });
@@ -355,8 +381,9 @@ export const codeCommands = (program, cliVersion) => {
355
381
  }));
356
382
  program
357
383
  .command('pull')
384
+ .option('--from-main', 'merge published project main into the local story before pushing')
358
385
  .description('Bring the latest story code into the checkout, or the latest main into a project snapshot (fast-forward only)')
359
- .action(run(async (_options, command) => {
386
+ .action(run(async (options, command) => {
360
387
  const json = command.optsWithGlobals().json === true;
361
388
  const folder = findFolder();
362
389
  if (folder?.kind === 'project') {
@@ -368,12 +395,19 @@ export const codeCommands = (program, cliVersion) => {
368
395
  }
369
396
  const { root, context } = findCheckout();
370
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
+ }
371
403
  const rows = [];
372
404
  for (const codebase of context.codebases) {
373
405
  const dir = path.join(root, codebase.dir);
374
406
  await git(dir, ['fetch', '--quiet', 'origin', 'main']);
375
407
  const merged = await gitTry(dir, ['merge', '--ff-only', '--quiet', 'origin/main']);
376
- const files = await storyGenerated(api, context, codebase.codebase);
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);
377
411
  const found = await generatedConflicts(dir, files, codebase.generated, 'HEAD');
378
412
  if (blocking(found).length) {
379
413
  rows.push({ codebase: codebase.codebase, result: `generated files not written: ${blocking(found).join('; ')}. Move these files, then run kodly pull again` });
@@ -42,7 +42,7 @@ export const IMPLEMENT_PROMPT = (story) => [
42
42
  KNOWLEDGE,
43
43
  '2. Implement the approved plan. Keep to the plan steps and to the acceptance criteria.',
44
44
  '3. Build the project and run its tests on this machine.',
45
- '4. Commit your changes with clear messages. Do not push with git.',
45
+ '4. Commit your changes with clear messages. If project main has moved, run kodly pull --from-main and resolve any conflicts locally. Do not push with git.',
46
46
  '5. Ask me before you call the push tool. After the push, Kodly runs the build checks and QA in its sandbox.',
47
47
  '6. Call report_usage with your model and your token counts, if you know them.',
48
48
  'Never approve, review, release or merge. Those steps are mine, in the Kodly web app.',
@@ -318,7 +318,12 @@ export const mcpCommands = (program, cliVersion) => {
318
318
  }, async ({ model, harness }) => tool(async () => {
319
319
  if (!checkout)
320
320
  throw new CliError('Run the agent inside a kodly checkout to push.');
321
- return (await pushCheckout(api, checkout.root, checkout.context, { model, harness: harness ?? 'mcp' })).result;
321
+ const { context } = findCheckout(checkout.root);
322
+ const original = checkout.context;
323
+ if (context.api !== original.api || context.org !== original.org || context.project !== original.project || context.story !== original.story) {
324
+ throw new CliError('The checkout changed. Restart Kodly MCP in this checkout.');
325
+ }
326
+ return (await pushCheckout(api, checkout.root, context, { model, harness: harness ?? 'mcp' })).result;
322
327
  })());
323
328
  server.registerTool('report_usage', {
324
329
  title: 'Report model use',
@@ -0,0 +1,68 @@
1
+ import path from 'node:path';
2
+ import { insideDir, writeContext } from './checkout.js';
3
+ import { CliError, ExitCode } from './errors.js';
4
+ import { projectPath } from './format.js';
5
+ import { applyGenerated, generatedConflicts } from './generated-files.js';
6
+ import { git, gitTry } from './git.js';
7
+ export const shellWord = (value) => "'" + value.replace(/'/g, "'\\''") + "'";
8
+ /** Merge published project history into the local story. The ordinary origin and its push URL always remain the story's. */
9
+ export const pullProjectMain = async (api, root, context) => {
10
+ const heads = await api.request(projectPath(context.project, '/code/main'));
11
+ const updates = context.codebases.map(cb => {
12
+ const head = heads.find(h => h.codebase === cb.codebase);
13
+ if (!head?.remote || !head.commit || !/^[0-9a-f]{40}$/.test(head.commit)) {
14
+ throw new CliError(`${cb.codebase}: published project main is unavailable.`, ExitCode.CONFLICT);
15
+ }
16
+ return { cb, dir: insideDir(root, cb.dir), remote: head.remote, commit: head.commit };
17
+ });
18
+ for (const { cb, dir } of updates) {
19
+ if (await gitTry(dir, ['symbolic-ref', '--quiet', 'HEAD']) === null
20
+ || await gitTry(dir, ['rev-parse', '--verify', 'MERGE_HEAD']) !== null
21
+ || (await git(dir, ['status', '--porcelain', '--untracked-files=no'])).trim()) {
22
+ throw new CliError(`${cb.dir}: finish your Git operation and commit or stash local edits before running kodly pull --from-main.`, ExitCode.CONFLICT);
23
+ }
24
+ await git(dir, ['fetch', '--quiet', 'origin', 'main']);
25
+ if (await gitTry(dir, ['merge-base', '--is-ancestor', 'origin/main', 'HEAD']) === null) {
26
+ throw new CliError(`${cb.dir}: the story fork has changed. Run kodly pull and integrate the saved story before syncing project main.`, ExitCode.CONFLICT);
27
+ }
28
+ }
29
+ // Partial syncs (including a manually resolved conflict) can be retried. A push must have one complete set of revisions.
30
+ delete context.mainCommits;
31
+ context.mainSyncPending = true;
32
+ writeContext(root, context);
33
+ const mainCommits = {};
34
+ for (const { cb, dir, remote, commit } of updates) {
35
+ const self = [process.execPath, path.resolve(process.argv[1])].map(shellWord).join(' ');
36
+ const helper = `!${self} git-credential --checkout ${shellWord(root)} --codebase ${shellWord(cb.codebase)} --project-main ${shellWord(remote)}`;
37
+ await git(dir, ['-c', 'credential.helper=', '-c', 'credential.helper=' + helper, '-c', 'credential.useHttpPath=true',
38
+ 'fetch', '--quiet', '--no-tags', '--', remote, 'refs/heads/main']);
39
+ if (await gitTry(dir, ['rev-parse', 'FETCH_HEAD']) !== commit) {
40
+ throw new CliError(`${cb.dir}: project main changed during the fetch. Run kodly pull --from-main again.`, ExitCode.CONFLICT);
41
+ }
42
+ const files = (await api.request(projectPath(context.project, '/code/generated'), { query: { codebase: cb.codebase, commit } })) ?? [];
43
+ try {
44
+ await git(dir, ['merge', '--no-edit', '--no-overwrite-ignore', '--ff', commit]);
45
+ }
46
+ catch (error) {
47
+ if (await gitTry(dir, ['rev-parse', '--verify', 'MERGE_HEAD']) === null)
48
+ throw error;
49
+ throw new CliError(`${cb.dir}: resolve the Git conflicts and run git merge --continue, or use git merge --abort. Then run kodly pull --from-main again.`, ExitCode.CONFLICT);
50
+ }
51
+ const found = await generatedConflicts(dir, files, cb.generated, 'HEAD');
52
+ const conflicts = found.filter(f => f.kind !== 'main');
53
+ if (conflicts.length)
54
+ throw new CliError(`${cb.dir}: ${conflicts.map(f => f.message).join(', ')}. Move the local files and repeat kodly pull --from-main.`, ExitCode.CONFLICT);
55
+ const tracked = new Set(found.map(f => f.path));
56
+ try {
57
+ await applyGenerated(dir, files.filter(f => !tracked.has(f.path)), cb.generated);
58
+ }
59
+ finally {
60
+ writeContext(root, context);
61
+ }
62
+ mainCommits[cb.codebase] = commit;
63
+ }
64
+ context.mainCommits = mainCommits;
65
+ delete context.mainSyncPending;
66
+ writeContext(root, context);
67
+ return updates.map(({ cb, commit }) => ({ codebase: cb.codebase, result: `project main ${commit.slice(0, 12)} integrated` }));
68
+ };
@@ -13,7 +13,7 @@ export const blobId = (bytes) => createHash('sha1').update(`blob ${bytes.length}
13
13
  * problem found here costs no upload. `generated` maps each generated path that git must not hold
14
14
  * to the blob id of its generated bytes.
15
15
  */
16
- export const checkPush = async (dir, codebase, generated) => {
16
+ export const checkPush = async (dir, codebase, generated, main) => {
17
17
  const problems = [];
18
18
  const dirty = (await git(dir, ['status', '--porcelain', '--untracked-files=no'])).trim();
19
19
  if (dirty)
@@ -22,21 +22,35 @@ export const checkPush = async (dir, codebase, generated) => {
22
22
  problems.push(`${codebase}: your commits do not build on the story code. Run kodly pull, then rebase your commits.`);
23
23
  return { head: null, commits: 0, problems };
24
24
  }
25
- const commits = Number((await git(dir, ['rev-list', '--count', 'origin/main..HEAD'])).trim());
26
- if (commits === 0)
25
+ if (main && (!/^[0-9a-f]{40}$/.test(main) || await gitTry(dir, ['merge-base', '--is-ancestor', main, 'HEAD']) === null)) {
26
+ problems.push(`${codebase}: run kodly pull --from-main to finish integrating project main before pushing.`);
27
27
  return { head: null, commits: 0, problems };
28
+ }
29
+ const range = ['HEAD', '^origin/main', ...(main ? ['^' + main] : [])];
30
+ const commits = Number((await git(dir, ['rev-list', '--count', ...range])).trim());
31
+ const head = (await git(dir, ['rev-parse', 'HEAD'])).trim();
32
+ if (commits === 0 && (!main || head !== main || head === (await git(dir, ['rev-parse', 'origin/main'])).trim())) {
33
+ return { head: null, commits: 0, problems };
34
+ }
28
35
  if (commits > MAX_COMMITS)
29
36
  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.`);
37
+ const merges = (await git(dir, ['rev-list', '--merges', '--parents', ...range])).trim();
38
+ for (const line of merges ? merges.split('\n') : []) {
39
+ const [, first, second, extra] = line.split(' ');
40
+ if (!main || extra || await gitTry(dir, ['merge-base', '--is-ancestor', second, main]) === null
41
+ || await gitTry(dir, ['merge-base', '--is-ancestor', 'origin/main', first]) === null) {
42
+ problems.push(`${codebase}: your commits include a merge outside the story and its synced project main. Run kodly pull --from-main to integrate project main.`);
43
+ break;
44
+ }
32
45
  }
33
- if (/^Kodly-[A-Za-z-]+:/m.test(await git(dir, ['log', '--format=%B', 'origin/main..HEAD']))) {
46
+ if (/^Kodly-[A-Za-z-]+:/m.test(await git(dir, ['log', '--format=%B', ...range]))) {
34
47
  problems.push(`${codebase}: a commit message has a Kodly- trailer. Only Kodly writes these.`);
35
48
  }
36
49
  // The secret rule reads only the paths that the commits add or change. The story code can hold a
37
50
  // file such as a scaffolded .env.dev, and that file is not part of this push.
38
51
  const changed = new Set((await git(dir, ['diff', '--name-only', '-z', '--no-renames', '--diff-filter=AM', 'origin/main', 'HEAD']))
39
52
  .split('\0').filter(Boolean));
53
+ const changedFromMain = main ? new Set((await git(dir, ['diff', '--name-only', '-z', '--no-renames', main, 'HEAD'])).split('\0')) : changed;
40
54
  for (const line of (await git(dir, ['ls-tree', '-r', '-l', '-z', 'HEAD'])).split('\0').filter(Boolean)) {
41
55
  const [meta, path] = line.split('\t');
42
56
  const [mode, , sha, size] = meta.split(/\s+/);
@@ -48,13 +62,12 @@ export const checkPush = async (dir, codebase, generated) => {
48
62
  problems.push(`${codebase}: ${path} is larger than 8 MiB.`);
49
63
  if (PLATFORM.test(path))
50
64
  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)) {
65
+ if (changed.has(path) && changedFromMain.has(path) && SECRET.some((pattern) => pattern.test(path)) && !SECRET_OK.test(path)) {
52
66
  problems.push(`${codebase}: ${path} looks like a secret. Remove it from git, and keep secrets in the Kodly project settings.`);
53
67
  }
54
68
  if (generated[path] && generated[path] === sha) {
55
69
  problems.push(`${codebase}: ${path} is a generated file. Remove it from git; kodly checkout writes it.`);
56
70
  }
57
71
  }
58
- const head = (await git(dir, ['rev-parse', 'HEAD'])).trim();
59
72
  return { head, commits, problems };
60
73
  };
package/llm.txt CHANGED
@@ -36,7 +36,7 @@ Node.js 20 or later is necessary.
36
36
  2. Get the context: the `story_context` tool, or `kodly --json story show KOD-12` and `kodly --json plan show KOD-12`.
37
37
  3. Implement the approved plan. Keep to its steps and to the acceptance criteria.
38
38
  4. Build the project and run its tests locally. The generated files are already in the checkout; git ignores them. Do not commit them.
39
- 5. Commit with clear messages. No merge commits, and no `Kodly-` trailers in messages.
39
+ 5. Commit with clear messages. To incorporate published project main, run `kodly pull --from-main` before pushing. Resolve conflicts locally. Only merges of verified project main are accepted. Reserve `Kodly-` trailers for the platform.
40
40
  6. Ask the developer, then `kodly push` (or the `push` tool). Do not commit secrets: a push with a `.env` or key file stops.
41
41
  7. `kodly watch KOD-12` until the build checks end. Then `kodly qa send KOD-12`.
42
42
  8. Report your model use with the `report_usage` tool, or `kodly push --model <model> --harness <tool>`. Kodly stores it and never bills it.
@@ -50,7 +50,7 @@ Node.js 20 or later is necessary.
50
50
  - Cloud runs: `kodly run build <story> [--checks-only]`, `kodly run test <story>`, `kodly runs <story>`, `kodly watch <story>`
51
51
  - Checks and QA: `kodly checks show|logs <story>`, `kodly qa send|show <story>`, `kodly qa local|accept <story>`, `kodly qa triage <story> --category <c> --reason <text>`
52
52
  - Review and release: `kodly review request|show|local|comment|reply|approve|request-changes <story>`, `kodly release <story>`, `kodly brief <story>`
53
- - Code: `kodly checkout <story>`, `kodly project checkout [--codebase <slug>] [--dir <path>]`, `kodly pull`, `kodly push`, `kodly status`, `kodly diff`
53
+ - Code: `kodly checkout <story>`, `kodly project checkout [--codebase <slug>] [--dir <path>]`, `kodly pull [--from-main]`, `kodly push`, `kodly status`, `kodly diff`
54
54
  - Local agents: `kodly mcp`, `kodly implement <story>`, `kodly harness install [--tool claude|codex|opencode|antigravity|other]`
55
55
  - Scaffolding (no login): `kodly scaffold list [--json]|create|init|<recipe>@<version>`
56
56
  - Options: `--api <url>`, `--org <slug>`, `--project <slug>` (these take the slug only), `--json`, `--no-browser`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kodly.dev/kodly-cli",
3
- "version": "2.2.0",
3
+ "version": "2.3.0",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "kodly": "./dist/bin/kodly.js"