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.
package/dist/qa.js ADDED
@@ -0,0 +1,77 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { existsSync, readFileSync, readdirSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { latestReview, stillBlocked } from './feature.js';
5
+ /**
6
+ * The QA step (design decision 81): in Verify, the QA agent (`agjan-qa`, the qa-tester
7
+ * skill) writes and runs tests from the spec alone, without the design, the diff or the
8
+ * main agent's tests. Its tests stay in the project as regression tests, in two folders per
9
+ * feature: service tests, and UI tests where the project's Playwright tests live.
10
+ */
11
+ export const QA_STEP = 'qa';
12
+ /** The folders a feature's QA tests live in; the only paths the QA agent writes. */
13
+ export function qaDirs(slug) {
14
+ return [`test/qa/${slug}/`, `test/ui/qa/${slug}/`];
15
+ }
16
+ /** QA runs for full-mode features unless the project turns it off (`review.qa: "off"`). */
17
+ export function qaApplies(config, feature) {
18
+ return feature.kind === 'feature' && feature.design?.parsed.mode === 'full' && config.review?.qa !== 'off';
19
+ }
20
+ function filesUnder(root, dir) {
21
+ const abs = join(root, dir);
22
+ if (!existsSync(abs))
23
+ return [];
24
+ const out = [];
25
+ const walk = (rel) => {
26
+ for (const entry of readdirSync(join(root, rel), { withFileTypes: true })) {
27
+ const path = `${rel}${entry.name}`;
28
+ if (entry.isDirectory())
29
+ walk(`${path}/`);
30
+ else if (entry.isFile())
31
+ out.push(path);
32
+ }
33
+ };
34
+ walk(dir);
35
+ return out;
36
+ }
37
+ /** The QA test files of a feature, sorted, as repository paths. */
38
+ export function qaTestFiles(root, slug) {
39
+ return qaDirs(slug).flatMap((dir) => filesUnder(root, dir)).sort();
40
+ }
41
+ /** Hash of the feature's QA tests as they are now: a change after QA makes it stale. */
42
+ export function qaTestsHash(root, slug) {
43
+ const hash = createHash('sha256');
44
+ for (const file of qaTestFiles(root, slug)) {
45
+ hash.update(file).update('\0').update(createHash('sha256').update(readFileSync(join(root, file))).digest('hex')).update('\0');
46
+ }
47
+ return `sha256:${hash.digest('hex')}`;
48
+ }
49
+ /**
50
+ * Where QA stands: `off` (light mode, or turned off), `due` (no QA round yet), `blocked`
51
+ * (its blockers are open: fix the code, then QA again), `stale` (the QA tests changed
52
+ * after the round: QA again) or `passed`. Code changes after a passing round are the
53
+ * final review's to judge, not QA's.
54
+ */
55
+ export function qaState(root, config, feature) {
56
+ if (!qaApplies(config, feature))
57
+ return { state: 'off', record: null };
58
+ const record = latestReview(feature.reviews, [QA_STEP]);
59
+ if (!record)
60
+ return { state: 'due', record: null };
61
+ if (stillBlocked(feature, record))
62
+ return { state: 'blocked', record };
63
+ if (record.qa_tests_hash !== qaTestsHash(root, feature.slug))
64
+ return { state: 'stale', record };
65
+ return { state: 'passed', record };
66
+ }
67
+ /** Why the final review and the acceptance wait for QA, or null when they need not. */
68
+ export function qaProblem(root, config, feature) {
69
+ const qa = qaState(root, config, feature);
70
+ if (qa.state === 'due')
71
+ return 'QA has not run yet: delegate step qa to agjan-qa';
72
+ if (qa.state === 'blocked')
73
+ return `the QA round ${qa.record.id} is blocked: fix the code (never the QA tests), then run QA again`;
74
+ if (qa.state === 'stale')
75
+ return `the QA tests changed after the QA round ${qa.record.id}: run QA again`;
76
+ return null;
77
+ }
@@ -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';
@@ -15,6 +15,7 @@ export const DEFAULT_TIERS = {
15
15
  verify: 'deep',
16
16
  fix: 'balanced',
17
17
  map: 'balanced',
18
+ qa: 'qa',
18
19
  };
19
20
  /** `build:cap` and `build:T2` are both of kind `build`. */
20
21
  export function stepKind(step) {
@@ -24,7 +25,7 @@ export function stepKind(step) {
24
25
  export function reviewerFor(config, step) {
25
26
  const kind = stepKind(step);
26
27
  const tier = config.review?.tiers?.[kind] ?? DEFAULT_TIERS[kind] ?? 'balanced';
27
- return tier === 'deep' ? 'agjan-reviewer-deep' : 'agjan-reviewer';
28
+ return tier === 'qa' ? 'agjan-qa' : tier === 'deep' ? 'agjan-reviewer-deep' : 'agjan-reviewer';
28
29
  }
29
30
  export function roundLimit(config) {
30
31
  return config.review?.rounds ?? 3;
package/dist/review.js CHANGED
@@ -15,6 +15,8 @@ import { LOG_FILE, appendLog } from './log.js';
15
15
  import { AgjanError } from './errors.js';
16
16
  import { nextRound } from './review-policy.js';
17
17
  import { designProblems, documentProblems } from './validate.js';
18
+ import { QA_STEP, qaApplies, qaDirs, qaProblem, qaState, qaTestFiles, qaTestsHash } from './qa.js';
19
+ import { buildProgress } from './progress.js';
18
20
  export const REVIEW_MD = 'review.md';
19
21
  const CONTEXT_DIR = '.agjan/review-contexts';
20
22
  /** Limit for diffs inside a review context, so a huge change cannot flood the reviewer. */
@@ -48,11 +50,11 @@ function currentContent(path) {
48
50
  * (committed, staged, unstaged, untracked) with its current content, except the
49
51
  * feature's script-owned files. Any write to the working tree changes it.
50
52
  */
51
- export function treeHash(root, config, slug) {
53
+ export function treeHash(root, config, slug, except = []) {
52
54
  const skip = scriptOwned(slug);
53
55
  const hash = createHash('sha256');
54
56
  for (const file of changedFiles(root, resolveBase(root, config.git?.base))) {
55
- if (skip.has(file) || file.startsWith('.agjan/'))
57
+ if (skip.has(file) || file.startsWith('.agjan/') || except.some((dir) => file.startsWith(dir)))
56
58
  continue;
57
59
  const content = currentContent(join(root, file));
58
60
  hash.update(file).update('\0');
@@ -72,7 +74,7 @@ export function parseStep(step, feature, config) {
72
74
  }
73
75
  if (step === 'fix' || step === 'map')
74
76
  throw new AgjanError(`'${step}' reviews belong to a ${step} record, not to a feature`);
75
- if (['spec', 'design', 'design:light', 'verify'].includes(step))
77
+ if (['spec', 'design', 'design:light', 'verify', QA_STEP].includes(step))
76
78
  return { step, kind: step };
77
79
  const match = /^build:(.+)$/.exec(step ?? '');
78
80
  if (!match)
@@ -146,7 +148,7 @@ const CHECKLISTS = {
146
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.',
147
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).',
148
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.',
149
- verify: 'Cross-task consistency. Every AC covered by a passing test or marked manual. 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.',
150
152
  };
151
153
  /**
152
154
  * What the given tasks may change (design 6.5), as `agjan check` judges it: the task paths,
@@ -244,6 +246,13 @@ export function buildContextText(root, config, feature, parsed) {
244
246
  parts.push(section(docPath(feature, 'tasks.md'), fence(feature.tasks.text, 'md')));
245
247
  parts.push(section('Allowed paths (scope, enforced by agjan check)', scopeText(scopeOf(config, feature, feature.tasks.parsed.tasks))));
246
248
  parts.push(section('Changed files', changed.map((f) => `- ${f}`).join('\n') || '(none)'));
249
+ const qa = qaState(root, config, feature);
250
+ if (qa.state !== 'off') {
251
+ const tests = qaTestFiles(root, feature.slug);
252
+ parts.push(section('QA (tests written from the spec by the QA agent)', qa.record
253
+ ? `${qa.record.id} round ${qa.record.round}: ${qa.record.verdict} (${qa.state}); ${tests.length} QA test file(s):\n${tests.map((f) => `- ${f}`).join('\n')}`
254
+ : 'not run'));
255
+ }
247
256
  parts.push(section('Full diff', fence(diffOf(root, base, changed), 'diff')));
248
257
  }
249
258
  if (baselineText && parsed.kind !== 'build' && parsed.kind !== 'fix')
@@ -259,7 +268,7 @@ export function buildContextText(root, config, feature, parsed) {
259
268
  /** review_context: builds the context, stores its metadata, returns id and text. */
260
269
  /**
261
270
  * A new round of a step is pointless when nothing changed since its last round raised
262
- * 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
263
272
  * review before (or in parallel with) its edits, and it costs one of the step's rounds.
264
273
  */
265
274
  function unchangedSinceFindings(feature, step, tree) {
@@ -298,6 +307,12 @@ export function createReviewContext(root, config, { feature: slug, step }) {
298
307
  const feature = loadFeature(root, slug);
299
308
  const parsed = parseStep(step, feature, config);
300
309
  unfinishedDocuments(feature, config, parsed.step);
310
+ if (parsed.step === QA_STEP)
311
+ throw new AgjanError('step qa is done by the QA agent (agjan-qa, qa_context), not by a reviewer');
312
+ // The final review comes after QA (decision 81).
313
+ const qa = parsed.step === 'verify' ? qaProblem(root, config, feature) : null;
314
+ if (qa)
315
+ throw new AgjanError(`the final review waits for QA: ${qa}`);
301
316
  const tree = treeHash(root, config, feature.slug);
302
317
  unchangedSinceFindings(feature, parsed.step, tree);
303
318
  const text = buildContextText(root, config, feature, parsed);
@@ -339,19 +354,17 @@ function validFinding(f, i) {
339
354
  return `${where} has unknown field(s): ${extra.join(', ')}`;
340
355
  return null;
341
356
  }
342
- /**
343
- * review_record: validates the reviewer's result against its context and appends it.
344
- * Refuses when anything in the working tree changed since the context was produced.
345
- */
346
- export function recordReview(root, config, { context_id: contextId, verdict, findings = [], resolves = [] }, { host = 'unknown', isolation = 'unknown', now }) {
357
+ /** Checks a result against its context; shared by review_record and qa_record. */
358
+ function validResult(root, { context_id: contextId, verdict, findings = [], resolves = [] }, kind) {
347
359
  if (typeof contextId !== 'string' || !/^[A-Z][A-Z0-9]{1,5}-C[0-9a-f]{8}$/.test(contextId))
348
360
  throw new AgjanError('context_id is missing or malformed');
349
361
  const metaFile = join(root, CONTEXT_DIR, `${contextId}.json`);
350
362
  const meta = readJson(metaFile);
351
- if (!meta)
352
- throw new AgjanError(`unknown context ${contextId}; call review_context first`);
363
+ const call = kind === 'qa' ? 'qa_context' : 'review_context';
364
+ if (!meta || (meta.kind ?? 'review') !== kind)
365
+ throw new AgjanError(`unknown context ${contextId}; call ${call} first`);
353
366
  if (meta.recorded)
354
- throw new AgjanError(`context ${contextId} was already used for ${meta.recorded}; call review_context again`);
367
+ throw new AgjanError(`context ${contextId} was already used for ${meta.recorded}; call ${call} again`);
355
368
  if (typeof verdict !== 'string' || !VERDICTS.includes(verdict))
356
369
  throw new AgjanError(`verdict must be one of ${VERDICTS.join(', ')}`);
357
370
  if (!Array.isArray(findings) || findings.length > 50)
@@ -373,10 +386,11 @@ export function recordReview(root, config, { context_id: contextId, verdict, fin
373
386
  const unknown = resolves.filter((id) => !open.has(id));
374
387
  if (unknown.length)
375
388
  throw new AgjanError(`resolves lists findings that are not open: ${unknown.join(', ')}`);
376
- if (treeHash(root, config, feature.slug) !== meta.tree_hash) {
377
- throw new AgjanError('the working tree changed since review_context was called; nothing was recorded. ' +
378
- 'A reviewer must not change files. Call review_context again and review the current state.');
379
- }
389
+ return { contextId, metaFile, meta, feature, verdict: verdict, findings: findings, resolves: resolves };
390
+ }
391
+ /** Appends a record to reviews.json, regenerates review.md and logs it. */
392
+ function storeRecord(root, result, { host = 'unknown', isolation = 'unknown', now }, extra) {
393
+ const { contextId, metaFile, meta, feature } = result;
380
394
  const records = feature.reviews.records;
381
395
  let next = feature.findings.length;
382
396
  const record = {
@@ -388,12 +402,12 @@ export function recordReview(root, config, { context_id: contextId, verdict, fin
388
402
  context: contextId,
389
403
  documents: meta.documents,
390
404
  inputs_hash: meta.inputs_hash,
391
- tree_hash: meta.tree_hash,
392
405
  base_commit: meta.base_commit,
393
406
  head_commit: meta.head_commit,
394
- verdict: verdict,
395
- resolves: resolves,
396
- findings: findings.map((f) => ({ id: `${feature.key}-F${++next}`, ...f })),
407
+ verdict: result.verdict,
408
+ resolves: result.resolves,
409
+ findings: result.findings.map((f) => ({ id: `${feature.key}-F${++next}`, ...f })),
410
+ ...extra,
397
411
  };
398
412
  records.push(record);
399
413
  writeJson(join(feature.dir, REVIEWS_FILE), { schema: 1, records });
@@ -410,6 +424,91 @@ export function recordReview(root, config, { context_id: contextId, verdict, fin
410
424
  });
411
425
  return record;
412
426
  }
427
+ /**
428
+ * review_record: validates the reviewer's result against its context and appends it.
429
+ * Refuses when anything in the working tree changed since the context was produced.
430
+ */
431
+ export function recordReview(root, config, input, recorder) {
432
+ const result = validResult(root, input, 'review');
433
+ if (treeHash(root, config, result.feature.slug) !== result.meta.tree_hash) {
434
+ throw new AgjanError('the working tree changed since review_context was called; nothing was recorded. ' +
435
+ 'A reviewer must not change files. Call review_context again and review the current state.');
436
+ }
437
+ return storeRecord(root, result, recorder, { tree_hash: result.meta.tree_hash });
438
+ }
439
+ /**
440
+ * qa_context (decision 81): the QA agent's input. Only what a tester gets: the spec, how
441
+ * to run the application and who its users are, and the test conventions; never the
442
+ * design, the diff or the main agent's tests. Ready once the build is complete and reviewed.
443
+ */
444
+ export function createQaContext(root, config, { feature: slug }) {
445
+ const feature = loadFeature(root, slug);
446
+ if (!qaApplies(config, feature))
447
+ throw new AgjanError(`QA does not apply to ${slug}: it runs for full-mode features (review.qa is ${config.review?.qa ?? 'on'})`);
448
+ if (feature.stage !== 'build' || !feature.spec)
449
+ throw new AgjanError(`${slug} is not in Build yet; QA runs in Verify`);
450
+ const progress = buildProgress(root, config, feature);
451
+ if (!progress.complete || progress.due.length)
452
+ throw new AgjanError('QA runs after the build: every task committed and its reviews done (npx agjan status)');
453
+ const dirs = qaDirs(feature.slug);
454
+ const baseline = join(root, FEATURES_DIR, 'project.md');
455
+ const runLocally = existsSync(baseline) ? (/^## Run locally\s*$([\s\S]*?)(?=^## |\s*$(?![\s\S]))/m.exec(readFileSync(baseline, 'utf8'))?.[1] ?? '').trim() : '';
456
+ const areaNames = [...new Set(feature.tasks.parsed.tasks.map((t) => resolveArea(config, t.area)?.name).filter((name) => Boolean(name)))];
457
+ const commands = areaNames.map((a) => `- ${a}: ${config.verify?.[a]?.test ?? 'npm test'} (tests: ${(config.tests[a] ?? []).join(', ') || '-'})`).join('\n');
458
+ const ui = Boolean(readJson(join(root, 'package.json'))?.scripts?.['test:ui']);
459
+ const existing = qaTestFiles(root, feature.slug);
460
+ const parts = [
461
+ `# QA context: ${feature.slug} (${feature.key}), step qa`,
462
+ '',
463
+ 'You are the tester. You know the requirements, not the code: do not read the design, the application code or the existing tests, and do not change anything outside your QA folders.',
464
+ '',
465
+ section('Your QA folders (the only paths you write)', `${dirs.map((d) => `- \`${d}\``).join('\n')}\n\nService tests go into \`${dirs[0]}\`, UI tests (Playwright) into \`${dirs[1]}\`. Name each test \`${feature.key}-AC<n> QA: <what it checks>\`. They stay in the project as regression tests.`),
466
+ section(docPath(feature, 'spec.md'), fence(feature.spec.text, 'md')),
467
+ section('Run locally (from docs/agjan/project.md)', runLocally || '(not described: start the application as the project README or package.json says)'),
468
+ section('Test conventions', `${commands}\n- UI tests: ${ui ? '`npx agjan ui-test` runs the Playwright tests (it skips them, with the reason, where no browser can start)' : 'the project has no Playwright setup (no `test:ui` script): write service tests only'}\n- How tests are written in this stack: \`.claude/skills/cap-developer/references/testing.md\` (cds.test) and \`.claude/skills/fiori-developer/references/testing.md\` (Playwright). Read those for the test mechanics only.`),
469
+ section('Your tests from earlier QA rounds', existing.length ? existing.map((f) => `- ${f}`).join('\n') : '(none: this is the first QA round)'),
470
+ section('Earlier rounds', reviewHistory(feature)),
471
+ section('Open findings', openFindings(feature, [QA_STEP])),
472
+ section('How to record your result', 'Run your tests. Then call qa_record with this context_id, a verdict (pass, pass-with-notes, blocked), your findings and in `resolves` the ids of earlier QA findings that pass now. ' +
473
+ 'A test that fails against an acceptance criterion or an authorization rule is a blocker (file: the test file; evidence: the test name and the failure output). ' +
474
+ 'Something the spec does not decide is a minor finding starting with "Spec question:". A blocker requires the verdict blocked.'),
475
+ ];
476
+ const text = parts.join('\n');
477
+ const id = `${feature.key}-C${randomBytes(4).toString('hex')}`;
478
+ const base = resolveBase(root, config.git?.base);
479
+ const meta = {
480
+ id,
481
+ kind: 'qa',
482
+ feature: feature.slug,
483
+ step: QA_STEP,
484
+ documents: { spec: feature.spec.hash, design: feature.designHash ?? undefined },
485
+ inputs_hash: sha256(text),
486
+ tree_hash: treeHash(root, config, feature.slug, dirs),
487
+ base_commit: mergeBase(root, base),
488
+ head_commit: git(root, ['rev-parse', '--verify', '--quiet', 'HEAD'], { allowFail: true })?.trim() ?? null,
489
+ };
490
+ const dir = join(root, CONTEXT_DIR);
491
+ mkdirSync(dir, { recursive: true });
492
+ writeJson(join(dir, `${id}.json`), meta);
493
+ return { id, text };
494
+ }
495
+ /**
496
+ * qa_record: the QA agent's result. Refused when it changed anything outside its QA
497
+ * folders; records the hash of its tests, so a later change to them makes QA stale.
498
+ */
499
+ export function recordQa(root, config, input, recorder) {
500
+ const result = validResult(root, input, 'qa');
501
+ const slug = result.feature.slug;
502
+ if (treeHash(root, config, slug, qaDirs(slug)) !== result.meta.tree_hash) {
503
+ throw new AgjanError(`files outside the QA folders (${qaDirs(slug).join(', ')}) changed since qa_context was called; nothing was recorded. ` +
504
+ 'QA writes only its own tests. Undo the other changes, then call qa_context again.');
505
+ }
506
+ return storeRecord(root, result, recorder, {
507
+ tree_hash: treeHash(root, config, slug),
508
+ qa_tests_hash: qaTestsHash(root, slug),
509
+ qa_tests: qaTestFiles(root, slug),
510
+ });
511
+ }
413
512
  /** Renders review.md from reviews.json (design 8.5). Generated; never edited by hand. */
414
513
  export function renderReviewMd(feature) {
415
514
  const out = [`# Reviews: ${feature.slug} (${feature.key})`, '', '<!-- Generated by agjan from reviews.json. Do not edit. -->', ''];
package/dist/scope.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import picomatch from 'picomatch';
2
2
  import { resolveArea } from './config.js';
3
+ import { qaDirs } from './qa.js';
3
4
  /** A path ending in '/' means the whole folder. */
4
5
  function toGlob(pattern) {
5
6
  return pattern.endsWith('/') ? `${pattern}**` : pattern;
@@ -26,5 +27,8 @@ export function allowedPatterns(feature, config) {
26
27
  if (amendment.status === 'approved')
27
28
  patterns.push(...amendment.paths);
28
29
  }
30
+ // The QA agent's tests (decision 81).
31
+ if (feature.kind === 'feature')
32
+ patterns.push(...qaDirs(feature.slug));
29
33
  return patterns;
30
34
  }
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
@@ -116,9 +132,24 @@ again; then Build continues. Until then `agjan check` reports one error, that th
116
132
  files wait for the revised design, and the pre-commit hook lets only the documents be
117
133
  committed.
118
134
 
119
- **Verify**: `/agjan-verify`. Full build, tests and lint, the baseline update, the final
120
- deep review, `agjan check --ci` and `report.md`. It ends with a completion block that
121
- gives you the last gate:
135
+ **Verify**: `/agjan-verify`. Full build, tests and lint, the baseline update, QA, the
136
+ final deep review, `agjan check --ci` and `report.md`. It ends with a completion block that
137
+ gives you the last gate.
138
+
139
+ **QA** (full-mode features; `review.qa: "off"` turns it off): before the final review, a
140
+ tester agent, `agjan-qa`, checks the feature from the spec alone. It gets the spec, how
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
143
+ excludes, anonymous requests, boundaries, doing something twice, the flows in the browser.
144
+ It runs them and records the result like a review. A failing test is a blocker: the
145
+ agent fixes the code, never the QA tests, and QA runs again. Something the spec does not
146
+ decide comes to you as a "Spec question". The tests stay in `test/qa/<feature>/` (UI tests
147
+ in `test/ui/qa/<feature>/`) as regression tests; a change to them after QA makes QA run
148
+ again. The final review, `check --ci` and `approve verify` wait for a passing QA round.
149
+ QA runs on the deep reviewer's model unless you give it its own:
150
+ `npx agjan models set qa <model>`.
151
+
152
+ The completion block gives you the last gate:
122
153
 
123
154
  **Accept (Gate 3)**: try the result, check the manual ACs by hand, then accept it in your
124
155
  terminal:
@@ -194,7 +225,7 @@ records (step, review, approval, amendment, fix record):
194
225
  loops round by round, tasks with their commits and reviews, the timeline of every
195
226
  event, and the findings. Committed with the unit, so the pull request shows it.
196
227
  - `.agjan/progress.html`: the whole project in one self-contained page (no extension, no
197
- 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,
198
229
  reviewers, people), the review loops (select a round to see its findings), findings,
199
230
  tasks and who worked on it. `.agjan/progress.md` is the same overview as Markdown.
200
231
  Both are local (`.agjan/` is not committed).
@@ -284,11 +315,12 @@ lists replace. The schema is `node_modules/agjan/schemas/config.schema.json`.
284
315
  | `fix` | `max_total`, `max_per_file`, `protected`, `ignored`, `new_file_paths` |
285
316
  | `review.build` | `area` (default: one build review per completed area) or `task` |
286
317
  | `review.rounds` | correction rounds per review step (default 3); if blockers remain, the agent asks you whether to run another round (one more per yes, recorded with `npx agjan review extend <step>`) or to stop |
318
+ | `review.qa` | `on` (default) or `off`: the QA step in Verify for full-mode features |
287
319
  | `review.tiers.<step>` | `balanced` or `deep` per step kind (`spec`, `design:light`, `design`, `build`, `verify`, `fix`, `map`); decides which reviewer agent runs it. Defaults: `deep` for `design` and `verify`, else `balanced`; `fast` uses the balanced agent |
288
320
  | `build.fix_attempts` | attempts for failing deterministic checks before the agent stops (default 3) |
289
321
  | `language` | language of the documents' text (default `en`); headings, ids and keywords stay English |
290
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`) |
291
- | `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. Model names differ per host (Claude Code: `sonnet`, `opus`; Copilot: for example `claude-opus-5.5`). `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 |
292
324
  | `mcp.servers.<name>` | documentation MCP servers: `command`, `args`, `env`, `areas`, `enabled` |
293
325
  | `ci.policy_changes`, `ci.untracked_changes` | `warn` or `fail` in `check --ci` |
294
326
 
@@ -2,7 +2,7 @@
2
2
  // @ts-check
3
3
  /**
4
4
  * agjan guard: a pre-tool-use hook that denies shell commands running the human-only
5
- * agjan commands (approve, accept, reject, auto), however they are wrapped (`npx`, `sh -c`,
5
+ * agjan commands (approve, accept, reject, auto, models set), however they are wrapped (`npx`, `sh -c`,
6
6
  * `cd … &&`, `node …/agjan.mjs`). It is a guardrail in front of the terminal
7
7
  * confirmation, not a proof (design 9.4).
8
8
  *
@@ -36,10 +36,10 @@ import { fileURLToPath } from 'node:url';
36
36
  */
37
37
 
38
38
  const REASON =
39
- 'agjan approve, accept, reject and auto are for the human, in a terminal. Do not run them in any form; ask the user to run the command.';
39
+ 'agjan approve, accept, reject, auto and models set are for the human, in a terminal. Do not run them in any form; ask the user to run the command.';
40
40
 
41
41
  /** `agjan` (or `agjan.mjs`) followed directly by a human-only command; an optional `--` (npm exec) between. */
42
- const HUMAN_ONLY = /\bagjan(?:\.mjs)?["']?\s+(?:--\s+)?["']?(approve|accept|reject|auto)\b/;
42
+ const HUMAN_ONLY = /\bagjan(?:\.mjs)?["']?\s+(?:--\s+)?["']?(approve|accept|reject|auto|models\s+set)\b/;
43
43
 
44
44
  const BRANCH_REASON =
45
45
  'Create branches with npx agjan branch, not with git. Ask the user first: create a new branch (your proposed name or one they type) or use an existing branch (npx agjan branch --list, then npx agjan branch --use <name>).';
@@ -56,9 +56,11 @@ Do not change it silently; `agjan check` fails on it.
56
56
  ## 4. Done
57
57
 
58
58
  When `npx agjan status` says all tasks are done and reviewed, tell the user to run
59
- `/agjan-verify`. In auto mode (`npx agjan status` shows `auto on`), continue in the same
60
- turn with the `agjan-verify` skill (`.claude/skills/agjan-verify/SKILL.md`) instead. Its
61
- final acceptance, `npx agjan approve verify`, stays with the user in every mode.
59
+ `/agjan-verify`. In auto mode (`npx agjan status` shows `auto on`) do not stop: your next
60
+ action is the shell command `cat .claude/skills/agjan-verify/SKILL.md` (it works on every
61
+ host), then follow that skill; put a one-line note for the user into the same reply, since
62
+ a reply without a tool call ends your run. Its final acceptance, `npx agjan approve
63
+ verify`, stays with the user in every mode.
62
64
 
63
65
  ## Never
64
66
 
@@ -97,8 +97,11 @@ passing one.
97
97
  what it lists, review again, and retry.
98
98
  3. **Auto mode** (`npx agjan status` shows `auto on`): step 2 has approved the design
99
99
  automatically. Commit the feature folder with the message it gives, show the user the
100
- last review report and one line that the gate passed in auto mode, and continue in the
101
- same turn with the `agjan-build` skill (`.claude/skills/agjan-build/SKILL.md`).
100
+ last review report and one line that the gate passed in auto mode, and
101
+ continue without stopping: your next action is the shell command
102
+ `cat .claude/skills/agjan-build/SKILL.md` (it works on every host), then follow that skill.
103
+ Put the one line for the user into the same reply as that command: a reply without a
104
+ tool call ends your run, and the user has to start it again.
102
105
  4. Otherwise tell the user what to review, the open findings, and the command for their
103
106
  terminal: `npx agjan approve design` (it also commits the approval); then
104
107
  `/agjan-build`. Stop.
@@ -120,10 +120,13 @@ Hand over the gate (see below) with `spec`. The user runs `/agjan-design` afterw
120
120
  3. **Auto mode** (`npx agjan status` shows `auto on`): step 2 has approved the gate
121
121
  automatically (it says `approved … automatically`). Commit the feature folder with the
122
122
  message it gives, show the user the `npx agjan review report` of the last review and
123
- one line that the gate passed in auto mode, and continue in the same turn: for `spec`
124
- with the `agjan-design` skill (`.claude/skills/agjan-design/SKILL.md`), for
125
- `spec design` with `agjan-build`. Stop only where a person is needed: blockers at the
126
- round limit, an amendment, a business question, and the acceptance at the end.
123
+ one line that the gate passed in auto mode, and continue without stopping: your next
124
+ action is the shell command `cat .claude/skills/agjan-design/SKILL.md` (it works on
125
+ every host; `agjan-build` after `spec design`), then follow that skill. Put the one line
126
+ for the user into the same reply as that command: a reply without a tool call ends
127
+ your run, and the user has to start it again.
128
+ Stop only where a person is needed: blockers at the round limit, an amendment, a
129
+ business question, and the acceptance at the end.
127
130
  4. Otherwise tell the user what to review, the open findings they should know about, and the
128
131
  command to run in their terminal: `npx agjan approve <gate>` (it also commits the
129
132
  approval). Then stop.
@@ -51,7 +51,34 @@ their roles, so the user can try the result. Then run
51
51
  `npx agjan baseline refresh` whenever `npx agjan check` warns that watched files changed
52
52
  since the baseline, and commit both.
53
53
 
54
- ## 5. Final review (step `verify`, deep)
54
+ ## 5. QA (step `qa`)
55
+
56
+ For full-mode features (unless `review.qa` is `off`; `npx agjan status` shows a `qa`
57
+ row), a tester checks the feature from the spec alone before the final review: the
58
+ `agjan-qa` agent writes tests into `test/qa/<slug>/` (and `test/ui/qa/<slug>/`), runs
59
+ them and records the result. Its tests stay in the project as regression tests.
60
+
61
+ 1. Everything committed. Delegate, on its own, to the `agjan-qa` agent with exactly this
62
+ prompt (Claude Code: the Agent tool with that subagent type; GitHub Copilot: the task
63
+ tool with that custom agent and the `name` `qa`):
64
+ `Run step qa of feature <slug>.` Do not tell it about the design, the code or your
65
+ tests: it works from the spec, and that is its value.
66
+ 2. Show the user the round: `npx agjan review report --step qa`, unchanged.
67
+ 3. Commit its tests with the subject `<KEY>: qa tests` (they are in scope).
68
+ 4. **Blockers** are failing QA tests: the application contradicts the spec. Fix the
69
+ **code** within the approved task paths, never the QA tests, and commit the fix with
70
+ the subject of its task (`<KEY>-<id>: …`). A fix makes that area's build review due
71
+ again: do it, then run QA again, up to the round limit (`npx agjan status`). At the
72
+ limit, ask the user, as for reviews (`Run another round`: `npx agjan review extend
73
+ qa`). If you are sure a QA test is wrong (it asks something the spec does not say),
74
+ do not change it: ask the user, who decides with `agjan accept` or a spec change.
75
+ 5. **Spec questions** (minor findings) go to the user in your final message; they do not
76
+ stop the flow.
77
+
78
+ The final review (next section) waits until QA has passed, and so do `check --ci` and
79
+ the acceptance.
80
+
81
+ ## 6. Final review (step `verify`, deep)
55
82
 
56
83
  Everything must be committed. When all your edits are saved, delegate, on its own (not in parallel with other tool calls), to the reviewer agent that `npx agjan status` names for the step (default `agjan-reviewer-deep`), with exactly this prompt (Claude Code: the Agent tool with that subagent type; GitHub Copilot: the task tool with that custom agent and a short `name`, for example `spec review`):
57
84
  `Review step verify of feature <slug>.`
@@ -61,7 +88,7 @@ commits and ask for the review again, up to the round limit that `npx agjan stat
61
88
  If blockers remain at the limit, ask the user with your host's question tool, naming the open blockers, with the choices `Run another round` and `Stop here`. On `Run another round`, run `npx agjan review extend verify` and continue; on `Stop here`, stop and tell the user.
62
89
  Any change after the final review makes it stale; review again after the last change.
63
90
 
64
- ## 6. Check and summary
91
+ ## 7. Check and summary
65
92
 
66
93
  - `npx agjan check --ci` must pass except for one error: `not accepted yet` (the human's
67
94
  acceptance is the last step). Fix everything else it reports, then review again if
@@ -80,7 +107,7 @@ Any change after the final review makes it stale; review again after the last ch
80
107
  Opening a pull request is optional, done only when the user
81
108
  asks (its description is the output of `npx agjan pr-summary`).
82
109
 
83
- ## 7. Pull request, only when the user asks
110
+ ## 8. Pull request, only when the user asks
84
111
 
85
112
  Push the branch and create the PR with the summary as its body, for example
86
113
  `gh pr create --fill-first --body "<pr-summary output>"`. Its CI check passes once the