agjan 0.0.12 โ†’ 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.
@@ -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
- import { CONFIG_FILE, MODEL_TIERS, SESSION_MODEL, agentModel, loadConfig, loadDomain } from '../config.js';
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}: ${MODEL_TIERS.map((t) => `${t} ${agentModel(config, h, t) ?? 'session model'}`).join(', ')}`).join('; '));
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)');
@@ -14,6 +14,7 @@ import { NOT_ACCEPTED, runChecks } from './check.js';
14
14
  import { readLog } from '../log.js';
15
15
  import { finalSteps } from '../progress-view.js';
16
16
  import { readAutoDefault } from '../auto.js';
17
+ import { QA_STEP, qaState, qaTestFiles } from '../qa.js';
17
18
  /** One indented row: a label column, then the value. `next` and `blocks` stand out. */
18
19
  function row(ctx, label, value) {
19
20
  const s = ctx.style;
@@ -32,8 +33,25 @@ function reviewNext(ctx, feature, step) {
32
33
  return `the ${step} review is still blocked after ${state.round} of ${state.limit} rounds: ask the user whether to run another round (yes: npx agjan review extend ${step}) or to stop and take over (fix with them, accept findings, or change the documents)`;
33
34
  }
34
35
  const round = state.round ? `, round ${state.next} of ${state.limit}` : '';
36
+ if (step === QA_STEP)
37
+ return `QA (step qa) with ${reviewerFor(ctx.config, step)}${round}`;
35
38
  return `review step ${step} with ${reviewerFor(ctx.config, step)}${round}`;
36
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
+ }
37
55
  /** The review step a feature in Spec or Design needs next. */
38
56
  function gateStep(feature) {
39
57
  if (feature.stage === 'design')
@@ -66,8 +84,19 @@ function nextInBuild(ctx, feature, progress) {
66
84
  return `${ctx.style.green('done')}: verified (${record.id}) and accepted by ${acceptance.approval.by}; the next steps below are optional`;
67
85
  return `${ctx.style.green('verified')} (${record.id}): a human accepts it in a terminal: '${ctx.style.bold('npx agjan approve verify')}'`;
68
86
  }
69
- if (lastStage === 'verify')
87
+ if (lastStage === 'verify') {
88
+ // In Verify, QA comes before the final review (decision 81).
89
+ const qa = qaState(ctx.root, ctx.config, feature);
90
+ if (qa.state === 'due' || qa.state === 'stale')
91
+ return `${reviewNext(ctx, feature, QA_STEP)}: it writes and runs tests from the spec (/agjan-verify, QA)`;
92
+ if (qa.state === 'blocked') {
93
+ const rounds = roundState(feature, ctx.config, QA_STEP);
94
+ if (rounds.exhausted)
95
+ return reviewNext(ctx, feature, QA_STEP);
96
+ return `the QA round ${qa.record.id} is blocked: fix the code (never the QA tests), then ${reviewNext(ctx, feature, QA_STEP)}`;
97
+ }
70
98
  return 'verify is running: /agjan-verify';
99
+ }
71
100
  return feature.approvals.auto ? 'all tasks done and reviewed: auto mode: the agent goes on with /agjan-verify' : 'all tasks done and reviewed: a human starts the verification: /agjan-verify';
72
101
  }
73
102
  /** "2 open, 1 blocker(s)", red when a blocker is open. */
@@ -199,10 +228,17 @@ async function describe(ctx, feature, onBase = false) {
199
228
  return describeRecord(ctx, feature, onBase);
200
229
  if (onBase)
201
230
  return describeOnBase(ctx, feature);
202
- 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)}`);
203
233
  row(ctx, 'spec', tone(ctx.style, feature.state.spec));
204
234
  const mode = feature.design?.parsed.mode ? ` (${feature.design.parsed.mode})` : '';
205
235
  row(ctx, 'design', `${tone(ctx.style, feature.state.design)}${mode}`);
236
+ const qa = qaState(ctx.root, ctx.config, feature);
237
+ if (qa.state !== 'off' && feature.stage === 'build') {
238
+ const tests = qaTestFiles(ctx.root, feature.slug).length;
239
+ const text = qa.state === 'due' ? 'not run yet: in Verify, agjan-qa writes and runs tests from the spec' : `${tone(ctx.style, qa.state)} (${qa.record.id}, ${tests} QA test file(s))`;
240
+ row(ctx, 'qa', text);
241
+ }
206
242
  const auto = feature.approvals.auto;
