agjan 0.0.13 → 0.0.15

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
@@ -7,8 +7,9 @@
7
7
 
8
8
  # agjan
9
9
 
10
- Spec-driven workflow kit for AI coding agents, with human approval gates and a
11
- read-only reviewer at every step.
10
+ An agentic engineering harness. It runs AI coding agents like an engineering team (a
11
+ main agent, an independent reviewer and a QA tester) under your approval gates and
12
+ checks that CI enforces. Spec-driven, starting with SAP BTP: CAP, Fiori elements and UI5.
12
13
 
13
14
  > **Status: closed beta (0.x).** The source repository is not public yet; it will open
14
15
  > soon. Until then, links to the repository and to other documents do not work on npm;
@@ -51,11 +52,19 @@ Requirements: Node.js 22 or later, git, and Claude Code and/or the GitHub Copilo
51
52
  Linux, macOS or Windows.
52
53
 
53
54
  ```sh
54
- npm install --save-dev agjan
55
- npx agjan init --hosts claude-code,copilot
56
- npx agjan doctor
55
+ npm install --global agjan
56
+ agjan init my-project --hosts claude-code,copilot # or "agjan init ." in an existing folder
57
+ cd my-project
58
+ agjan doctor
57
59
  ```
58
60
 
61
+ `agjan init my-project` creates the folder, the git repository (branch `main`) and a
62
+ `package.json`, pins this version of agjan in its `devDependencies` and installs it, then
63
+ sets the project up. Without `--hosts` it asks which hosts to set up. The global `agjan`
64
+ only starts things: `init`, `--help` and `--version` run in it, and every other command
65
+ runs in the version the project pins, so a project never depends on the global version.
66
+ After cloning a project, the first command offers to install the pinned version.
67
+
59
68
  Open the project in your agent host, trust the folder, and start a feature:
60
69
 
61
70
  ```text
package/bin/agjan.mjs CHANGED
@@ -5,8 +5,16 @@ import { existsSync } from 'node:fs';
5
5
  // In the agjan repository Node runs the TypeScript sources directly; the npm package
6
6
  // ships them compiled to dist/ (Node does not strip types inside node_modules).
7
7
  const source = new URL('../src/cli.ts', import.meta.url);
8
+ const load = (/** @type {string} */ name) => (existsSync(source) ? new URL(`../src/${name}.ts`, import.meta.url) : new URL(`../dist/${name}.js`, import.meta.url)).href;
9
+
10
+ // The global agjan only launches: project commands run in the version the project pins.
11
+ /** @type {typeof import('../src/launcher.ts')} */
12
+ const { launch } = await import(load('launcher'));
13
+ const launched = await launch(process.argv.slice(2));
14
+ if ('code' in launched) process.exit(launched.code);
15
+
8
16
  /** @type {typeof import('../src/cli.ts')} */
9
- const { main } = await import(existsSync(source) ? source.href : new URL('../dist/cli.js', import.meta.url).href);
17
+ const { main } = await import(load('cli'));
10
18
 
11
19
  // A reader that stops early (`agjan status | head`) is not an error.
12
20
  for (const stream of [process.stdout, process.stderr]) {
@@ -16,4 +24,4 @@ for (const stream of [process.stdout, process.stderr]) {
16
24
  });
17
25
  }
18
26
 
19
- process.exitCode = await main(process.argv.slice(2));
27
+ process.exitCode = await main(launched.run);
@@ -90,7 +90,7 @@ function reviewerAgent(name, tier, model, skill) {
90
90
  'review of a step; it records its result itself.',
91
91
  tools: 'Read, Grep, Glob, mcp__agjan__review_context, mcp__agjan__review_record',
92
92
  ...(model ? { model } : {}),
93
- // Scoped to this agent only: the writer session must not have review_record.
93
+ // Scoped to this agent only: the main agent session must not have review_record.
94
94
  mcpServers: [
95
95
  {
96
96
  agjan: {
@@ -56,7 +56,7 @@ function reviewerAgent(name, tier, model, skill) {
56
56
  'review of a step; it records its result itself.',
57
57
  tools: ['read', 'search', 'agjan/review_context', 'agjan/review_record'],
58
58
  ...(model ? { model } : {}),
59
- // Scoped to this agent only: the writer session must not have review_record.
59
+ // Scoped to this agent only: the main agent session must not have review_record.
60
60
  'mcp-servers': {
61
61
  agjan: {
62
62
  type: 'local',
package/dist/cli.js CHANGED
@@ -49,22 +49,28 @@ const COMMANDS = {
49
49
  };
50
50
  const HELP = `agjan ${pkg.version}
51
51
 
52
- Spec-driven workflow kit for AI coding agents, with human approval gates
53
- and a read-only reviewer at every step. Closed beta (0.x); the user guide is\nin this package: docs/guide.md
52
+ Agentic engineering harness for AI coding agents: role agents (main agent,
53
+ reviewer, QA), human approval gates and CI-enforced checks. SAP BTP first.
54
+ Closed beta (0.x); the user guide is in this package: docs/guide.md
54
55
 
55
56
  Usage: agjan <command> [options]
