agjan 0.0.13 → 0.0.14

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
@@ -51,11 +51,19 @@ Requirements: Node.js 22 or later, git, and Claude Code and/or the GitHub Copilo
51
51
  Linux, macOS or Windows.
52
52
 
53
53
  ```sh
54
- npm install --save-dev agjan
55
- npx agjan init --hosts claude-code,copilot
56
- npx agjan doctor
54
+ npm install --global agjan
55
+ agjan init my-project --hosts claude-code,copilot # or "agjan init ." in an existing folder
56
+ cd my-project
57
+ agjan doctor
57
58
  ```
58
59
 
60
+ `agjan init my-project` creates the folder, the git repository (branch `main`) and a
61
+ `package.json`, pins this version of agjan in its `devDependencies` and installs it, then
62
+ sets the project up. Without `--hosts` it asks which hosts to set up. The global `agjan`
63
+ only starts things: `init`, `--help` and `--version` run in it, and every other command
64
+ runs in the version the project pins, so a project never depends on the global version.
65
+ After cloning a project, the first command offers to install the pinned version.
66
+
59
67
  Open the project in your agent host, trust the folder, and start a feature:
60
68
 
61
69
  ```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
@@ -55,16 +55,19 @@ and a read-only reviewer at every step. Closed beta (0.x); the user guide is\nin
55
55
  Usage: agjan <command> [options]
56
56
 
57
57
  Setup (human):
58
- init [--domains btp] [--hosts claude-code,copilot] [--base <ref>]
58
+ init <folder | .> [--hosts claude-code,copilot] [--domains btp] [--base <ref>]
59
59
  [--no-hook] [--no-ci] [--prepare] [--copilot-mcp | --no-copilot-mcp]
60
- set up agjan in this repository
60
+ [--no-install] [--pm npm|pnpm|yarn|bun] [--dry-run]
61
+ set up agjan: <folder> is created (git init, package.json,
62
+ agjan pinned and installed), . is the current folder; without
63
+ --hosts it asks which hosts (claude-code, copilot) to set up
61
64
  sync [--force] [--copilot-mcp]
62
65
  regenerate managed files (skills, agents, blocks, settings);
63
66
  --copilot-mcp adds missing MCP servers to Copilot
64
67
  hook install install the pre-commit hook
65
68
  models [set <balanced|deep|qa> <model> [--host <h>]]
66
69
  show the reviewers' models, or choose one (the deep reviewer
67
- on another model family than the writer catches other things)
70
+ on another model family than the main agent catches other things)
68
71
  doctor check the environment and the project setup
69
72
 
70
73
  Agent and human:
@@ -117,6 +120,9 @@ Human only, in a terminal:
117
120
 
118
121
  Other:
119
122
  --version, --help
123
+ --yes <command> install the project's pinned agjan without asking, then run
124
+ the command (the global agjan runs project commands in the
125
+ version the project pins in node_modules)
120
126
  `;
121
127
  /**
122
128
  * 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, 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';
@@ -97,13 +98,88 @@ function nextSteps(ctx, hosts, firstCommit) {
97
98
  steps.push(`Run: ${s.cyan('npx agjan doctor')}`);
98
99
  return ['', s.bold('Next steps:'), ...steps.map((text, i) => ` ${i + 1}. ${text}`)];
99
100
  }
101
+ const INIT_USAGE = [
102
+ 'Usage: agjan init <folder | .> --hosts <host,...> [options]',
103
+ '',
104
+ ' <folder> create the folder (git init, package.json, agjan pinned as a devDependency) and set it up',
105
+ ' . set up the current folder, keeping what is in it',
106
+ '',
107
+ ' --hosts <host,...> claude-code, copilot (asked for on a terminal when left out)',
108
+ ' --domains btp --language en --base <ref> --no-hook --no-ci --prepare',
109
+ ' --copilot-mcp | --no-copilot-mcp',
110
+ ' --no-install pin agjan in package.json but do not install it',
111
+ ` --pm <${PACKAGE_MANAGERS.join('|')}> the package manager to install with (default: from the lockfile, else npm)`,
112
+ ' --dry-run show what would be done and stop',
113
+ ];
114
+ /** The folder `init` works in, and what it has to do there; throws on anything that would clash. */
115
+ function planScaffold(ctx, target) {
116
+ const exists = existsSync(target);
117
+ if (exists && !statSync(target).isDirectory())
118
+ throw new AgjanError(`${target} is a file, not a folder`);
119
+ if (exists && existsSync(join(target, CONFIG_FILE)))
120
+ throw new AgjanError(`${CONFIG_FILE} already exists in ${target}; run 'agjan sync' there to update the managed files`);
121
+ if (exists)
122
+ readJson(join(target, 'package.json'));
123
+ // agjan sets up the root of a repository: a folder inside another repository is refused.
124
+ let ancestor = target;
125
+ while (!existsSync(ancestor))
126
+ ancestor = dirname(ancestor);
127
+ const top = git(ancestor, ['rev-parse', '--show-toplevel'], { allowFail: true })?.trim();
128
+ if (top && realpathSync(top) !== join(realpathSync(ancestor), relative(ancestor, target))) {
129
+ throw new AgjanError(`${target} is inside the git repository ${top}; agjan is set up at the root of a repository (run 'agjan init .' there)`);
130
+ }
131
+ return { exists, repo: Boolean(top), packageJson: exists && existsSync(join(target, 'package.json')) };
132
+ }
133
+ /** A valid package name for a folder name. */
134
+ function packageName(folder) {
135
+ return basename(folder).toLowerCase().replace(/[^a-z0-9._~-]+/g, '-').replace(/^[-._]+|-+$/g, '') || 'project';
136
+ }
100
137
  /**
101
- * agjan init [--domains btp] [--hosts claude-code] [--language en] [--base <ref>] [--no-hook] [--no-ci]
102
- * [--prepare] [--copilot-mcp | --no-copilot-mcp]
138
+ * Creates the folder and the git repository when missing, and pins this version of agjan
139
+ * in package.json (creating it when missing), so every developer and CI use the same one.
140
+ */
141
+ function scaffold(ctx, target, found, { install, manager }) {
142
+ const s = ctx.style;
143
+ const line = (action, what) => ctx.out(` ${pad(tone(s, action), action, 14)} ${what}`);
144
+ if (!found.exists) {
145
+ mkdirSync(target, { recursive: true });
146
+ line('created', `${basename(target)}/`);
147
+ }
148
+ if (!found.repo) {
149
+ git(target, ['init', '-q', '-b', 'main']);
150
+ line('created', 'git repository (branch main)');
151
+ }
152
+ const file = join(target, 'package.json');
153
+ const pkg = readJson(file) ?? { name: packageName(target), version: '0.0.0', private: true };
154
+ const pinned = pkg.devDependencies?.agjan ?? pkg.dependencies?.agjan;
155
+ if (!pinned) {
156
+ // Keys in alphabetical order, as npm writes them.
157
+ pkg.devDependencies = Object.fromEntries(Object.entries({ ...(pkg.devDependencies ?? {}), agjan: ctx.kit }).sort(([a], [b]) => a.localeCompare(b)));
158
+ }
159
+ if (!found.packageJson || !pinned) {
160
+ writeJson(file, pkg);
161
+ line(found.packageJson ? 'updated' : 'created', `package.json (agjan ${pinned ?? ctx.kit} in devDependencies)`);
162
+ }
163
+ else {
164
+ line('unchanged', `package.json (agjan ${pinned})`);
165
+ }
166
+ if (install) {
167
+ ctx.out(s.gray(` ${manager} install`));
168
+ installDependencies(target, manager);
169
+ }
170
+ else {
171
+ ctx.out(s.gray(` not installed; run '${manager} install' before using agjan commands in this folder`));
172
+ }
173
+ }
174
+ /**
175
+ * agjan init <folder | .> --hosts claude-code,copilot [--domains btp] [--language en] [--base <ref>]
176
+ * [--no-hook] [--no-ci] [--prepare] [--copilot-mcp | --no-copilot-mcp]
177
+ * [--no-install] [--pm npm|pnpm|yarn|bun] [--dry-run]
103
178
  */