207
243
  if (auto)
208
244
  row(ctx, 'auto', `${ctx.style.yellow('on')} (switched on by ${auto.by}, ${auto.at_utc}): spec and design pass automatically after their reviews; approve verify stays yours`);
package/dist/config.js CHANGED
@@ -10,9 +10,13 @@ const KIT_DIR = new URL('../kit/', import.meta.url);
10
10
  */
11
11
  export const SESSION_MODEL = 'session';
12
12
  export const MODEL_TIERS = ['balanced', 'deep'];
13
+ /** Every agent tier `agjan models` sets: the reviewers' and the QA agent's (decision 81). */
14
+ export const AGENT_TIERS = [...MODEL_TIERS, 'qa'];
13
15
  /** The model to write into an agent file, or undefined for the session's model. */
14
16
  export function agentModel(config, host, tier) {
15
- const value = config.models?.[host]?.[tier] ?? config.models?.[host]?.balanced;
17
+ const models = config.models?.[host];
18
+ // The QA agent runs on the deep model unless it has its own (decision 81).
19
+ const value = models?.[tier] ?? (tier === 'qa' ? models?.deep : undefined) ?? models?.balanced;
16
20
  return value && value !== SESSION_MODEL ? value : undefined;
17
21
  }
18
22
  /** Package defaults. Domain defaults and project overrides are layered on top. */
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
+ }
package/dist/mcp.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { createInterface } from 'node:readline';
2
- import { createReviewContext, recordReview } from './review.js';
2
+ import { createQaContext, createReviewContext, recordQa, recordReview } from './review.js';
3
3
  import { selectFeature } from './feature.js';
4
4
  import { AgjanError } from './errors.js';