56
57
 
57
58
  Setup (human):
58
- init [--domains btp] [--hosts claude-code,copilot] [--base <ref>]
59
+ init <folder | .> [--hosts claude-code,copilot] [--domains btp] [--base <ref>]
59
60
  [--no-hook] [--no-ci] [--prepare] [--copilot-mcp | --no-copilot-mcp]
60
- set up agjan in this repository
61
+ [--commit | --no-commit] [--no-install] [--pm npm|pnpm|yarn|bun] [--dry-run]
62
+ set up agjan: <folder> is created (git init, package.json,
63
+ agjan pinned and installed), . is the current folder; without
64
+ --hosts it asks which hosts (claude-code, copilot) to set up,
65
+ and at the end whether to commit the setup (a new repository:
66
+ on main; else on chore/set-up-agjan)
61
67
  sync [--force] [--copilot-mcp]
62
68
  regenerate managed files (skills, agents, blocks, settings);
63
69
  --copilot-mcp adds missing MCP servers to Copilot
64
70
  hook install install the pre-commit hook
65
71
  models [set <balanced|deep|qa> <model> [--host <h>]]
66
72
  show the reviewers' models, or choose one (the deep reviewer
67
- on another model family than the writer catches other things)
73
+ on another model family than the main agent catches other things)
68
74
  doctor check the environment and the project setup
69
75
 
70
76
  Agent and human:
@@ -117,6 +123,9 @@ Human only, in a terminal:
117
123
 
118
124
  Other:
119
125
  --version, --help
126
+ --yes <command> install the project's pinned agjan without asking, then run
127
+ the command (the global agjan runs project commands in the
128
+ version the project pins in node_modules)
120
129
  `;
121
130
  /**
122
131
  * Runs the CLI and returns the process exit code.
@@ -378,7 +378,19 @@ export async function auto(ctx, argv) {
378
378
  throw new UsageError(usage);
379
379
  return autoDefault(ctx, what === 'on');
380
380
  }
381
- const feature = loadFeature(ctx.root, selectFeature(ctx.root, ctx.config, values.feature));
381
+ let slug;
382
+ try {
383
+ slug = selectFeature(ctx.root, ctx.config, values.feature);
384
+ }
385
+ catch (error) {
386
+ if (!(error instanceof UsageError))
387
+ throw error;
388
+ // No single feature to act on: name both ways, the feature and the default.
389
+ throw new UsageError(`${error.message.replace(/; pass --feature <slug>$/, '')}.\n` +
390
+ ` every new feature in this checkout: npx agjan auto ${what} --default\n` +
391
+ ` one feature: npx agjan auto ${what} --feature <slug>, or run it on the feature's branch after /agjan-spec has created it`);
392
+ }
393
+ const feature = loadFeature(ctx.root, slug);
382
394
  if (feature.kind !== 'feature')
383
395
  throw new AgjanError(`auto mode is for features; ${feature.slug} is a ${feature.kind}`);
384
396
  const current = feature.approvals.auto;
@@ -4,7 +4,8 @@ import { parseArgs } from 'node:util';
4
4
  import { AGENT_TIERS, CONFIG_FILE, SESSION_MODEL, agentModel } from '../config.js';
5
5
  import { readJson, writeJson } from '../json-file.js';
6
6
  import { AgjanError, UsageError } from '../errors.js';
7
- import { pad } from '../ui.js';
7
+ import { markLine, pad } from '../ui.js';
8
+ import { DEFAULT_TIERS, reviewerFor } from '../review-policy.js';
8
9
  import { sync } from './setup.js';