104
179
  export async function init(ctx, argv) {
105
- const { values } = parseArgs({
180
+ const { values, positionals } = parseArgs({
106
181
  args: argv,
182
+ allowPositionals: true,
107
183
  options: {
108
184
  domains: { type: 'string' },
109
185
  hosts: { type: 'string' },
@@ -114,24 +190,47 @@ export async function init(ctx, argv) {
114
190
  prepare: { type: 'boolean' },
115
191
  'copilot-mcp': { type: 'boolean' },
116
192
  'no-copilot-mcp': { type: 'boolean' },
193
+ 'no-install': { type: 'boolean' },
194
+ pm: { type: 'string' },
195
+ 'dry-run': { type: 'boolean' },
117
196
  },
118
197
  });
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`);
198
+ if (positionals.length === 0) {
199
+ ctx.out(...INIT_USAGE);
200
+ return 2;
201
+ }
202
+ if (positionals.length > 1)
203
+ throw new UsageError(`init takes one folder, got ${positionals.length}: ${positionals.join(' ')}`);
204
+ const target = resolve(ctx.cwd, positionals[0]);
205
+ if (values.pm && !PACKAGE_MANAGERS.includes(values.pm))
206
+ throw new UsageError(`--pm must be one of ${PACKAGE_MANAGERS.join(', ')}`);
207
+ const found = planScaffold(ctx, target);
122
208
  const domains = list(values.domains) ?? ['btp'];
123
209
  for (const d of domains)
124
210
  loadDomain(d);
125
- const hosts = list(values.hosts) ?? ['claude-code'];
126
- for (const h of hosts)
211
+ const supported = Object.keys(ADAPTERS);
212
+ const chosen = list(values.hosts);
213
+ for (const h of chosen ?? [])
127
214
  if (!ADAPTERS[h])
128
- throw new UsageError(`host '${h}' is not supported in this version (supported: ${Object.keys(ADAPTERS).join(', ')})`);
215
+ throw new UsageError(`host '${h}' is not supported in this version (supported: ${supported.join(', ')})`);
216
+ const manager = values.pm ?? detectPackageManager(target);
217
+ if (values['dry-run']) {
218
+ 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'}`);
219
+ return 0;
220
+ }
129
221
  // The mark first, then the questions (design decision 69).
130
222
  const s = ctx.style;
131
223
  const lines = mark(s, ctx.kit, 'setting up this repository');
132
224
  for (const line of lines)
133
225
  ctx.out(line);
134
226
  await blink(ctx, lines);
227
+ const hosts = chosen ?? ctx.select('Which hosts should agjan set up?', supported.map((id) => ({ id, label: id })));
228
+ if (!hosts)
229
+ throw new UsageError(`no host chosen and no terminal to ask on; pass --hosts <host,...> (supported: ${supported.join(', ')})`);
230
+ ctx.out('');
231
+ scaffold(ctx, target, found, { install: !values['no-install'], manager });
232
+ ctx.chdir(target);
233
+ const root = ctx.root;
135
234
  // Enter takes the recommended answer (yes); without a terminal the default (no) applies.
136
235
  const flag = (yes, no) => (values[yes] ? true : values[no] ? false : null);
137
236
  // Copilot loads the project's .mcp.json only in folders it remembers as trusted; its
@@ -174,10 +273,6 @@ export async function init(ctx, argv) {
174
273
  ctx.out(` ${pad(tone(s, 'created'), 'created', 14)} ${CI_FILE}`);
175
274
  }
176
275
  }
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
276
  const firstCommit = git(root, ['rev-parse', '--verify', '--quiet', 'HEAD'], { allowFail: true }) === null;
182
277
  ctx.out(...nextSteps(ctx, hosts, firstCommit));
183
278
  return 0;
@@ -214,7 +309,7 @@ function addToCopilot(ctx, config) {
214
309
  export function sync(ctx, argv) {
215
310
  const { values } = parseArgs({ args: argv, options: { force: { type: 'boolean' }, 'copilot-mcp': { type: 'boolean' } } });
216
311
  if (!existsSync(join(ctx.root, CONFIG_FILE)))
217
- throw new AgjanError(`no ${CONFIG_FILE}; run 'agjan init' first`);
312
+ throw new AgjanError(`no ${CONFIG_FILE}; run 'agjan init .' first`);
218
313
  ctx.out(`${ctx.style.bold('agjan sync')}:`);
219
314
  const results = doSync(ctx, { force: Boolean(values.force) });
220
315
  printResults(ctx, results);
@@ -236,7 +331,7 @@ function probeMcp(root) {
236
331
  { jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-11-25', capabilities: {}, clientInfo: { name: 'agjan-doctor', version: '1' } } },
237
332
  { jsonrpc: '2.0', id: 2, method: 'tools/list' },
238
333
  ].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 });
334
+ const run = spawnSync(process.execPath, [BIN, 'mcp'], { cwd: root, env: { ...process.env, AGJAN_DELEGATED: '1' }, input: `${input}\n`, encoding: 'utf8', timeout: 10_000 });
240
335
  try {
241
336
  const lines = run.stdout.trim().split('\n').map((l) => JSON.parse(l));
242
337
  const tools = lines.find((l) => l.id === 2)?.result?.tools?.map((t) => t.name) ?? [];
@@ -301,7 +396,7 @@ export async function doctor(ctx) {
301
396
  warn('kit version', `project records ${raw.kit}, installed ${ctx.kit}; run: npx agjan sync`);
302
397
  const local = readJson(join(root, 'node_modules', 'agjan', 'package.json'));
303
398
  if (!local)
304
- warn('local install', 'agjan is not installed in node_modules; run: npm install --save-dev agjan');
399
+ warn('local install', 'agjan is not installed in node_modules; run: npm install');
305
400
  else if (local.version !== ctx.kit)
306
401
  warn('local install', `node_modules has ${local.version}, this command is ${ctx.kit}`);
307
402
  else
@@ -370,7 +465,7 @@ export async function doctor(ctx) {
370
465
  else if (config.areas.fiori) {
371
466
  ok('ui tests', `none (optional: Playwright, a ${UI_SCRIPT} script; see the fiori-developer skill)`);
372
467
  }
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>)' : ''}`);
468
+ 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
469
  ok('branches', 'agents ask you, then run npx agjan branch');
375
470
  const autoDefault = readAutoDefault(root);
376
471
  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) {
@@ -0,0 +1,81 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { existsSync, realpathSync } from 'node:fs';
3
+ import { createRequire } from 'node:module';
4
+ import { dirname, join, parse } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { CONFIG_FILE } from './config.js';
7
+ import { readJson } from './json-file.js';
8
+ import { detectPackageManager, installDependencies } from './package-manager.js';
9
+ import { askOnTerminal } from './terminal.js';
10
+ /** Commands the global agjan runs itself; everything else belongs to a project's pinned version. */
11
+ const GLOBAL_COMMANDS = new Set(['init', 'help', '--help', '-h', 'version', '--version', '-v']);
12
+ /** Set for the process the launcher starts, so that it never delegates again. */
13
+ const DELEGATED = 'AGJAN_DELEGATED';
14
+ const OWN_PACKAGE = realpathSync(fileURLToPath(new URL('..', import.meta.url)));
15
+ /** The nearest folder up from `dir` with an agjan.config.json; null outside an agjan project. */
16
+ export function findProject(dir) {
17
+ for (let current = dir;; current = dirname(current)) {
18
+ if (existsSync(join(current, CONFIG_FILE)))
19
+ return current;
20
+ if (current === parse(current).root)
21
+ return null;
22
+ }
23
+ }
24
+ /** The folder of the agjan installed in the project (node_modules, hoisted or not); null when missing. */
25
+ function localPackage(root) {
26
+ try {
27
+ return realpathSync(dirname(createRequire(join(root, 'package.json')).resolve('agjan/package.json')));
28
+ }
29
+ catch {
30
+ return null;
31
+ }
32
+ }
33
+ function defaultDelegate(bin, args, env) {
34
+ return spawnSync(process.execPath, [bin, ...args], { stdio: 'inherit', env }).status ?? 1;
35
+ }
36
+ /**
37
+ * The global `agjan` is a launcher: `init`, `--help` and `--version` run in it; every other
38
+ * command runs in the agjan version the project pins (node_modules), so a project is
39
+ * never driven by whichever version happens to be installed globally. When the pinned
40
+ * version is not installed (a fresh clone), it is installed first, after asking
41
+ * (`--yes` as the first argument skips the question). Outside an agjan project, and in
42
+ * the project's own agjan, the command runs here.
43
+ */
44
+ export async function launch(args, { cwd = process.cwd(), env = process.env, stderr = process.stderr, ask = askOnTerminal, install = installDependencies, delegate = defaultDelegate, } = {}) {
45
+ const yes = args[0] === '--yes' || args[0] === '-y';
46
+ const rest = yes ? args.slice(1) : args;
47
+ if (rest[0] === undefined || GLOBAL_COMMANDS.has(rest[0]) || env[DELEGATED])
48
+ return { run: rest };
49
+ const root = findProject(cwd);
50
+ if (!root)
51
+ return { run: rest };
52
+ const fail = (...lines) => {
53
+ stderr.write(`agjan: ${lines.join('\n')}\n`);
54
+ return { code: 1 };
55
+ };
56
+ let local = localPackage(root);
57
+ if (local === OWN_PACKAGE)
58
+ return { run: rest };
59
+ if (!local) {
60
+ const pkg = readJson(join(root, 'package.json'));
61
+ const pinned = pkg?.devDependencies?.agjan ?? pkg?.dependencies?.agjan;
62
+ const kit = readJson(join(root, CONFIG_FILE))?.kit ?? '<version>';
63
+ if (!pinned) {
64
+ return fail(`${root} is an agjan project, but agjan is not pinned in its package.json.`, `Pin it: npm install --save-dev --save-exact agjan@${kit}`);
65
+ }
66
+ const manager = detectPackageManager(root);
67
+ const answer = yes ? true : ask(`agjan ${pinned} is pinned in ${root} but not installed. Install it now (${manager} install)?`, { defaultYes: true });
68
+ if (answer === null) {
69
+ return fail(`agjan ${pinned} is pinned in ${root} but not installed, and there is no terminal to ask on.`, `Run '${manager} install' there, or run this command with --yes first: agjan --yes ${rest.join(' ')}`);
70
+ }
71
+ if (!answer)
72
+ return fail(`agjan ${pinned} is not installed in ${root}; run '${manager} install' there first.`);
73
+ install(root, manager);
74
+ local = localPackage(root);
75
+ if (!local)
76
+ return fail(`'${manager} install' finished, but agjan is still not installed in ${root}.`);
77
+ if (local === OWN_PACKAGE)
78
+ return { run: rest };
79
+ }
80
+ return { code: delegate(join(local, 'bin', 'agjan.mjs'), rest, { ...env, [DELEGATED]: '1' }) };
81
+ }
@@ -0,0 +1,21 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { existsSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { AgjanError } from './errors.js';
5
+ export const PACKAGE_MANAGERS = ['npm', 'pnpm', 'yarn', 'bun'];
6
+ const LOCKFILES = [
7
+ ['pnpm-lock.yaml', 'pnpm'],
8
+ ['yarn.lock', 'yarn'],
9
+ ['bun.lock', 'bun'],
10
+ ['bun.lockb', 'bun'],
11
+ ];
12
+ /** The package manager a project uses, from its lockfile; npm without one. */
13
+ export function detectPackageManager(dir) {
14
+ return LOCKFILES.find(([file]) => existsSync(join(dir, file)))?.[1] ?? 'npm';
15
+ }
16
+ /** Installs the project's dependencies (the pinned agjan among them) with its package manager. */
17
+ export function installDependencies(dir, manager) {
18
+ const result = spawnSync(manager, ['install'], { cwd: dir, stdio: 'inherit', shell: process.platform === 'win32' });
19
+ if (result.status !== 0)
20
+ throw new AgjanError(`${manager} install failed${result.error ? `: ${result.error.message}` : ''}; fix it and run it yourself in ${dir}`);
21
+ }
@@ -272,7 +272,7 @@ export function unitModel(ctx, slug, { onBase = false, now = Date.now() } = {})
272
272
  end: iso(end),
273
273
  last: iso(last),
274
274
  host,
275
- writer: steps.map((s) => ({ from: iso(s.from), to: iso(s.to), label: s.label })),
275
+ mainAgent: steps.map((s) => ({ from: iso(s.from), to: iso(s.to), label: s.label })),
276
276
  gates: gates.map((g) => ({ from: iso(g.from), to: iso(g.to), label: g.label.replace(/^gate /, ''), open: Boolean(g.open) })),
277
277
  events: events.map((e) => ({ at: e.at_utc, event: e.event, ...Object.fromEntries(Object.entries(e).filter(([k]) => !['at_utc', 'event'].includes(k))) })),
278
278
  commits,
@@ -313,7 +313,7 @@ export function projectModels(ctx, { now = Date.now() } = {}) {
313
313
  }
314
314
  // ---------------------------------------------------------------- Markdown
315
315
  const VERDICT_MD = { pass: '✅ pass', 'pass-with-notes': '🟡 notes', blocked: '⛔ blocked' };
316
- const TURN_MD = { you: '👤 your turn', agent: '🤖 agent working', done: '✅ done', merged: '✅ merged', idle: '⏸ idle' };
316
+ const TURN_MD = { you: '👤 your turn', agent: '🤖 main agent working', done: '✅ done', merged: '✅ merged', idle: '⏸ idle' };
317
317
  function duration(ms) {
318
318
  if (ms < 60_000)
319
319
  return `${Math.max(Math.round(ms / 1000), 0)} s`;
@@ -340,11 +340,11 @@ export function timelineRows(model) {
340
340
  const rows = [];
341
341
  for (const e of model.events) {
342
342
  if (e.event === 'step')
343
- rows.push([e.at, '🤖 writer', `${[e.stage, e.task, e.role].filter(Boolean).join(' ')} started`]);
343
+ rows.push([e.at, '🤖 main agent', `${[e.stage, e.task, e.role].filter(Boolean).join(' ')} started`]);
344
344
  if (e.event === 'gate-requested')
345
- rows.push([e.at, '🤖 writer', e.gate === 'verify' ? 'asks you to accept the feature' : `asks you to approve ${e.gate}`]);
345
+ rows.push([e.at, '🤖 main agent', e.gate === 'verify' ? 'asks you to accept the feature' : `asks you to approve ${e.gate}`]);
346
346
  if (e.event === 'amendment-proposed')
347
- rows.push([e.at, '🤖 writer', `proposes amendment ${e.amendment ?? ''}`.trim()]);
347
+ rows.push([e.at, '🤖 main agent', `proposes amendment ${e.amendment ?? ''}`.trim()]);
348
348
  if (e.event === 'round-granted')
349
349
  rows.push([e.at, '👤 human', `allows round ${e.round} for ${e.step}`]);
350
350
  if (e.event === 'auto-on')
@@ -359,7 +359,7 @@ export function timelineRows(model) {
359
359
  for (const d of model.decisions)
360
360
  rows.push([d.at, '👤 human', `${d.what}${d.detail ? `: ${d.detail}` : ''}`]);
361
361
  for (const c of model.commits)
362
- rows.push([c.at, '🤖 writer', `commit \`${c.sha}\` ${c.subject}`]);
362
+ rows.push([c.at, '🤖 main agent', `commit \`${c.sha}\` ${c.subject}`]);
363
363
  return rows.sort((a, b) => a[0].localeCompare(b[0]));
364
364
  }
365
365
  /** docs/agjan/<unit>/progress.md */
@@ -383,7 +383,7 @@ export function unitMarkdown(model, { generatedAt }) {
383
383
  out.push(`| Acceptance criteria | ${model.acs.total}: ${tested}${model.acs.manual.length ? ` · manual: ${model.acs.manual.join(', ')}` : ''} |`);
384
384
  }
385
385
  out.push(`| Reviews | ${s.reviews} · ${s.blocked} blocked · findings ${s.openFindings} open of ${s.totalFindings}, ${s.openBlockers} blocker(s) |`);
386
- const agents = [model.host ? `writer: ${model.host}` : null, ...model.reviewers.map((r) => `${r.name} (${r.model}${r.isolated ? ', isolated' : ''})`)].filter(Boolean);
386
+ const agents = [model.host ? `main agent: ${model.host}` : null, ...model.reviewers.map((r) => `${r.name} (${r.model}${r.isolated ? ', isolated' : ''})`)].filter(Boolean);
387
387
  if (agents.length)
388
388
  out.push(`| Agents | ${agents.join(' · ')} |`);
389
389
  if (model.humans.length)
package/dist/qa.js CHANGED
@@ -5,7 +5,7 @@ import { latestReview, stillBlocked } from './feature.js';
5
5
  /**
6
6
  * The QA step (design decision 81): in Verify, the QA agent (`agjan-qa`, the qa-tester
7
7
  * skill) writes and runs tests from the spec alone, without the design, the diff or the
8
- * writer's tests. Its tests stay in the project as regression tests, in two folders per
8
+ * main agent's tests. Its tests stay in the project as regression tests, in two folders per
9
9
  * feature: service tests, and UI tests where the project's Playwright tests live.
10
10
  */
11
11
  export const QA_STEP = 'qa';
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Review settings from agjan.config.json (design 7.3, 7.4): which reviewer agent runs a
3
3
  * step (`review.tiers`), how many correction rounds a step gets (`review.rounds`), and
4
- * how many attempts the writer has for failing deterministic checks
4
+ * how many attempts the main agent has for failing deterministic checks
5
5
  * (`build.fix_attempts`). `agjan status` shows them; the skills follow `status`.
6
6
  */
7
7
  import { stillBlocked } from './feature.js';
package/dist/review.js CHANGED
@@ -148,7 +148,7 @@ const CHECKLISTS = {
148
148
  build: 'Each covered AC is met by the diff. Tests exist and carry the AC id in their names. An AC that a user does on a page of a Fiori app (create a record, choose an action) has a UI test (Playwright, test/ui) besides the service tests; UI tests that agjan ui-test skipped because no browser can start here are not a finding. Project conventions. The spec\'s Authorization section, rule by rule: each role and permission is enforced in the code (for example @requires or @restrict on every entity and operation it covers; anything without them is open to every user, anonymous requests included) and covered by tests, including a negative test for a user without the role and for an anonymous request, and for every where condition a test with a user who has the role but whom the condition excludes. The service has a service-level @requires, so nothing it exposes (code lists, auto-exposed entities) is open. Security basics (authorization, input validation, no secrets; test or mocked users and other development settings only in a development profile, never active in production). Scope is checked by agjan: a file under the allowed paths (task, implicit or amended) is in scope; do not report it as out of scope.',
149
149
  fix: 'The change does exactly what the fix description says and nothing else. It is correct and complete. A test covers it where practical. No hidden scope: anything that changes behaviour beyond the description, or needs a business decision, is a blocker (it belongs in /agjan-spec).',
150
150
  map: 'Every claim in project.md is traceable to the files it points to. Services, applications and BTP services are complete. The do-not-touch list is plausible and uses real paths. Short: one to two pages, pointers instead of copies.',
151
- verify: 'Cross-task consistency. Every AC covered by a passing test or marked manual. When the context has a QA section: the QA round passed and its tests (test/qa, test/ui/qa) are part of the change; the writer fixed the code for QA blockers, never the QA tests. UI tests that agjan ui-test skipped because no browser can start here are not a finding: the final message names those ACs for the human. When the project records no test results (no results file in the context), judge coverage by the tests that carry the AC ids: missing recorded results is a project setting for the human, not a finding. The spec\'s Authorization section, rule by rule: each role and permission is enforced in the code (for example @requires or @restrict on every entity and operation it covers; anything without them is open to every user, anonymous requests included) and covered by tests, including a negative test for a user without the role and for an anonymous request. Scope is checked by agjan: a file under the allowed paths (task, implicit or amended) is in scope; do not report it as out of scope. The baseline (project.md) updated if a service, application or BTP service was added, and its section "Run locally" (start command, app URLs, test users and roles) matches the change. Do not re-review each task.',
151
+ verify: 'Cross-task consistency. Every AC covered by a passing test or marked manual. When the context has a QA section: the QA round passed and its tests (test/qa, test/ui/qa) are part of the change; the main agent fixed the code for QA blockers, never the QA tests. UI tests that agjan ui-test skipped because no browser can start here are not a finding: the final message names those ACs for the human. When the project records no test results (no results file in the context), judge coverage by the tests that carry the AC ids: missing recorded results is a project setting for the human, not a finding. The spec\'s Authorization section, rule by rule: each role and permission is enforced in the code (for example @requires or @restrict on every entity and operation it covers; anything without them is open to every user, anonymous requests included) and covered by tests, including a negative test for a user without the role and for an anonymous request. Scope is checked by agjan: a file under the allowed paths (task, implicit or amended) is in scope; do not report it as out of scope. The baseline (project.md) updated if a service, application or BTP service was added, and its section "Run locally" (start command, app URLs, test users and roles) matches the change. Do not re-review each task.',
152
152
  };
153
153
  /**
154
154
  * What the given tasks may change (design 6.5), as `agjan check` judges it: the task paths,
@@ -268,7 +268,7 @@ export function buildContextText(root, config, feature, parsed) {
268
268
  /** review_context: builds the context, stores its metadata, returns id and text. */
269
269
  /**
270
270
  * A new round of a step is pointless when nothing changed since its last round raised
271
- * findings: the reviewer would see the same files. It happens when a writer starts the
271
+ * findings: the reviewer would see the same files. It happens when the main agent starts the
272
272
  * review before (or in parallel with) its edits, and it costs one of the step's rounds.
273
273
  */
274
274
  function unchangedSinceFindings(feature, step, tree) {
@@ -439,7 +439,7 @@ export function recordReview(root, config, input, recorder) {
439
439
  /**
440
440
  * qa_context (decision 81): the QA agent's input. Only what a tester gets: the spec, how
441
441
  * to run the application and who its users are, and the test conventions; never the
442
- * design, the diff or the writer's tests. Ready once the build is complete and reviewed.
442
+ * design, the diff or the main agent's tests. Ready once the build is complete and reviewed.
443
443
  */
444
444
  export function createQaContext(root, config, { feature: slug }) {
445
445
  const feature = loadFeature(root, slug);
package/dist/terminal.js CHANGED
@@ -81,6 +81,33 @@ export function askOnTerminal(question, { defaultYes = false } = {}) {
81
81
  closeSync(tty.output);
82
82
  }
83
83
  }
84
+ /**
85
+ * Lists `choices` on the controlling terminal and asks for one or more of them, by number
86
+ * or name, separated by commas. Asks again on input it does not understand; an empty
87
+ * answer selects nothing. Returns null when there is no terminal (a script, CI or an
88
+ * agent): the caller then needs the choice from a flag.
89
+ */
90
+ export function selectOnTerminal(question, choices) {
91
+ const tty = openTerminal();
92
+ if (!tty)
93
+ return null;
94
+ try {
95
+ writeSync(tty.output, `${question}\n${choices.map((c, i) => ` ${i + 1}. ${c.label}`).join('\n')}\n`);
96
+ for (;;) {
97
+ writeSync(tty.output, 'Choose one or more (numbers or names, separated by commas): ');
98
+ const answer = readLine(tty.input).trim();
99
+ const picked = answer.split(',').map((a) => a.trim()).filter(Boolean).map((a) => choices[Number(a) - 1]?.id ?? choices.find((c) => c.id === a)?.id);
100
+ if (picked.length && picked.every(Boolean))
101
+ return [...new Set(picked)];
102
+ writeSync(tty.output, `Not understood: ${answer === '' ? '(nothing)' : answer}\n`);
103
+ }
104
+ }
105
+ finally {
106
+ closeSync(tty.input);
107
+ if (tty.output !== tty.input)
108
+ closeSync(tty.output);
109
+ }
110
+ }
84
111
  /**
85
112
  * Asks for one line on the controlling terminal with `initial` already typed, so the human
86
113
  * can edit it in place (cursor keys, backspace) or press Enter to keep it. Without line
package/docs/guide.md CHANGED
@@ -33,12 +33,28 @@ in the [design](design.md); this guide is about using it.
33
33
  Requirements: Node.js 22 or later, git, and Claude Code and/or GitHub Copilot.
34
34
 
35
35
  ```sh
36
- npm install --save-dev agjan
37
- npx agjan init --hosts claude-code,copilot # or just claude-code (the default)
38
- npx agjan doctor
36
+ npm install --global agjan
37
+ agjan init my-project --hosts claude-code,copilot # or one of them; without --hosts, init asks
38
+ cd my-project
39
+ agjan doctor
39
40
  git add -A && git commit -m "chore: set up agjan"
40
41
  ```
41
42
 
43
+ `agjan init <folder>` creates the folder, runs `git init -b main`, writes a `package.json`
44
+ (only when there is none), pins the running version of agjan in `devDependencies` and
45
+ installs it with the project's package manager (npm, pnpm, yarn or bun, from the lockfile;
46
+ `--pm` overrides). `agjan init .` does the same in the current folder and keeps what is
47
+ there: an existing repository, `package.json` and pinned version stay as they are. It stops
48
+ before changing anything when the folder already has an `agjan.config.json`, when
49
+ `package.json` is not valid JSON, or when the folder lies inside another git repository.
50
+ `--dry-run` shows the plan, `--no-install` only pins the version.
51
+
52
+ The global `agjan` runs `init`, `--help` and `--version` itself. Every other command runs
53
+ in the agjan the project pins in `node_modules`. If that is not installed (a fresh clone),
54
+ the command offers to run the install first; without a terminal it fails and says how
55
+ (`agjan --yes <command>` installs without asking). Without a global install, `npx agjan init
56
+ <folder>` works the same.
57
+
42
58
  `init` writes `agjan.config.json`, the skills (`.claude/skills/`), the reviewer agents,
43
59
  the guardrails against agents running approvals, the MCP configuration, a block in
44
60
  `AGENTS.md` and `CLAUDE.md`, a pre-commit hook and a CI workflow. Your own content in
@@ -122,8 +138,8 @@ gives you the last gate.
122
138
 
123
139
  **QA** (full-mode features; `review.qa: "off"` turns it off): before the final review, a
124
140
  tester agent, `agjan-qa`, checks the feature from the spec alone. It gets the spec, how
125
- to run the application and its users, but not the design, the code or the writer's
126
- tests, and writes tests aimed at what writers tend to miss: invalid input, users a rule
141
+ to run the application and its users, but not the design, the code or the main agent's
142
+ tests, and writes tests aimed at what main agents tend to miss: invalid input, users a rule
127
143
  excludes, anonymous requests, boundaries, doing something twice, the flows in the browser.
128
144
  It runs them and records the result like a review. A failing test is a blocker: the
129
145
  agent fixes the code, never the QA tests, and QA runs again. Something the spec does not
@@ -209,7 +225,7 @@ records (step, review, approval, amendment, fix record):
209
225
  loops round by round, tasks with their commits and reviews, the timeline of every
210
226
  event, and the findings. Committed with the unit, so the pull request shows it.
211
227
  - `.agjan/progress.html`: the whole project in one self-contained page (no extension, no
212
- internet): one row per unit, and for the selected one a swim-lane timeline (writer,
228
+ internet): one row per unit, and for the selected one a swim-lane timeline (main agent,
213
229
  reviewers, people), the review loops (select a round to see its findings), findings,
214
230
  tasks and who worked on it. `.agjan/progress.md` is the same overview as Markdown.
215
231
  Both are local (`.agjan/` is not committed).
@@ -304,7 +320,7 @@ lists replace. The schema is `node_modules/agjan/schemas/config.schema.json`.
304
320
  | `build.fix_attempts` | attempts for failing deterministic checks before the agent stops (default 3) |
305
321
  | `language` | language of the documents' text (default `en`); headings, ids and keywords stay English |
306
322
  | `limits.spec_kb`, `limits.design_kb` | soft size limits; `check` warns above them (defaults 12 and 20 KB; design covers `design.md` and `tasks.md`) |
307
- | `models.<host>.<tier>` | model of the reviewer agents per tier (`balanced`, `deep`); `"session"` (the default, written by `init` so you see it) runs the reviewer on the model of the session that starts it. Set it with `npx agjan models set deep <model>` in your terminal (`npx agjan models` lists the settings and, for Copilot, the models it offers). A deep reviewer on another model family than the writer (for example `gpt-6-sol` while the writer runs on Claude) misses other things than the writer. Model names differ per host (Claude Code: `sonnet`, `opus` or a full id; Copilot: for example `claude-opus-5.5`). Copilot uses the agent file's model unless the session was started with `--model`, which overrides it. `doctor` shows what each reviewer runs on |
323
+ | `models.<host>.<tier>` | model of the reviewer agents per tier (`balanced`, `deep`); `"session"` (the default, written by `init` so you see it) runs the reviewer on the model of the session that starts it. Set it with `npx agjan models set deep <model>` in your terminal (`npx agjan models` lists the settings and, for Copilot, the models it offers). A deep reviewer on another model family than the main agent (for example `gpt-6-sol` while the main agent runs on Claude) misses other things than the main agent. Model names differ per host (Claude Code: `sonnet`, `opus` or a full id; Copilot: for example `claude-opus-5.5`). Copilot uses the agent file's model unless the session was started with `--model`, which overrides it. `doctor` shows what each reviewer runs on |
308
324
  | `mcp.servers.<name>` | documentation MCP servers: `command`, `args`, `env`, `areas`, `enabled` |
309
325
  | `ci.policy_changes`, `ci.untracked_changes` | `warn` or `fail` in `check --ci` |
310
326
 
@@ -5,15 +5,15 @@ description: Knowledge of agjan's QA agent, the tester of the QA step in Verify.
5
5
 
6
6
  # agjan QA
7
7
 
8
- You are agjan's tester. A writer built a feature and tested it with its own tests; you
8
+ You are agjan's tester. The main agent built a feature and tested it with its own tests; you
9
9
  test it again **from the requirements alone**, the way a tester who got the spec would.
10
- Your value is the view the writer does not have: you find what its tests did not ask.
10
+ Your value is the view the main agent does not have: you find what its tests did not ask.
11
11
 
12
12
  ## The rules
13
13
 
14
14
  - **Black box.** Use only what `qa_context` gives you: the spec, how to run the
15
15
  application, its users and the test conventions. Do not read the design, the
16
- application code (`srv/`, `db/`, `app/`) or the writer's tests. You may read the
16
+ application code (`srv/`, `db/`, `app/`) or the main agent's tests. You may read the
17
17
  testing references it names, for the test mechanics only.
18
18
  - **Your folders only.** Write only in the two QA folders the context names
19
19
  (`test/qa/<feature>/` for service tests, `test/ui/qa/<feature>/` for UI tests). Never
@@ -27,7 +27,7 @@ Your value is the view the writer does not have: you find what its tests did not
27
27
  1. Call `qa_context`. It returns a `context_id` and the material.
28
28
  2. Read the spec closely: every acceptance criterion, the Authorization section, the
29
29
  non-functional requirements and the scope.
30
- 3. Derive the cases the writer most likely did not test. For each AC and rule:
30
+ 3. Derive the cases the main agent most likely did not test. For each AC and rule:
31
31
  - **negative cases:** invalid input, missing required values, wrong types, values
32
32
  just outside the allowed range;
33
33
  - **who may not:** a user without the role, a user with the role whom a condition
@@ -62,13 +62,13 @@ Your value is the view the writer does not have: you find what its tests did not
62
62
 
63
63
  ## In later rounds
64
64
 
65
- The writer fixed the code for your blockers (never your tests). Run all your tests
65
+ The main agent fixed the code for your blockers (never your tests). Run all your tests
66
66
  again, add tests where the fix suggests a related risk, and record the round. If a test
67
67
  of yours was changed by someone else, `agjan status` reports QA as stale: run it again
68
68
  and judge the current tests.
69
69
 
70
70
  ## Never
71
71
 
72
- - Read the design, the application code or the writer's tests.
72
+ - Read the design, the application code or the main agent's tests.
73
73
  - Change anything outside your QA folders, or weaken a test so that it passes.
74
74
  - Run `agjan approve`, `agjan accept`, `agjan reject`, `agjan auto` or `agjan models set`.
@@ -5,7 +5,7 @@ description: Knowledge of agjan's read-only reviewer. Used by the generated agja
5
5
 
6
6
  # agjan reviewer
7
7
 
8
- You are agjan's independent, read-only reviewer. A writer produced a document or a
8
+ You are agjan's independent, read-only reviewer. The main agent produced a document or a
9
9
  change; you judge it. You never fix anything yourself.
10
10
 
11
11
  ## How a review runs
@@ -47,7 +47,7 @@ A finding that says an API, annotation, configuration or syntax is wrong must na
47
47
  `.claude/skills/fiori-developer/references/elements.md`, section "Actions") or a project
48
48
  file that shows it. Read the reference before you claim it. If you cannot confirm the
49
49
  claim, give it at most the severity `minor` and start the issue with "Unverified:". An
50
- unverified claim must never make a writer remove working code.
50
+ unverified claim must never make the main agent remove working code.
51
51
 
52
52
  ## Rules
53
53
 
@@ -57,5 +57,5 @@ unverified claim must never make a writer remove working code.
57
57
  own preferences. Do not ask for work beyond the spec.
58
58
  - The document structure (headings, sections) is fixed by agjan and checked by a
59
59
  script. Never ask to remove, rename or add a section.
60
- - Be specific and brief. No praise, no summaries of what the writer did.
60
+ - Be specific and brief. No praise, no summaries of what the main agent did.
61
61
  - Prefer one precise blocker over several vague notes.
@@ -143,7 +143,7 @@ footer { font-size: 12.5px; color: var(--muted); border-top: 1px solid var(--lin
143
143
  <div class="gen"><span id="generated"></span><span>refresh: <code>npx agjan progress --open</code></span></div>
144
144
  </header>
145
145
  <section aria-labelledby="ov">
146
- <div class="panel-head" style="margin-bottom:10px"><h2 id="ov">Project</h2><span class="legend"><span><i style="background:var(--human)"></i>your turn</span><span><i style="background:var(--accent)"></i>agent working</span><span><i style="background:var(--pass)"></i>done or merged</span></span></div>
146
+ <div class="panel-head" style="margin-bottom:10px"><h2 id="ov">Project</h2><span class="legend"><span><i style="background:var(--human)"></i>your turn</span><span><i style="background:var(--accent)"></i>main agent working</span><span><i style="background:var(--pass)"></i>done or merged</span></span></div>
147
147
  <div class="units" id="units"></div>
148
148
  </section>
149
149
  <section class="detail" id="detail" aria-live="polite"></section>
@@ -173,7 +173,7 @@ function turnPill(u) {
173
173
  if (u.turn === 'you') return `<span class="pill you"><span class="pulse">●</span> Your turn</span>`;
174
174
  if (u.turn === 'merged') return `<span class="pill merged">✓ Merged</span>`;
175
175
  if (u.turn === 'done') return `<span class="pill merged">✓ Done</span>`;
176
- return `<span class="pill agent">Agent working</span>`;
176
+ return `<span class="pill agent">Main agent working</span>`;
177
177
  }
178
178
  function trackHtml(u) {
179
179
  return u.stages.map((s, i) => {
@@ -219,7 +219,7 @@ function timeline(u) {
219
219
  const pad = (t1 - t0) * 0.02;
220
220
  const a = t0 - pad, z = t1 + pad;
221
221
  const x = (at) => L + ((ms(at) - a) / (z - a)) * (W - L - R);
222
- const writer = u.host ? `${u.host}` : 'writer agent';
222
+ const mainAgent = u.host ? `${u.host}` : 'main agent';
223
223
  let s = `<svg viewBox="0 0 ${W} 214" width="100%" style="min-width:760px" role="img" aria-label="Timeline of ${esc(u.key)}">`;
224
224
  const tk = ticks(a, z);
225
225
  for (const t of tk.out) {
@@ -227,10 +227,10 @@ function timeline(u) {
227
227
  const iso = new Date(t).toISOString();
228
228
  s += `<line x1="${xx}" y1="14" x2="${xx}" y2="188" stroke="var(--line)" stroke-width="1"/><text class="t-tick" x="${xx}" y="206" text-anchor="middle">${tk.days ? dhm(iso) : hm(iso)}</text>`;
229
229
  }
230
- s += `<text class="t-lane" x="0" y="42">Writer</text><text class="t-sub" x="0" y="56">${esc(writer)}</text>`;
230
+ s += `<text class="t-lane" x="0" y="42">Main agent</text><text class="t-sub" x="0" y="56">${esc(mainAgent)}</text>`;
231
231
  s += `<text class="t-lane" x="0" y="102">Reviewers</text><text class="t-sub" x="0" y="116">isolated agents</text>`;
232
- s += `<text class="t-lane" x="0" y="162">People</text><text class="t-sub" x="0" y="176">gates in a terminal</text>`;
233
- for (const w of u.writer) {
232
+ s += `<text class="t-lane" x="0" y="162">Human</text><text class="t-sub" x="0" y="176">gates in a terminal</text>`;
233
+ for (const w of u.mainAgent) {
234
234
  const p = x(w.from), q = x(w.to);
235
235
  s += `<rect x="${p}" y="26" width="${Math.max(q - p, 3)}" height="26" rx="4" fill="var(--accent-bg)" stroke="var(--accent)"><title>${esc(w.label)}: ${hm(w.from)}–${hm(w.to)}</title></rect>`;
236
236
  if (q - p > 60) s += `<text class="t-bar" x="${p + 6}" y="43">${esc(w.label)}</text>`;
@@ -308,7 +308,7 @@ function renderDetail() {
308
308
  <div class="stat"><span class="v">${s.reviews} <small>${s.blocked} blocked</small></span><span class="l">reviews</span></div>
309
309
  <div class="stat"><span class="v">${s.openFindings} <small>/ ${s.totalFindings}</small></span><span class="l">findings open · ${s.openBlockers} blocker(s)</span></div>
310
310
  </div>
311
- <div class="panel"><div class="panel-head"><h3>Timeline</h3><span class="legend"><span><i style="background:var(--accent)"></i>writer step · ▲ commit</span><span><i style="background:var(--pass)"></i>pass</span><span><i style="background:var(--notes)"></i>notes</span><span><i style="background:var(--blocked)"></i>blocked</span><span><i style="background:var(--human)"></i>waiting for a human · | decision</span></span></div>
311
+ <div class="panel"><div class="panel-head"><h3>Timeline</h3><span class="legend"><span><i style="background:var(--accent)"></i>main agent step · ▲ commit</span><span><i style="background:var(--pass)"></i>pass</span><span><i style="background:var(--notes)"></i>notes</span><span><i style="background:var(--blocked)"></i>blocked</span><span><i style="background:var(--human)"></i>waiting for a human · | decision</span></span></div>
312
312
  <div class="scroll">${timeline(u)}</div></div>
313
313
  <div class="panel"><div class="panel-head"><h3>Review loops</h3><span class="muted" style="font-size:12.5px">Up to ${u.roundLimit} rounds per loop. Select a round to see what it raised and resolved.</span></div><div class="loops">${loops(u)}</div></div>
314
314
  <div class="cols">
@@ -318,7 +318,7 @@ function renderDetail() {
318
318
  <div style="display:grid;gap:16px;align-content:start">
319
319
  ${u.tasks.length ? `<div class="panel"><h3>Tasks</h3><table><thead><tr><th>Task</th><th>Commits</th><th>Reviews</th></tr></thead><tbody>${taskRows}</tbody></table></div>` : ''}
320
320
  <div class="panel"><h3>Who worked on it</h3><div class="people">
321
- ${u.host ? `<div class="who"><span class="av w">W</span><span><b>Writer</b> · ${esc(u.host)}<small>${u.writer.length} step${u.writer.length === 1 ? '' : 's'} · ${u.commits.length} commit${u.commits.length === 1 ? '' : 's'}</small></span></div>` : ''}
321
+ ${u.host ? `<div class="who"><span class="av w">M</span><span><b>Main agent</b> · ${esc(u.host)}<small>${u.mainAgent.length} step${u.mainAgent.length === 1 ? '' : 's'} · ${u.commits.length} commit${u.commits.length === 1 ? '' : 's'}</small></span></div>` : ''}
322
322
  ${reviewers}${people}
323
323
  ${!u.host && !reviewers && !people ? '<p class="empty">Nobody yet.</p>' : ''}
324
324
  </div></div>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agjan",
3
- "version": "0.0.13",
3
+ "version": "0.0.14",
4
4
  "description": "Spec-driven workflow kit for AI coding agents, with human approval gates and a read-only reviewer at every step.",
5
5
  "keywords": [
6
6
  "ai",