5
5
  /**
@@ -24,6 +24,38 @@ const FINDING_SCHEMA = {
24
24
  required: ['severity', 'issue'],
25
25
  additionalProperties: false,
26
26
  };
27
+ /** The QA agent's tools (decision 81): its own server, so the reviewer never sees them. */
28
+ export const QA_TOOLS = [
29
+ {
30
+ name: 'qa_context',
31
+ title: 'agjan: get QA context',
32
+ description: 'Returns the tester\'s inputs for the QA step of an agjan feature and a context_id: the spec, how to run the ' +
33
+ 'application, its users, the test conventions and your QA folders. Write and run tests only from this material.',
34
+ inputSchema: {
35
+ type: 'object',
36
+ properties: { feature: { type: 'string', description: 'Feature slug; optional when exactly one feature changed on the branch' } },
37
+ additionalProperties: false,
38
+ },
39
+ annotations: { readOnlyHint: true },
40
+ },
41
+ {
42
+ name: 'qa_record',
43
+ title: 'agjan: record QA result',
44
+ description: 'Records the QA result for a context_id: verdict, findings (failing tests, spec questions) and the ids of earlier ' +
45
+ 'QA findings that pass now. Refused if files outside your QA folders changed.',
46
+ inputSchema: {
47
+ type: 'object',
48
+ properties: {
49
+ context_id: { type: 'string' },
50
+ verdict: { type: 'string', enum: ['pass', 'pass-with-notes', 'blocked'] },
51
+ findings: { type: 'array', items: FINDING_SCHEMA, maxItems: 50 },
52
+ resolves: { type: 'array', items: { type: 'string' } },
53
+ },
54
+ required: ['context_id', 'verdict'],
55
+ additionalProperties: false,
56
+ },
57
+ },
58
+ ];
27
59
  export const TOOLS = [
28
60
  {
29
61
  name: 'review_context',
@@ -66,6 +98,19 @@ function text(content, isError = false) {
66
98
  /** Handles one tools/call; tool failures are results with isError, not protocol errors. */
67
99
  function callTool(ctx, server, name, args = {}) {
68
100
  try {
101
+ if (server.role === 'qa') {
102
+ if (name === 'qa_context') {
103
+ const feature = selectFeature(ctx.root, ctx.config, args.feature);
104
+ const { id, text: body } = createQaContext(ctx.root, ctx.config, { feature });
105
+ return text(`context_id: ${id}\n\n${body}`);
106
+ }
107
+ if (name === 'qa_record') {
108
+ const record = recordQa(ctx.root, ctx.config, args, { host: server.host, isolation: server.isolation, now: ctx.now });
109
+ const ids = record.findings.map((f) => f.id).join(', ') || 'none';
110
+ return text(`recorded ${record.id} (qa, round ${record.round}): ${record.verdict}; findings: ${ids}; QA tests: ${record.qa_tests?.length ?? 0}`);
111
+ }
112
+ return null;
113
+ }
69
114
  if (name === 'review_context') {
70
115
  const feature = selectFeature(ctx.root, ctx.config, args.feature);
71
116
  const { id, text: body } = createReviewContext(ctx.root, ctx.config, { feature, step: args.step });
@@ -107,7 +152,7 @@ export function handleMessage(ctx, server, message) {
107
152
  case 'ping':
108
153
  return reply({});
109
154
  case 'tools/list':
110
- return reply({ tools: TOOLS });
155
+ return reply({ tools: server.role === 'qa' ? QA_TOOLS : TOOLS });
111
156
  case 'tools/call': {
112
157
  const result = callTool(ctx, server, params?.name, params?.arguments);
113
158
  return result ? reply(result) : fail(-32602, `unknown tool '${params?.name}'`);
@@ -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
+ }
@@ -1,7 +1,7 @@
1
1
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
3
  import { git } from './git.js';
4
- import { loadConfig } from './config.js';
4
+ import { agentModel, loadConfig } from './config.js';
5
5
  import { FEATURES_DIR, changedFeatures, listFeatures, loadFeature, stillBlocked } from './feature.js';
6
6
  import { readLog } from './log.js';
7
7
  import { acceptanceState, buildProgress, verifyState } from './progress.js';
@@ -166,7 +166,7 @@ export function unitModel(ctx, slug, { onBase = false, now = Date.now() } = {})
166
166
  round: r.round,
167
167
  verdict: r.verdict,
168
168
  at: r.at_utc,
169
- tier: reviewerFor(config, r.step) === 'agjan-reviewer-deep' ? 'deep' : 'balanced',
169
+ tier: { 'agjan-reviewer-deep': 'deep', 'agjan-qa': 'qa' }[reviewerFor(config, r.step)] ?? 'balanced',
170
170
  host: r.reviewer?.host ?? null,
171
171
  isolation: r.reviewer?.isolation ?? null,
172
172
  findings: (r.findings ?? []).map((f) => f.id),
@@ -237,14 +237,14 @@ export function unitModel(ctx, slug, { onBase = false, now = Date.now() } = {})
237
237
  shown.push({ ...d });
238
238
  }
239
239
  const tierModel = (tier) => {
240
- const value = host ? config.models?.[host]?.[tier] : undefined;
240
+ const value = host ? agentModel(config, host, tier) : undefined;
241
241
  return !value || value === 'session' ? 'session model' : value;
242
242
  };
243
- const reviewers = ['balanced', 'deep']
243
+ const reviewers = ['balanced', 'deep', 'qa']
244
244
  .map((tier) => {
245
245
  const own = reviews.filter((r) => r.tier === tier);
246
246
  return {
247
- name: tier === 'deep' ? 'agjan-reviewer-deep' : 'agjan-reviewer',
247
+ name: tier === 'qa' ? 'agjan-qa' : tier === 'deep' ? 'agjan-reviewer-deep' : 'agjan-reviewer',
248
248
  tier,
249
249
  model: tierModel(tier),
250
250
  count: own.length,
@@ -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')
@@ -354,12 +354,12 @@ export function timelineRows(model) {
354
354
  }
355
355
  for (const r of model.reviews) {
356
356
  const what = r.findings.length ? ` (${severities(r.findings, model.findings)})` : '';
357
- rows.push([r.at, `๐Ÿ” reviewer${r.tier === 'deep' ? ' (deep)' : ''}`, `${r.step} ยท round ${r.round} โ†’ ${VERDICT_MD[r.verdict]}${what}`]);
357
+ rows.push([r.at, r.tier === 'qa' ? '๐Ÿงช qa' : `๐Ÿ” reviewer${r.tier === 'deep' ? ' (deep)' : ''}`, `${r.step} ยท round ${r.round} โ†’ ${VERDICT_MD[r.verdict]}${what}`]);
358
358
  }
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)