9
10
  /**
10
11
  * The models GitHub Copilot CLI accepts, from `copilot help config` (its `model` setting
@@ -20,26 +21,79 @@ export function copilotModels() {
20
21
  const section = /`model`:[^\n]*\n((?:\s+- "[^"]+"\n?)+)/.exec(run.stdout ?? '');
21
22
  return section ? [...section[1].matchAll(/- "([^"]+)"/g)].map((m) => m[1]) : null;
22
23
  }
23
- /** What each reviewer runs on, per host and tier. */
24
+ /** The agent of each tier, and what it does. */
25
+ const AGENTS = {
26
+ balanced: { agent: 'agjan-reviewer', label: 'reviewer' },
27
+ deep: { agent: 'agjan-reviewer-deep', label: 'deep reviewer' },
28
+ qa: { agent: 'agjan-qa', label: 'QA' },
29
+ };
30
+ /** The steps a tier runs, from the step tiers (`review.tiers` over the defaults). */
31
+ function stepsOf(config, tier) {
32
+ if (tier === 'qa')
33
+ return 'tests from the spec in Verify';
34
+ const kinds = Object.keys(DEFAULT_TIERS).filter((kind) => kind !== 'qa' && reviewerFor(config, kind) === AGENTS[tier].agent);
35
+ return kinds.length ? `reviews ${kinds.join(', ')}` : 'no steps (review.tiers)';
36
+ }
37
+ /** Model names grouped by family, for reading: Claude, GPT, Gemini, the others. */
38
+ function families(models) {
39
+ const groups = [['Claude', /^claude-/], ['GPT', /^gpt-/], ['Gemini', /^gemini-/]];
40
+ const out = groups.map(([name, re]) => [name, models.filter((m) => re.test(m))]);
41
+ out.push(['Others', models.filter((m) => !groups.some(([, re]) => re.test(m)))]);
42
+ return out.filter(([, list]) => list.length);
43
+ }
44
+ /** Joins words into lines of at most `width` characters after an indent. */
45
+ function wrap(words, indent, width = 92) {
46
+ const lines = [];
47
+ let line = '';
48
+ for (const word of words) {
49
+ if (line && indent.length + line.length + word.length + 2 > width) {
50
+ lines.push(`${line},`);
51
+ line = word;
52
+ }
53
+ else
54
+ line = line ? `${line}, ${word}` : word;
55
+ }
56
+ if (line)
57
+ lines.push(line);
58
+ return lines.map((l, i) => (i ? `${indent}${l}` : l));
59
+ }
60
+ /** What each agent runs on, per host, how to change it, and the models the host offers. */
24
61
  function show(ctx) {
25
62
  const s = ctx.style;
26
63
  const config = ctx.config;
64
+ for (const line of markLine(s, ctx.kit, 'models'))
65
+ ctx.out(line);
27
66
  for (const host of config.hosts) {
67
+ ctx.out('', s.bold(host));
28
68
  for (const tier of AGENT_TIERS) {
69
+ const { agent, label } = AGENTS[tier];
29
70
  const model = agentModel(config, host, tier);
30
- const agent = tier === 'qa' ? 'agjan-qa' : tier === 'deep' ? 'agjan-reviewer-deep' : 'agjan-reviewer';
31
- const inherited = tier === 'qa' && !config.models?.[host]?.qa ? s.gray(' (the deep model; its own: models set qa <model>)') : '';
32
- ctx.out(`${pad(s.bold(host), host, 12)} ${pad(s.gray(tier), tier, 9)} ${pad(agent, agent, 20)} ${model ? s.cyan(model) : s.gray("the session's model")}${inherited}`);
71
+ const shown = model ? s.cyan(model) : s.gray('session model');
72
+ const plain = model ?? 'session model';
73
+ const follows = tier === 'qa' && !config.models?.[host]?.qa ? s.gray(' (follows the deep reviewer)') : '';
74
+ ctx.out(` ${pad(label, label, 15)}${pad(s.gray(agent), agent, 21)}${pad(shown, plain, 19)}${s.gray(stepsOf(config, tier))}${follows}`);
33
75
  }
34
76
  }
35
- ctx.out(s.gray(`change: npx agjan models set <balanced|deep|qa> <model> [--host <host>] (in your terminal); '${SESSION_MODEL}' uses the session's model`));
77
+ ctx.out('', s.bold('Change, in your terminal:'));
78
+ const change = [
79
+ ['npx agjan models set deep <model>', 'tip: another model family than the main agent finds other things'],
80
+ ['npx agjan models set qa <model>', 'QA gets its own model'],
81
+ [`npx agjan models set <tier> ${SESSION_MODEL}`, "back to the session's model"],
82
+ ];
83
+ for (const [command, why] of change)
84
+ ctx.out(` ${pad(s.cyan(command), command, 38)}${s.gray(why)}`);
85
+ if (config.hosts.length > 1)
86
+ ctx.out(s.gray(' add --host <host> for one host only'));
36
87
  if (config.hosts.includes('copilot')) {
37
88
  const models = copilotModels();
38
- if (models)
39
- ctx.out(s.gray(`copilot models: ${models.join(', ')}`));
89
+ if (models) {
90
+ ctx.out('', s.bold('Models GitHub Copilot offers:'));
91
+ for (const [family, list] of families(models))
92
+ ctx.out(` ${pad(s.gray(family), family, 9)}${wrap(list, ' '.repeat(11)).join('\n')}`);
93
+ }
40
94
  }
41
95
  if (config.hosts.includes('claude-code'))
42
- ctx.out(s.gray('claude-code models: an alias (sonnet, opus, haiku, fable) or a full model id'));
96
+ ctx.out('', s.bold('Models Claude Code takes:'), ' an alias (sonnet, opus, haiku, fable) or a full model id');
43
97
  return 0;
44
98
  }
45
99
  /**
@@ -36,7 +36,7 @@ function oneLine(text, max = 140) {
36
36
  const line = String(text ?? '').replace(/\s+/g, ' ').trim();
37
37
  return line.length > max ? `${line.slice(0, max - 1)}…` : line;
38
38
  }
39
- /** What the writer does after this review (design 7.4), in the user's words. */
39
+ /** What the main agent does after this review (design 7.4), in the user's words. */
40
40
  function nextAfter(feature, config, record) {
41
41
  const state = roundState(feature, config, record.step);
42
42
  const status = new Map(feature.findings.map((f) => [f.id, f.status]));
@@ -1,13 +1,14 @@
1
1
  import { spawnSync } from 'node:child_process';
2
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, statSync, writeFileSync } from 'node:fs';
3
3
  import { homedir } from 'node:os';
4
- import { join } from 'node:path';
4
+ import { basename, dirname, join, relative, resolve } from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { parseArgs } from 'node:util';
7
7
  import { AGENT_TIERS, CONFIG_FILE, MODEL_TIERS, SESSION_MODEL, agentModel, loadConfig, loadDomain } from '../config.js';
8
8
  import { LEGACY_MODELS as CLAUDE_LEGACY } from '../adapters/claude-code.js';
9
9
  import { LEGACY_MODELS as COPILOT_LEGACY } from '../adapters/copilot.js';
10
10
  import { readJson, writeJson } from '../json-file.js';
11
+ import { PACKAGE_MANAGERS, detectPackageManager, installDependencies } from '../package-manager.js';
11
12
  import { applyPlan, planStatus } from '../managed.js';
12
13
  import { ADAPTERS, buildPlan, unsupportedHosts } from '../plan.js';
13
14
  import { hookStatus, installHook } from '../hook.js';
@@ -80,30 +81,135 @@ function doSync(ctx, { force }) {
80
81
  function ask(ctx, question, options) {
81
82
  return ctx.ask(question, options);
82
83
  }
84
+ const SETUP_BRANCH = 'chore/set-up-agjan';
85
+ const SETUP_COMMIT = 'chore: set up agjan';
83
86
  /** The next steps after init, for the configured hosts (design decision 69). */
84
- function nextSteps(ctx, hosts, firstCommit) {
87
+ function nextSteps(ctx, hosts, left) {
85
88
  const s = ctx.style;
86
- const steps = [
87
- firstCommit
88
- ? `Commit the setup: ${s.cyan('git add -A && git commit -m "chore: set up agjan"')}`
89
- : `Commit the setup on a branch of its own and merge it with a PR: ${s.cyan('git add -A && git commit -m "chore: set up agjan"')}`,
90
- ];
89
+ const steps = [];
90
+ if (left.cd)
91
+ steps.push(`Move into the project: ${s.cyan(`cd ${/\s/.test(left.cd) ? JSON.stringify(left.cd) : left.cd}`)}`);
92
+ if (left.install)
93
+ steps.push(`Install the pinned agjan: ${s.cyan(left.install)}`);
94
+ if (left.committed?.created) {
95
+ steps.push(`The setup is committed on ${s.cyan(left.committed.branch)}: push it and merge it with a PR.`);
96
+ }
97
+ else if (!left.committed) {
98
+ steps.push(left.firstCommit
99
+ ? `Commit the setup: ${s.cyan(`git add -A && git commit -m "${SETUP_COMMIT}"`)}`
100
+ : `Commit the setup on a branch of its own and merge it with a PR: ${s.cyan(`git switch -c ${SETUP_BRANCH} && git add -A && git commit -m "${SETUP_COMMIT}"`)}`);
101
+ }
91
102
  if (hosts.includes('claude-code')) {
92
103
  steps.push("Open this folder once in Claude Code and trust it: the reviewer's agjan tools load only in trusted folders.");
93
104
  }
94
105
  if (hosts.includes('copilot')) {
95
106
  steps.push(`Start ${s.cyan('copilot')} in this folder and trust it.`);
96
107
  }
97
- steps.push(`Run: ${s.cyan('npx agjan doctor')}`);
108
+ steps.push(`Run: ${s.cyan('agjan doctor')}`);
98
109
  return ['', s.bold('Next steps:'), ...steps.map((text, i) => ` ${i + 1}. ${text}`)];
99
110
  }
100
111
  /**
101
- * agjan init [--domains btp] [--hosts claude-code] [--language en] [--base <ref>] [--no-hook] [--no-ci]
102
- * [--prepare] [--copilot-mcp | --no-copilot-mcp]
112
+ * Commits everything init wrote: on the current branch of a new repository, else on a
113
+ * branch of its own (the base branch changes through a PR). Returns the branch, or why not.
114
+ */
115
+ function commitSetup(root, { firstCommit }) {
116
+ try {
117
+ if (!firstCommit)
118
+ git(root, ['switch', '-q', '-c', SETUP_BRANCH]);
119
+ git(root, ['add', '-A']);
120
+ git(root, ['commit', '-q', '-m', SETUP_COMMIT]);
121
+ return { branch: git(root, ['branch', '--show-current']).trim(), created: !firstCommit };
122
+ }
123
+ catch (error) {
124
+ return { error: error.message };
125
+ }
126
+ }
127
+ const INIT_USAGE = [
128
+ 'Usage: agjan init <folder | .> --hosts <host,...> [options]',
129
+ '',
130
+ ' <folder> create the folder (git init, package.json, agjan pinned as a devDependency) and set it up',
131
+ ' . set up the current folder, keeping what is in it',
132
+ '',
133
+ ' --hosts <host,...> claude-code, copilot (asked for on a terminal when left out)',
134
+ ' --domains btp --language en --base <ref> --no-hook --no-ci --prepare',
135
+ ' --copilot-mcp | --no-copilot-mcp',
136
+ ' --commit | --no-commit commit the setup (a new repository: on main; else on chore/set-up-agjan) or leave it to you',
137
+ ' --no-install pin agjan in package.json but do not install it',
138
+ ` --pm <${PACKAGE_MANAGERS.join('|')}> the package manager to install with (default: from the lockfile, else npm)`,
139
+ ' --dry-run show what would be done and stop',
140
+ ];
141
+ /** The folder `init` works in, and what it has to do there; throws on anything that would clash. */
142
+ function planScaffold(ctx, target) {
143
+ const exists = existsSync(target);
144
+ if (exists && !statSync(target).isDirectory())
145
+ throw new AgjanError(`${target} is a file, not a folder`);
146
+ if (exists && existsSync(join(target, CONFIG_FILE)))
147
+ throw new AgjanError(`${CONFIG_FILE} already exists in ${target}; run 'agjan sync' there to update the managed files`);
148
+ if (exists)
149
+ readJson(join(target, 'package.json'));
150
+ // agjan sets up the root of a repository: a folder inside another repository is refused.
151
+ let ancestor = target;
152
+ while (!existsSync(ancestor))
153
+ ancestor = dirname(ancestor);
154
+ const top = git(ancestor, ['rev-parse', '--show-toplevel'], { allowFail: true })?.trim();
155
+ if (top && realpathSync(top) !== join(realpathSync(ancestor), relative(ancestor, target))) {
156
+ throw new AgjanError(`${target} is inside the git repository ${top}; agjan is set up at the root of a repository (run 'agjan init .' there)`);
157
+ }
158
+ // Only a start without other work in it may be committed as a whole: a new folder, an
159
+ // empty one, or a repository whose working tree is clean.
160
+ const clean = !exists || (top ? git(target, ['status', '--porcelain']).trim() === '' : readdirSync(target).length === 0);
161
+ return { exists, repo: Boolean(top), packageJson: exists && existsSync(join(target, 'package.json')), clean };
162
+ }
163
+ /** A valid package name for a folder name. */
164
+ function packageName(folder) {
165
+ return basename(folder).toLowerCase().replace(/[^a-z0-9._~-]+/g, '-').replace(/^[-._]+|-+$/g, '') || 'project';
166
+ }
167
+ /**
168
+ * Creates the folder and the git repository when missing, and pins this version of agjan
169
+ * in package.json (creating it when missing), so every developer and CI use the same one.
170
+ */
171
+ function scaffold(ctx, target, found, { install, manager }) {
172
+ const s = ctx.style;
173
+ const line = (action, what) => ctx.out(` ${pad(tone(s, action), action, 14)} ${what}`);
174
+ if (!found.exists) {
175
+ mkdirSync(target, { recursive: true });
176
+ line('created', `${basename(target)}/`);
177
+ }
178
+ if (!found.repo) {
179
+ git(target, ['init', '-q', '-b', 'main']);
180
+ line('created', 'git repository (branch main)');
181
+ }
182
+ const file = join(target, 'package.json');
183
+ const pkg = readJson(file) ?? { name: packageName(target), version: '0.0.0', private: true };
184
+ const pinned = pkg.devDependencies?.agjan ?? pkg.dependencies?.agjan;
185
+ if (!pinned) {
186
+ // Keys in alphabetical order, as npm writes them.
187
+ pkg.devDependencies = Object.fromEntries(Object.entries({ ...(pkg.devDependencies ?? {}), agjan: ctx.kit }).sort(([a], [b]) => a.localeCompare(b)));
188
+ }
189
+ if (!found.packageJson || !pinned) {
190
+ writeJson(file, pkg);
191
+ line(found.packageJson ? 'updated' : 'created', `package.json (agjan ${pinned ?? ctx.kit} in devDependencies)`);
192
+ }
193
+ else {
194
+ line('unchanged', `package.json (agjan ${pinned})`);
195
+ }
196
+ if (install) {
197
+ ctx.out(s.gray(` ${manager} install`));
198
+ installDependencies(target, manager);
199
+ }
200
+ else {
201
+ ctx.out(s.gray(` not installed; run '${manager} install' before using agjan commands in this folder`));
202
+ }
203
+ }
204
+ /**
205
+ * agjan init <folder | .> --hosts claude-code,copilot [--domains btp] [--language en] [--base <ref>]
206
+ * [--no-hook] [--no-ci] [--prepare] [--copilot-mcp | --no-copilot-mcp]
207
+ * [--commit | --no-commit] [--no-install] [--pm npm|pnpm|yarn|bun] [--dry-run]
103
208
  */
104
209
  export async function init(ctx, argv) {
105
- const { values } = parseArgs({
210
+ const { values, positionals } = parseArgs({
106
211
  args: argv,
212
+ allowPositionals: true,
107
213
  options: {
108
214
  domains: { type: 'string' },
109
215
  hosts: { type: 'string' },
@@ -114,24 +220,52 @@ export async function init(ctx, argv) {
114
220
  prepare: { type: 'boolean' },
115
221
  'copilot-mcp': { type: 'boolean' },
116
222
  'no-copilot-mcp': { type: 'boolean' },
223
+ commit: { type: 'boolean' },
224
+ 'no-commit': { type: 'boolean' },
225
+ 'no-install': { type: 'boolean' },
226
+ pm: { type: 'string' },
227
+ 'dry-run': { type: 'boolean' },
117
228
  },
118
229
  });
119
- const root = ctx.root;
120
- if (existsSync(join(root, CONFIG_FILE)))
121
- throw new AgjanError(`${CONFIG_FILE} already exists; run 'agjan sync' to update the managed files`);
230
+ if (positionals.length === 0) {
231
+ ctx.out(...INIT_USAGE);
232
+ return 2;
233
+ }
234
+ if (positionals.length > 1)
235
+ throw new UsageError(`init takes one folder, got ${positionals.length}: ${positionals.join(' ')}`);
236
+ const target = resolve(ctx.cwd, positionals[0]);
237
+ if (values.commit && values['no-commit'])
238
+ throw new UsageError('--commit and --no-commit exclude each other');
239
+ if (values.pm && !PACKAGE_MANAGERS.includes(values.pm))
240
+ throw new UsageError(`--pm must be one of ${PACKAGE_MANAGERS.join(', ')}`);
241
+ const found = planScaffold(ctx, target);
122
242
  const domains = list(values.domains) ?? ['btp'];
123
243
  for (const d of domains)
124
244
  loadDomain(d);
125
- const hosts = list(values.hosts) ?? ['claude-code'];
126
- for (const h of hosts)
245
+ const supported = Object.keys(ADAPTERS);
246
+ const chosen = list(values.hosts);
247
+ for (const h of chosen ?? [])
127
248
  if (!ADAPTERS[h])
128
- throw new UsageError(`host '${h}' is not supported in this version (supported: ${Object.keys(ADAPTERS).join(', ')})`);
249
+ throw new UsageError(`host '${h}' is not supported in this version (supported: ${supported.join(', ')})`);
250
+ const manager = values.pm ?? detectPackageManager(target);
251
+ if (values['dry-run']) {
252
+ ctx.out(`agjan init ${positionals[0]} (dry run; nothing is changed):`, ...(found.exists ? [` use the existing folder ${target}`] : [` create the folder ${target}`]), ...(found.repo ? [] : [' git init -b main']), ` ${found.packageJson ? 'pin' : 'create package.json and pin'} agjan ${ctx.kit} in devDependencies${values['no-install'] ? '' : `, then ${manager} install`}`, ` write ${CONFIG_FILE} and the managed files for ${chosen?.join(', ') ?? 'the hosts you choose'}`);
253
+ return 0;
254
+ }
129
255
  // The mark first, then the questions (design decision 69).
130
256
  const s = ctx.style;
131
257
  const lines = mark(s, ctx.kit, 'setting up this repository');
132
258
  for (const line of lines)
133
259
  ctx.out(line);
134
260
  await blink(ctx, lines);
261
+ const hosts = chosen ?? await ctx.select('Which hosts should agjan set up?', supported.map((id) => ({ id, label: id })));
262
+ if (!hosts)
263
+ throw new UsageError(`no host chosen and no terminal to ask on; pass --hosts <host,...> (supported: ${supported.join(', ')})`);
264
+ const origin = ctx.cwd;
265
+ ctx.out('');
266
+ scaffold(ctx, target, found, { install: !values['no-install'], manager });
267
+ ctx.chdir(target);
268
+ const root = ctx.root;
135
269
  // Enter takes the recommended answer (yes); without a terminal the default (no) applies.
136
270
  const flag = (yes, no) => (values[yes] ? true : values[no] ? false : null);
137
271
  // Copilot loads the project's .mcp.json only in folders it remembers as trusted; its
@@ -174,12 +308,37 @@ export async function init(ctx, argv) {
174
308
  ctx.out(` ${pad(tone(s, 'created'), 'created', 14)} ${CI_FILE}`);
175
309
  }
176
310
  }
177
- const pkg = readJson(join(root, 'package.json'));
178
- if (!pkg?.devDependencies?.agjan && !pkg?.dependencies?.agjan) {
179
- ctx.out('', s.yellow('Pin agjan in this project so every developer and CI use the same version:'), ` ${s.cyan('npm install --save-dev agjan')}`);
180
- }
181
311
  const firstCommit = git(root, ['rev-parse', '--verify', '--quiet', 'HEAD'], { allowFail: true }) === null;
182
- ctx.out(...nextSteps(ctx, hosts, firstCommit));
312
+ // Asked once everything is written. Not when other work is in the folder (git add -A would
313
+ // sweep it in), unless --commit says so.
314
+ let committed = null;
315
+ // The pre-commit hook runs the project's agjan: without the install, committing would hang on it.
316
+ const hookNeedsInstall = values['no-install'] && !values['no-hook'];
317
+ const wanted = values['no-commit'] || hookNeedsInstall ? false : values.commit ? true : !found.clean ? false
318
+ : ask(ctx, firstCommit ? `Commit the setup now (${SETUP_COMMIT})?` : `Commit the setup on a new branch, ${SETUP_BRANCH}?`, { defaultYes: true }) ?? false;
319
+ if (hookNeedsInstall && !values['no-commit']) {
320
+ ctx.out('', s.yellow(`The setup is not committed: the pre-commit hook needs the installed agjan (${manager} install, then commit).`));
321
+ }
322
+ else if (!found.clean && !values.commit && !values['no-commit']) {
323
+ ctx.out('', s.yellow('The folder had other work in it, so the setup is not committed for you; commit what belongs to it yourself.'));
324
+ }
325
+ if (wanted) {
326
+ const result = commitSetup(root, { firstCommit });
327
+ if ('error' in result) {
328
+ ctx.out('', s.yellow(`Could not commit the setup: ${result.error}`));
329
+ }
330
+ else {
331
+ committed = result;
332
+ ctx.out('', ` ${pad(tone(s, 'created'), 'created', 14)} commit "${SETUP_COMMIT}" on ${result.branch}`);
333
+ }
334
+ }
335
+ const cd = relative(origin, target);
336
+ ctx.out(...nextSteps(ctx, hosts, {
337
+ cd: cd && cd !== '.' ? cd : null,
338
+ install: values['no-install'] ? `${manager} install` : null,
339
+ committed,
340
+ firstCommit,
341
+ }));
183
342
  return 0;
184
343
  }
185
344
  function addPrepare(root) {
@@ -214,7 +373,7 @@ function addToCopilot(ctx, config) {
214
373
  export function sync(ctx, argv) {
215
374
  const { values } = parseArgs({ args: argv, options: { force: { type: 'boolean' }, 'copilot-mcp': { type: 'boolean' } } });
216
375
  if (!existsSync(join(ctx.root, CONFIG_FILE)))
217
- throw new AgjanError(`no ${CONFIG_FILE}; run 'agjan init' first`);
376
+ throw new AgjanError(`no ${CONFIG_FILE}; run 'agjan init .' first`);
218
377
  ctx.out(`${ctx.style.bold('agjan sync')}:`);
219
378
  const results = doSync(ctx, { force: Boolean(values.force) });
220
379
  printResults(ctx, results);
@@ -236,7 +395,7 @@ function probeMcp(root) {
236
395
  { jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-11-25', capabilities: {}, clientInfo: { name: 'agjan-doctor', version: '1' } } },
237
396
  { jsonrpc: '2.0', id: 2, method: 'tools/list' },
238
397
  ].map((m) => JSON.stringify(m)).join('\n');
239
- const run = spawnSync(process.execPath, [BIN, 'mcp'], { cwd: root, input: `${input}\n`, encoding: 'utf8', timeout: 10_000 });
398
+ const run = spawnSync(process.execPath, [BIN, 'mcp'], { cwd: root, env: { ...process.env, AGJAN_DELEGATED: '1' }, input: `${input}\n`, encoding: 'utf8', timeout: 10_000 });
240
399
  try {
241
400
  const lines = run.stdout.trim().split('\n').map((l) => JSON.parse(l));
242
401
  const tools = lines.find((l) => l.id === 2)?.result?.tools?.map((t) => t.name) ?? [];
@@ -301,7 +460,7 @@ export async function doctor(ctx) {
301
460
  warn('kit version', `project records ${raw.kit}, installed ${ctx.kit}; run: npx agjan sync`);
302
461
  const local = readJson(join(root, 'node_modules', 'agjan', 'package.json'));
303
462
  if (!local)
304
- warn('local install', 'agjan is not installed in node_modules; run: npm install --save-dev agjan');
463
+ warn('local install', 'agjan is not installed in node_modules; run: npm install');
305
464
  else if (local.version !== ctx.kit)
306
465
  warn('local install', `node_modules has ${local.version}, this command is ${ctx.kit}`);
307
466
  else
@@ -370,7 +529,7 @@ export async function doctor(ctx) {
370
529
  else if (config.areas.fiori) {
371
530
  ok('ui tests', `none (optional: Playwright, a ${UI_SCRIPT} script; see the fiori-developer skill)`);
372
531
  }
373
- ok('reviewer models', `${config.hosts.map((h) => `${h}: ${AGENT_TIERS.map((t) => `${t} ${agentModel(config, h, t) ?? 'session model'}`).join(', ')}`).join('; ')}${config.hosts.every((h) => !agentModel(config, h, 'deep')) ? ' (a deep reviewer on another model family than the writer catches other things: npx agjan models set deep <model>)' : ''}`);
532
+ ok('reviewer models', `${config.hosts.map((h) => `${h}: ${AGENT_TIERS.map((t) => `${t} ${agentModel(config, h, t) ?? 'session model'}`).join(', ')}`).join('; ')}${config.hosts.every((h) => !agentModel(config, h, 'deep')) ? ' (a deep reviewer on another model family than the main agent catches other things: npx agjan models set deep <model>)' : ''}`);
374
533
  ok('branches', 'agents ask you, then run npx agjan branch');
375
534
  const autoDefault = readAutoDefault(root);
376
535
  ok('auto mode', autoDefault ? `on for new features in this checkout (since ${autoDefault.at_utc}); off: npx agjan auto off --default` : 'off: gates wait for you (npx agjan auto on --default for new features, auto on for one)');
@@ -37,6 +37,21 @@ function reviewNext(ctx, feature, step) {
37
37
  return `QA (step qa) with ${reviewerFor(ctx.config, step)}${round}`;
38
38
  return `review step ${step} with ${reviewerFor(ctx.config, step)}${round}`;
39
39
  }
40
+ /**
41
+ * The stage to show: the documents' stages (spec, design, build), then `verify` once the
42
+ * verification started (its step logged since the design approval, or a verify review),
43
+ * and `done` once the human accepted the verified feature, as on the progress pages.
44
+ */
45
+ function shownStage(ctx, feature) {
46
+ if (feature.stage !== 'build')
47
+ return feature.stage;
48
+ const verify = verifyState(ctx.root, ctx.config, feature);
49
+ if (verify.state === 'current' && acceptanceState(ctx.root, ctx.config, feature, verify).state === 'accepted')
50
+ return 'done';
51
+ const since = feature.approvals.approvals.design?.at_utc;
52
+ const verifying = readLog(feature.dir).some((e) => e.event === 'step' && e.stage === 'verify' && (!since || e.at_utc >= since));
53
+ return verifying || verify.state !== 'none' ? 'verify' : 'build';
54
+ }
40
55
  /** The review step a feature in Spec or Design needs next. */
41
56
  function gateStep(feature) {
42
57
  if (feature.stage === 'design')
@@ -213,7 +228,8 @@ async function describe(ctx, feature, onBase = false) {
213
228
  return describeRecord(ctx, feature, onBase);
214
229
  if (onBase)
215
230
  return describeOnBase(ctx, feature);
216
- heading(ctx, feature, `stage: ${ctx.style.magenta(feature.stage)}`);
231
+ const stage = shownStage(ctx, feature);
232
+ heading(ctx, feature, `stage: ${stage === 'done' ? ctx.style.green(stage) : ctx.style.magenta(stage)}`);
217
233
  row(ctx, 'spec', tone(ctx.style, feature.state.spec));
218
234
  const mode = feature.design?.parsed.mode ? ` (${feature.design.parsed.mode})` : '';
219
235
  row(ctx, 'design', `${tone(ctx.style, feature.state.design)}${mode}`);
package/dist/context.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { readFileSync } from 'node:fs';
2
2
  import { repoRoot, userEmail } from './git.js';
3
3
  import { loadConfig } from './config.js';
4
- import { askOnTerminal, confirmOnTerminal, editOnTerminal } from './terminal.js';
4
+ import { askOnTerminal, confirmOnTerminal, editOnTerminal, selectOnTerminal } from './terminal.js';
5
5
  import { createStyle } from './ui.js';
6
6
  export const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
7
7
  /** UTC timestamp without milliseconds, for example 2026-10-17T09:12:03Z. */
@@ -14,11 +14,20 @@ export function utcNow() {
14
14
  * no option
15
15
  * to skip the confirmation from the command line or the environment.
16
16
  */
17
- export function createContext({ cwd = process.cwd(), stdout = process.stdout, stderr = process.stderr, now = utcNow, confirm = confirmOnTerminal, edit = editOnTerminal, ask = askOnTerminal, } = {}) {
17
+ export function createContext({ cwd: initialCwd = process.cwd(), stdout = process.stdout, stderr = process.stderr, now = utcNow, confirm = confirmOnTerminal, edit = editOnTerminal, ask = askOnTerminal, select = selectOnTerminal, } = {}) {
18
+ let cwd = initialCwd;
18
19
  let root;
19
20
  let config;
20
21
  return {
21
- cwd,
22
+ get cwd() {
23
+ return cwd;
24
+ },
25
+ /** Moves the command to another folder (init creates the folder it then works in). */
26
+ chdir(dir) {
27
+ cwd = dir;
28
+ root = undefined;
29
+ config = undefined;
30
+ },
22
31
  /** Colors for stdout; plain text unless stdout is a terminal (see ui.ts). */
23
32
  style: createStyle(stdout),
24
33
  now,
@@ -27,6 +36,8 @@ export function createContext({ cwd = process.cwd(), stdout = process.stdout, st
27
36
  edit,
28
37
  /** Asks the human a yes/no question; null without a terminal. */
29
38
  ask,
39
+ /** Asks the human to choose among `choices`; null without a terminal. */
40
+ select,
30
41
  kit: pkg.version,
31
42
  get root() {
32
43
  root ??= repoRoot(cwd);
package/dist/fix.js CHANGED
@@ -9,7 +9,7 @@ export const FIX_MD = 'fix.md';
9
9
  export const PROJECT_MD = `${FEATURES_DIR}/project.md`;
10
10
  /**
11
11
  * Paths named in the baseline's "Do-not-touch list": every `code span` in its bullets
12
- * (design 8.6; writers often list several paths in one bullet). They are protected for
12
+ * (design 8.6; main agents often list several paths in one bullet). They are protected for
13
13
  * fixes like `fix.protected`.
14
14
  */
15
15
  export function doNotTouch(root) {