agjan 0.0.22 → 0.0.25

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.
Files changed (66) hide show
  1. package/README.md +6 -4
  2. package/dist/adapters/claude-code.js +3 -3
  3. package/dist/baseline.js +2 -2
  4. package/dist/browser.js +25 -8
  5. package/dist/cli.js +22 -4
  6. package/dist/commands/check.js +91 -7
  7. package/dist/commands/discover.js +54 -0
  8. package/dist/commands/fix.js +8 -3
  9. package/dist/commands/gates.js +48 -28
  10. package/dist/commands/import.js +73 -0
  11. package/dist/commands/log.js +3 -2
  12. package/dist/commands/map.js +6 -1
  13. package/dist/commands/new.js +7 -3
  14. package/dist/commands/pr-summary.js +20 -5
  15. package/dist/commands/progress.js +1 -1
  16. package/dist/commands/report.js +1 -1
  17. package/dist/commands/review.js +21 -9
  18. package/dist/commands/setup.js +51 -1
  19. package/dist/commands/status.js +118 -20
  20. package/dist/commands/summary.js +2 -1
  21. package/dist/commands/team.js +45 -0
  22. package/dist/commands/test.js +37 -0
  23. package/dist/config.js +9 -1
  24. package/dist/defaults-file.js +33 -0
  25. package/dist/discovery.js +42 -0
  26. package/dist/feature.js +14 -7
  27. package/dist/imports.js +197 -0
  28. package/dist/plan.js +1 -1
  29. package/dist/progress-view.js +46 -11
  30. package/dist/qa.js +27 -3
  31. package/dist/readiness.js +33 -0
  32. package/dist/review-policy.js +2 -1
  33. package/dist/review.js +68 -17
  34. package/dist/schema.js +4 -0
  35. package/dist/story.js +15 -8
  36. package/dist/teams.js +127 -0
  37. package/dist/test-run.js +101 -0
  38. package/dist/types.js +0 -4
  39. package/dist/workflow.js +83 -0
  40. package/docs/guide.md +166 -24
  41. package/kit/domains/btp/domain.json +1 -0
  42. package/kit/hooks/guard.mjs +134 -6
  43. package/kit/skills/agjan-ask/SKILL.md +20 -9
  44. package/kit/skills/agjan-build/SKILL.md +6 -5
  45. package/kit/skills/agjan-design/SKILL.md +2 -2
  46. package/kit/skills/agjan-discover/SKILL.md +87 -0
  47. package/kit/skills/agjan-fix/SKILL.md +10 -6
  48. package/kit/skills/agjan-map/SKILL.md +12 -8
  49. package/kit/skills/agjan-spec/SKILL.md +14 -7
  50. package/kit/skills/agjan-verify/SKILL.md +27 -17
  51. package/kit/skills/btp-architect/SKILL.md +1 -1
  52. package/kit/skills/btp-architect/references/security.md +1 -1
  53. package/kit/skills/cap-developer/SKILL.md +1 -1
  54. package/kit/skills/cap-developer/references/project-setup.md +1 -1
  55. package/kit/skills/cap-developer/references/validation-security.md +1 -1
  56. package/kit/skills/fiori-developer/SKILL.md +1 -1
  57. package/kit/skills/qa-tester/SKILL.md +4 -2
  58. package/kit/templates/agents-block.md +13 -6
  59. package/kit/templates/progress.html +2 -2
  60. package/kit/templates/proposal.md +22 -0
  61. package/package.json +1 -1
  62. package/schemas/approvals.schema.json +9 -1
  63. package/schemas/config.defaults.json +66 -0
  64. package/schemas/config.schema.json +33 -1
  65. package/schemas/log.schema.json +1 -1
  66. package/schemas/reviews.schema.json +2 -2
@@ -0,0 +1,33 @@
1
+ import { NOT_ACCEPTED, runChecks } from './commands/check.js';
2
+ import { acceptanceState, verifyState } from './progress.js';
3
+ import { qaProblem } from './qa.js';
4
+ /**
5
+ * Whether a feature is verified (decision 77): QA passed, the final verify review is current,
6
+ * and `check --ci` has no error but the missing acceptance. The one answer for the
7
+ * acceptance gate, `status --done`, the completion screen and the progress pages, so none of
8
+ * them calls a feature verified while another reports what blocks it.
9
+ */
10
+ export function verification(ctx, feature) {
11
+ if (feature.stage !== 'build')
12
+ return { problems: [`the feature is in ${feature.stage}; it is accepted after /agjan-verify`], record: null, accepted: false };
13
+ const problems = [];
14
+ const qa = qaProblem(ctx.root, ctx.config, feature);
15
+ if (qa)
16
+ problems.push(qa);
17
+ const verify = verifyState(ctx.root, ctx.config, feature);
18
+ if (verify.state === 'none')
19
+ problems.push('no final verify review recorded: /agjan-verify');
20
+ else if (verify.state === 'blocked')
21
+ problems.push(`the final verify review ${verify.record.id} is blocked`);
22
+ else if (verify.state === 'stale')
23
+ problems.push(`files changed after the final verify review ${verify.record.id}: /agjan-verify again`);
24
+ if (verify.state === 'current') {
25
+ const { report } = runChecks(ctx, 'ci', feature.slug);
26
+ for (const item of report.items) {
27
+ if (item.level === 'error' && !item.message.startsWith(NOT_ACCEPTED))
28
+ problems.push(`check --ci: ${item.message}`);
29
+ }
30
+ }
31
+ const accepted = verify.state === 'current' && problems.length === 0 && acceptanceState(ctx.root, ctx.config, feature, verify).state === 'accepted';
32
+ return { problems, record: verify.record, accepted };
33
+ }
@@ -15,6 +15,7 @@ export const DEFAULT_TIERS = {
15
15
  verify: 'deep',
16
16
  fix: 'balanced',
17
17
  map: 'balanced',
18
+ proposal: 'deep',
18
19
  qa: 'qa',
19
20
  };
20
21
  /** `build:cap` and `build:T2` are both of kind `build`. */
@@ -34,7 +35,7 @@ export function fixAttempts(config) {
34
35
  return config.build?.fix_attempts ?? 3;
35
36
  }
36
37
  /** The gate approvals that close a correction loop of a review step. */
37
- const CLOSING_APPROVALS = { spec: ['spec'], design: ['design'], 'design:light': ['spec', 'design'] };
38
+ const CLOSING_APPROVALS = { spec: ['spec'], design: ['design'], 'design:light': ['spec', 'design'], proposal: ['proposal'] };
38
39
  /** Steps whose loop a later spec or design approval closes: a revision (decision 84) starts them again. */
39
40
  const AFTER_GATES = (step) => step === 'qa' || step === 'verify' || step.startsWith('build:');
40
41
  /**
package/dist/review.js CHANGED
@@ -12,11 +12,15 @@ import { acTestFiles, repoFiles } from './tests-map.js';
12
12
  import { fixRules } from './fix.js';
13
13
  import { watchedHashes } from './baseline.js';
14
14
  import { acResults, loadResults, resultLabel } from './test-results.js';
15
+ import { readTestRun, testRunProblem } from './test-run.js';
16
+ import { WORKFLOWS, hasReviewStep, workflowOf } from './workflow.js';
17
+ import { proposalProblems } from './discovery.js';
18
+ import { personaText, unitTeam } from './teams.js';
15
19
  import { LOG_FILE, appendLog } from './log.js';
16
20
  import { AgjanError } from './errors.js';
17
21
  import { nextRound, roundState } from './review-policy.js';
18
22
  import { designProblems, documentProblems } from './validate.js';
19
- import { QA_STEP, qaApplies, qaDirs, qaProblem, qaState, qaTestFiles, qaTestsHash } from './qa.js';
23
+ import { QA_STEP, qaApplies, qaDirs, writeQaGuard, qaProblem, qaState, qaTestFiles, qaTestsHash } from './qa.js';
20
24
  import { buildProgress } from './progress.js';
21
25
  export const REVIEW_MD = 'review.md';
22
26
  const CONTEXT_DIR = '.agjan/review-contexts';
@@ -25,7 +29,7 @@ const MAX_DIFF_BYTES = 200_000;
25
29
  const SEVERITIES = ['blocker', 'major', 'minor'];
26
30
  const VERDICTS = ['pass', 'pass-with-notes', 'blocked'];
27
31
  /** The files agjan writes itself in a unit's folder: its records. */
28
- const RECORD_FILES = new Set([APPROVALS_FILE, REVIEWS_FILE, REVIEW_MD, LOG_FILE, 'report.md', 'progress.md', 'fix.json', 'fix.md']);
32
+ const RECORD_FILES = new Set([APPROVALS_FILE, REVIEWS_FILE, REVIEW_MD, LOG_FILE, 'report.md', 'progress.md', 'fix.json', 'fix.md', 'tests.json']);
29
33
  /**
30
34
  * Whether a path is a record agjan writes itself (approvals, reviews, log, progress, …) in
31
35
  * the folder of any unit. Records are outside every review's tree hash: recording a review
@@ -56,13 +60,15 @@ function currentContent(path) {
56
60
  /**
57
61
  * Hash of the change as it stands: every file changed relative to the merge-base
58
62
  * (committed, staged, unstaged, untracked) with its current content, except agjan's records
59
- * (`isRecord`) and the folders in `except`. Any other write to the working tree changes it.
63
+ * (`isRecord`), the test results files (`verify.<area>.results`: a test run's output, not
64
+ * the change) and the folders in `except`. Any other write to the working tree changes it.
60
65
  * The content is taken as git stores it (`contentIds`), so the hash is the same in a CRLF
61
66
  * checkout on Windows and in CI.
62
67
  */
63
68
  export function treeHash(root, config, except = []) {
69
+ const results = new Set(Object.values(config.verify ?? {}).flatMap((v) => (v?.results ? [v.results].flat() : [])));
64
70
  const files = changedFiles(root, resolveBase(root, config.git?.base))
65
- .filter((file) => !isRecord(file) && !file.startsWith('.agjan/') && !except.some((dir) => file.startsWith(dir)));
71
+ .filter((file) => !isRecord(file) && !results.has(file) && !file.startsWith('.agjan/') && !except.some((dir) => file.startsWith(dir)));
66
72
  const ids = contentIds(root, files);
67
73
  const hash = createHash('sha256');
68
74
  for (const file of files)
@@ -70,17 +76,20 @@ export function treeHash(root, config, except = []) {
70
76
  return `sha256:${hash.digest('hex')}`;
71
77
  }
72
78
  /**
73
- * Parses a review step. Features: spec, design, design:light, verify, build:<area>,
74
- * build:<task>. A fix has only the step fix, a map run only map.
79
+ * Parses a review step against the unit's workflow (decision 90). Features: spec, design,
80
+ * design:light, verify, build:<area>, build:<task>. A fix has only the step fix, a map run
81
+ * only map.
75
82
  */
76
83
  export function parseStep(step, feature, config) {
77
- if (feature.kind === 'fix' || feature.kind === 'map') {
78
- if (step !== feature.kind)
79
- throw new AgjanError(`a ${feature.kind} record has only the review step '${feature.kind}'`);
84
+ const workflow = workflowOf(feature.kind);
85
+ if (feature.kind !== 'feature') {
86
+ if (!hasReviewStep(workflow, step))
87
+ throw new AgjanError(`a ${workflow.name} record has only the review step${workflow.reviewSteps.length > 1 ? 's' : ''} ${workflow.reviewSteps.map((s) => `'${s}'`).join(', ')}`);
80
88
  return { step, kind: step };
81
89
  }
82
- if (step === 'fix' || step === 'map')
83
- throw new AgjanError(`'${step}' reviews belong to a ${step} record, not to a feature`);
90
+ const owner = Object.values(WORKFLOWS).find((w) => w.kind !== 'feature' && hasReviewStep(w, step));
91
+ if (owner)
92
+ throw new AgjanError(`'${step}' reviews belong to a ${owner.name} record, not to a feature`);
84
93
  if (['spec', 'design', 'design:light', 'verify', QA_STEP].includes(step))
85
94
  return { step, kind: step };
86
95
  const match = /^build:(.+)$/.exec(step ?? '');
@@ -180,8 +189,9 @@ const CHECKLISTS = {
180
189
  design: 'Every AC covered by tasks. Areas and app types justified with alternatives. Open technical questions answered. Every rule of the spec\'s Authorization section has a decision on how it is enforced. Every task\'s paths include where the tests of its ACs go (tests of Fiori annotations usually live in the CAP tests); a task covers an AC only if its paths include every file needed to implement and test it. The chosen service shape supports every interaction the ACs describe in the UI: in a Fiori elements app, creating or editing records needs a draft-enabled entity (@odata.draft.enabled), so "no draft" for such an app is a blocker. Nothing beyond the spec.',
181
190
  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.',
182
191
  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).',
192
+ proposal: 'The proposal answers the question that was asked, for this application. Each option is real and described correctly for the versions in use (CAP, SAPUI5, BTP services): check claims against the role skills and the sources the proposal cites; a claim you cannot confirm is a major finding starting with "Unverified:". The options considered are the ones a SAP consultant would consider; a missing obvious option is a major finding. The recommendation follows from the options and states its costs and risks (security, data protection, licences, effort, operations). Open questions are listed, not decided silently. No code or configuration was changed: a discovery only writes its proposal.',
183
193
  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.',
184
- 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.',
194
+ 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. The test run in the context (agjan test) passed on this change; do not rerun the suite. When the project records no results per test, 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.',
185
195
  };
186
196
  /**
187
197
  * What the given tasks may change (design 6.5), as `agjan check` judges it: the task paths,
@@ -218,6 +228,11 @@ export function buildContextText(root, config, feature, parsed) {
218
228
  '',
219
229
  ];
220
230
  parts.push(section('Checklist', CHECKLISTS[parsed.kind]));
231
+ // The unit's team adds what the reviewer works with; it never removes a check (decision 92).
232
+ const team = unitTeam(config, feature.approvals.feature.team);
233
+ const reviewer = team?.team ? personaText(team.name, 'reviewer', team.team.personas.reviewer) : null;
234
+ if (reviewer)
235
+ parts.push(section('Your team', reviewer));
221
236
  const baseline = join(root, FEATURES_DIR, 'project.md');
222
237
  const baselineText = existsSync(baseline) ? readFileSync(baseline, 'utf8') : null;
223
238
  if (parsed.kind === 'fix') {
@@ -229,6 +244,14 @@ export function buildContextText(root, config, feature, parsed) {
229
244
  parts.push(section('Fast-path rules', `${rules.total} changed lines (limit ${rules.limits.max_total}). ${verdict}\n\n${files}`));
230
245
  parts.push(section('Diff', fence(diffOfFiles(root, base, rules.files.map((f) => f.path)), 'diff')));
231
246
  }
247
+ else if (parsed.kind === 'proposal') {
248
+ if (!feature.proposal)
249
+ throw new AgjanError('proposal.md does not exist');
250
+ parts.push(section(docPath(feature, 'proposal.md'), fence(feature.proposal.text, 'md')));
251
+ if (baselineText)
252
+ parts.push(section(`${FEATURES_DIR}/project.md (the application)`, fence(baselineText, 'md')));
253
+ parts.push(section('Sources to check claims against', 'The role skills in `.claude/skills/` (cap-developer, fiori-developer, btp-architect) and `.claude/skills/agjan-ask/references/sources.md`.'));
254
+ }
232
255
  else if (parsed.kind === 'map') {
233
256
  if (!baselineText)
234
257
  throw new AgjanError(`${FEATURES_DIR}/project.md does not exist; write it first`);
@@ -271,10 +294,16 @@ export function buildContextText(root, config, feature, parsed) {
271
294
  .join('\n');
272
295
  const unrecorded = results
273
296
  ? ''
274
- : '\n\nThis project records no test results (no `verify.<area>.results` in agjan.config.json, a setting for the human). Coverage here means a test names the AC; missing results are not a finding.';
297
+ : '\n\nThis project records no test results per test (no `verify.<area>.results` in agjan.config.json, a setting for the human). Coverage here means a test names the AC; missing results are not a finding.';
298
+ const run = config.test_evidence === 'names' ? null : readTestRun(feature);
299
+ const runText = run
300
+ ? `${run.runs.map((r) => `- \`${r.command}\`: ${r.exit === 0 ? 'passed' : `failed (exit code ${r.exit})`}`).join('\n')}\n- UI tests: ${run.ui.state === 'skipped' ? `skipped (${run.ui.reason})` : run.ui.state === 'none' ? 'none in the project' : run.ui.state}\n\nRecorded by agjan test at ${run.at_utc} on this change (the tree hash matches); it includes the QA tests.`
301
+ : '';
275
302
  const changed = changedFiles(root, base).filter((f) => !isRecord(f) && !f.startsWith('.agjan/'));
276
303
  parts.push(section('Acceptance criteria', acsText(feature)));
277
304
  parts.push(section('AC coverage (test files mentioning the AC id, and test results)', `| AC | verification | test files | result |\n|---|---|---|---|\n${coverage}${unrecorded}`));
305
+ if (runText)
306
+ parts.push(section('Test run (agjan test)', runText));
278
307
  parts.push(section(docPath(feature, 'design.md'), fence(feature.design.text, 'md')));
279
308
  parts.push(section(docPath(feature, 'tasks.md'), fence(feature.tasks.text, 'md')));
280
309
  parts.push(section('Allowed paths (scope, enforced by agjan check)', scopeText(scopeOf(config, feature, feature.tasks.parsed.tasks))));
@@ -289,7 +318,7 @@ export function buildContextText(root, config, feature, parsed) {
289
318
  parts.push(section('Full diff', fence(diffOfFiles(root, base, changed), 'diff')));
290
319
  }
291
320
  if (baselineText && parsed.kind !== 'build' && parsed.kind !== 'fix')
292
- parts.push(section('Baseline (docs/agjan/project.md)', fence(baselineText, 'md')));
321
+ parts.push(section('Baseline (agjan-docs/project.md)', fence(baselineText, 'md')));
293
322
  parts.push(section('Earlier reviews', reviewHistory(feature)));
294
323
  parts.push(section('Open findings', openFindings(feature)));
295
324
  parts.push(section('How to record your result', 'Call review_record with this context_id, a verdict (pass, pass-with-notes, blocked), your findings ' +
@@ -317,6 +346,12 @@ function unchangedSinceFindings(feature, step, tree) {
317
346
  * an unfinished template only reports that and costs one of the step's rounds.
318
347
  */
319
348
  function unfinishedDocuments(feature, config, step) {
349
+ if (step === 'proposal') {
350
+ const problems = proposalProblems(feature);
351
+ if (problems.length)
352
+ throw new AgjanError(`the proposal is not ready for its review; complete it first:\n${problems.map((p) => ` - ${p}`).join('\n')}`);
353
+ return;
354
+ }
320
355
  if (!['spec', 'design', 'design:light'].includes(step))
321
356
  return;
322
357
  const problems = [];
@@ -359,6 +394,10 @@ export function createReviewContext(root, config, { feature: slug, step }) {
359
394
  const qa = parsed.step === 'verify' ? qaProblem(root, config, feature) : null;
360
395
  if (qa)
361
396
  throw new AgjanError(`the final review waits for QA: ${qa}`);
397
+ // And after a passing test run on this change (decision 88).
398
+ const tests = parsed.step === 'verify' && config.test_evidence !== 'names' ? testRunProblem(root, config, feature) : null;
399
+ if (tests)
400
+ throw new AgjanError(`the final review waits for the tests: ${tests}`);
362
401
  const tree = treeHash(root, config);
363
402
  unchangedSinceFindings(feature, parsed.step, tree);
364
403
  const text = buildContextText(root, config, feature, parsed);
@@ -368,7 +407,7 @@ export function createReviewContext(root, config, { feature: slug, step }) {
368
407
  id,
369
408
  feature: feature.slug,
370
409
  step: parsed.step,
371
- documents: { spec: feature.spec?.hash, design: feature.designHash ?? undefined },
410
+ documents: { spec: feature.spec?.hash, design: feature.designHash ?? undefined, proposal: feature.proposal?.hash },
372
411
  inputs_hash: sha256(text),
373
412
  tree_hash: tree,
374
413
  base_commit: mergeBase(root, base),
@@ -498,6 +537,7 @@ export function createQaContext(root, config, { feature: slug }) {
498
537
  throw new AgjanError('QA runs after the build: every task committed and its reviews done (npx agjan status)');
499
538
  withinRoundLimit(feature, config, QA_STEP);
500
539
  const dirs = qaDirs(feature.slug);
540
+ writeQaGuard(root, config, feature.slug);
501
541
  const baseline = join(root, FEATURES_DIR, 'project.md');
502
542
  const runLocally = existsSync(baseline) ? (/^## Run locally\s*$([\s\S]*?)(?=^## |\s*$(?![\s\S]))/m.exec(readFileSync(baseline, 'utf8'))?.[1] ?? '').trim() : '';
503
543
  const areaNames = [...new Set(feature.tasks.parsed.tasks.map((t) => resolveArea(config, t.area)?.name).filter((name) => Boolean(name)))];
@@ -511,7 +551,12 @@ export function createQaContext(root, config, { feature: slug }) {
511
551
  '',
512
552
  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.`),
513
553
  section(docPath(feature, 'spec.md'), fence(feature.spec.text, 'md')),
514
- section('Run locally (from docs/agjan/project.md)', runLocally || '(not described: start the application as the project README or package.json says)'),
554
+ section('Run locally (from agjan-docs/project.md)', runLocally || '(not described: start the application as the project README or package.json says)'),
555
+ ...((() => {
556
+ const team = unitTeam(config, feature.approvals.feature.team);
557
+ const tester = team?.team ? personaText(team.name, 'tester', team.team.personas.tester) : null;
558
+ return tester ? [section('Your team', tester)] : [];
559
+ })()),
515
560
  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.`),
516
561
  section('Your tests from earlier QA rounds', existing.length ? existing.map((f) => `- ${f}`).join('\n') : '(none: this is the first QA round)'),
517
562
  section('Earlier rounds', reviewHistory(feature)),
@@ -541,7 +586,8 @@ export function createQaContext(root, config, { feature: slug }) {
541
586
  }
542
587
  /**
543
588
  * qa_record: the QA agent's result. Refused when it changed anything outside its QA
544
- * folders; records the hash of its tests, so a later change to them makes QA stale.
589
+ * folders, and a passing verdict without any QA test while an AC is automated: no tests is
590
+ * no evidence. Records the hash of its tests, so a later change to them makes QA stale.
545
591
  */
546
592
  export function recordQa(root, config, input, recorder) {
547
593
  const result = validResult(root, input, 'qa');
@@ -550,6 +596,11 @@ export function recordQa(root, config, input, recorder) {
550
596
  throw new AgjanError(`files outside the QA folders (${qaDirs(slug).join(', ')}) changed since qa_context was called; nothing was recorded. ` +
551
597
  'QA writes only its own tests. Undo the other changes, then call qa_context again.');
552
598
  }
599
+ const automated = (result.feature.spec?.parsed.acs ?? []).filter((ac) => ac.verification !== 'manual');
600
+ if (result.verdict !== 'blocked' && automated.length && qaTestFiles(root, slug).length === 0) {
601
+ throw new AgjanError(`the verdict ${result.verdict} needs QA tests, but ${qaDirs(slug).join(' and ')} hold none; nothing was recorded. ` +
602
+ `Write and run tests for the automated ACs (${automated.map((ac) => ac.id).join(', ')}), then call qa_record again.`);
603
+ }
553
604
  return storeRecord(root, result, recorder, {
554
605
  tree_hash: treeHash(root, config),
555
606
  qa_tests_hash: qaTestsHash(root, slug),
package/dist/schema.js CHANGED
@@ -73,6 +73,10 @@ export function validate(schema, value, root = schema, path = '') {
73
73
  if (item === undefined)
74
74
  continue;
75
75
  const where = path ? `${path}.${key}` : key;
76
+ if (schema.propertyNames?.enum && !schema.propertyNames.enum.includes(key)) {
77
+ errors.push(`${where}: unknown name; one of ${schema.propertyNames.enum.join(', ')}`);
78
+ continue;
79
+ }
76
80
  if (schema.properties?.[key])
77
81
  errors.push(...validate(schema.properties[key], item, root, where));
78
82
  else if (schema.additionalProperties === false)
package/dist/story.js CHANGED
@@ -18,9 +18,11 @@ function subject(step) {
18
18
  if (step === 'design:light')
19
19
  return { name: 'the spec and design', first: 'Spec and design reviewed', again: 'Spec and design reviewed again', revised: 'Spec and design revised', clean: 'no findings' };
20
20
  if (step === 'qa')
21
- return { name: 'the independent tests', first: 'Independent tests written from the spec', again: 'Independent tests run again', revised: 'Code fixed', clean: 'all passed' };
21
+ return { name: 'the independent tests', first: 'Independent tests written from the spec', again: 'Independent tests run again', revised: 'Changed since the last test round', clean: 'no findings' };
22
+ if (step === 'proposal')
23
+ return { name: 'the proposal', first: 'Proposal reviewed', again: 'Proposal reviewed again', revised: 'Proposal revised', clean: 'no findings' };
22
24
  if (step === 'verify')
23
- return { name: 'the final check', first: 'Final check', again: 'Final check repeated', revised: 'Code fixed', clean: 'everything checks out' };
25
+ return { name: 'the final check', first: 'Final check', again: 'Final check repeated', revised: 'Changed since the last final check', clean: 'no findings' };
24
26
  const part = step.replace(/^build:/, '');
25
27
  return { name: `the code (${part})`, first: `Code checked (${part})`, again: `Code checked again (${part})`, revised: `Code revised (${part})`, clean: 'no findings' };
26
28
  }
@@ -30,9 +32,9 @@ const who = (by) => by.split('@')[0];
30
32
  export function storyItems(model) {
31
33
  const items = [];
32
34
  const t = (iso) => Date.parse(iso);
33
- const add = (at, text, rank = 5) => items.push({ at: typeof at === 'number' ? at : t(at), text, rank });
35
+ const add = (at, text, rank = 5, mark) => items.push({ at: typeof at === 'number' ? at : t(at), text, rank, ...(mark ? { mark } : {}) });
34
36
  // The time the unit was created, not the first logged event: `agjan new` logs nothing.
35
- add(model.created && model.created < model.start ? model.created : model.start, model.kind === 'feature' ? 'Requirement received' : model.kind === 'fix' ? 'Change requested' : 'Mapping of the project started', 0);
37
+ add(model.created && model.created < model.start ? model.created : model.start, model.kind === 'feature' ? 'Requirement received' : model.kind === 'fix' ? 'Change requested' : model.kind === 'discovery' ? 'Question received' : 'Mapping of the project started', 0);
36
38
  // Before the first review of a step, its document was prepared.
37
39
  const firstReview = (steps) => model.reviews.filter((r) => steps.includes(r.step)).map((r) => t(r.at)).sort((a, b) => a - b)[0];
38
40
  const specAt = firstReview(['spec']) ?? (model.mode === 'light' ? firstReview(['design:light']) : undefined);
@@ -51,16 +53,19 @@ export function storyItems(model) {
51
53
  if (e.event === 'round-granted')
52
54
  add(e.at, `You allowed another review round for ${subject(String(e.step)).name}`);
53
55
  }
54
- // Reviews: a later review of the same step means the work was revised in between.
56
+ // Reviews, with a revision before a later round only when what the step looks at changed.
57
+ // A review's finding nothing is said as such: whether tests ran is not the review's claim.
55
58
  const seen = new Map();
56
59
  for (const r of [...model.reviews].sort((a, b) => t(a.at) - t(b.at))) {
57
60
  const words = subject(r.step);
58
61
  const before = seen.get(r.step) ?? 0;
59
62
  seen.set(r.step, before + 1);
60
- if (before)
63
+ if (before && r.changed)
61
64
  add(t(r.at) - 1, words.revised, 3);
62
65
  const fixed = r.resolves.length ? `; ${r.resolves.length} earlier finding${r.resolves.length === 1 ? '' : 's'} fixed` : '';
63
- add(r.at, `${before ? words.again : words.first}: ${r.findings.length ? findingsText(model, r.findings) : words.clean}${fixed}`, 4);
66
+ const tests = typeof r.tests === 'number' ? ` (${r.tests} test file${r.tests === 1 ? '' : 's'})` : '';
67
+ const mark = r.findings.some((id) => model.findings[id].severity === 'blocker') ? 'issue' : r.findings.length ? 'note' : undefined;
68
+ add(r.at, `${before ? words.again : words.first}${tests}: ${r.findings.length ? findingsText(model, r.findings) : words.clean}${fixed}`, 4, mark);
64
69
  }
65
70
  for (const d of model.decisions) {
66
71
  const auto = d.by.startsWith('auto mode');
@@ -69,6 +74,8 @@ export function storyItems(model) {
69
74
  add(d.at, `${approved[1][0].toUpperCase()}${approved[1].slice(1)} approved ${auto ? 'automatically (auto mode)' : `by ${who(d.by)}`}`);
70
75
  else if (d.what === 'accepted the feature')
71
76
  add(d.at, `Feature accepted by ${who(d.by)}`);
77
+ else if (d.what === 'approved proposal')
78
+ add(d.at, `Recommendation approved by ${who(d.by)}`);
72
79
  else if (d.what.startsWith('accepted '))
73
80
  add(d.at, `${d.what.replace('accepted ', 'Finding ')} accepted by ${who(d.by)}${d.detail ? `: ${d.detail}` : ''}`);
74
81
  else if (d.what.startsWith('rejected '))
@@ -86,7 +93,7 @@ export function storyItems(model) {
86
93
  return items.sort((a, b) => a.at - b.at || a.rank - b.rank);
87
94
  }
88
95
  /** The command or skill in a "now" text, and the text without it. */
89
- function splitNow(now) {
96
+ export function splitNow(now) {
90
97
  const command = /\((npx agjan [^)]+)\)/.exec(now)?.[1] ?? /(\/agjan-[a-z-]+)/.exec(now)?.[1] ?? null;
91
98
  const text = now
92
99
  .replace(/\s*\(npx agjan [^)]+\)/, '')
package/dist/teams.js ADDED
@@ -0,0 +1,127 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { hashText } from './hash.js';
4
+ import { AgjanError } from './errors.js';
5
+ import { WORKFLOWS } from './workflow.js';
6
+ export const ROLES = ['implementer', 'reviewer', 'tester', 'analyst'];
7
+ /** The roles a workflow uses, besides the reviewer every workflow has. */
8
+ const ROLES_OF = {
9
+ feature: ['implementer', 'reviewer', 'tester'],
10
+ fix: ['implementer', 'reviewer'],
11
+ map: ['analyst', 'reviewer'],
12
+ discovery: ['analyst', 'reviewer'],
13
+ };
14
+ const ROLE_SKILLS = ['cap-developer', 'fiori-developer', 'btp-architect'];
15
+ export const BUILT_IN_TEAMS = {
16
+ 'sap-delivery': {
17
+ description: 'Implements a business feature on SAP BTP: CAP, Fiori elements and UI5, BTP services.',
18
+ workflows: ['feature'],
19
+ personas: {
20
+ implementer: { skills: ROLE_SKILLS },
21
+ reviewer: { skills: ['solution-reviewer', ...ROLE_SKILLS] },
22
+ tester: { skills: ['qa-tester'] },
23
+ },
24
+ },
25
+ 'sap-maintenance': {
26
+ description: 'Fixes a bounded defect, and maps an existing application.',
27
+ workflows: ['fix', 'map'],
28
+ personas: {
29
+ implementer: { skills: ['cap-developer', 'fiori-developer'] },
30
+ analyst: { skills: ROLE_SKILLS },
31
+ reviewer: { skills: ['solution-reviewer', 'cap-developer', 'fiori-developer'] },
32
+ },
33
+ },
34
+ 'sap-discovery': {
35
+ description: 'Explores a question and recommends an option: integration, BTP services, feasibility.',
36
+ workflows: ['discovery'],
37
+ personas: {
38
+ analyst: { skills: ['btp-architect', 'cap-developer', 'fiori-developer'] },
39
+ reviewer: { skills: ['solution-reviewer', 'btp-architect'] },
40
+ },
41
+ },
42
+ };
43
+ /** The built-in teams with the imported ones (loadConfig puts them in) and the project's own on top. */
44
+ export function allTeams(config) {
45
+ return { ...BUILT_IN_TEAMS, ...(config.teams ?? {}) };
46
+ }
47
+ /** The default team of a workflow: the project's choice (`team.<kind>`), else the first that serves it. */
48
+ export function defaultTeam(config, kind) {
49
+ const chosen = config.team?.[kind];
50
+ if (chosen)
51
+ return chosen;
52
+ return Object.entries(allTeams(config)).find(([, t]) => t.workflows.includes(kind))?.[0] ?? null;
53
+ }
54
+ /** JSON with the keys of every object sorted: the same definition always gives the same text. */
55
+ function canonical(value) {
56
+ if (Array.isArray(value))
57
+ return `[${value.map(canonical).join(',')}]`;
58
+ if (value && typeof value === 'object') {
59
+ return `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${canonical(value[k])}`).join(',')}}`;
60
+ }
61
+ return JSON.stringify(value);
62
+ }
63
+ /** What the team's definition is now: the hash a unit records when it starts. */
64
+ export function teamHash(team) {
65
+ return hashText(canonical(team));
66
+ }
67
+ /** What is wrong with a team, for the workflow it would run (or all it serves). */
68
+ export function teamProblems(root, config, name, kind) {
69
+ const team = allTeams(config)[name];
70
+ if (!team)
71
+ return [`no team '${name}' (built in: ${Object.keys(BUILT_IN_TEAMS).join(', ')}; or define it under "teams" in agjan.config.json)`];
72
+ const problems = [];
73
+ if (!team.workflows?.length)
74
+ problems.push(`team '${name}' serves no workflow`);
75
+ for (const w of team.workflows ?? [])
76
+ if (!WORKFLOWS[w])
77
+ problems.push(`team '${name}': unknown workflow '${w}'`);
78
+ if (kind && !team.workflows?.includes(kind))
79
+ problems.push(`team '${name}' does not serve the ${WORKFLOWS[kind].name} workflow (it serves: ${team.workflows.join(', ')})`);
80
+ for (const [role, persona] of Object.entries(team.personas ?? {})) {
81
+ if (!ROLES.includes(role))
82
+ problems.push(`team '${name}': unknown role '${role}' (roles: ${ROLES.join(', ')})`);
83
+ for (const skill of persona?.skills ?? []) {
84
+ if (!existsSync(join(root, '.claude', 'skills', skill, 'SKILL.md')))
85
+ problems.push(`team '${name}', ${role}: no skill '${skill}' in .claude/skills/`);
86
+ }
87
+ }
88
+ for (const w of team.workflows ?? []) {
89
+ for (const role of ROLES_OF[w] ?? []) {
90
+ if (!team.personas?.[role]?.skills?.length)
91
+ problems.push(`team '${name}' serves ${w} but has no ${role} with skills`);
92
+ }
93
+ }
94
+ return problems;
95
+ }
96
+ /** A persona as the agent in its role reads it: the skill files, then the instructions. */
97
+ export function personaText(team, role, persona) {
98
+ if (!persona)
99
+ return null;
100
+ const skills = persona.skills.map((s) => `- \`.claude/skills/${s}/SKILL.md\` (and the references its table names for your topic)`).join('\n');
101
+ return [`Team ${team}, ${role}. Work with these skills:`, skills, persona.instructions?.trim() ? `\n${persona.instructions.trim()}` : ''].join('\n').trim();
102
+ }
103
+ /** The role of the main agent in a workflow: it implements, or (map run, discovery) it analyses. */
104
+ export function mainRole(kind) {
105
+ return kind === 'map' || kind === 'discovery' ? 'analyst' : 'implementer';
106
+ }
107
+ /** A unit's team: its recorded name, and whether the definition changed since it started. */
108
+ export function unitTeam(config, recorded) {
109
+ if (!recorded)
110
+ return null;
111
+ const team = allTeams(config)[recorded.name] ?? null;
112
+ return { name: recorded.name, team, changed: !team || teamHash(team) !== recorded.hash };
113
+ }
114
+ /**
115
+ * The team a new unit starts with: the one named, else the workflow's default. Refused when
116
+ * it does not exist or does not serve the workflow; missing skills are `check`'s to report
117
+ * (`agjan sync` installs the built-in ones).
118
+ */
119
+ export function chooseTeam(root, config, kind, explicit) {
120
+ const name = explicit ?? defaultTeam(config, kind);
121
+ if (!name)
122
+ return null;
123
+ const problems = teamProblems(root, config, name, kind).filter((p) => !p.includes('in .claude/skills/'));
124
+ if (problems.length)
125
+ throw new AgjanError(problems.join('; '));
126
+ return { name, hash: teamHash(allTeams(config)[name]) };
127
+ }
@@ -0,0 +1,101 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { join } from 'node:path';
3
+ import { readJson, writeJson } from './json-file.js';
4
+ import { git } from './git.js';
5
+ import { resolveArea } from './config.js';
6
+ import { UI_SCRIPT, hasUiTests, probeBrowser } from './browser.js';
7
+ import { treeHash } from './review.js';
8
+ import { acResults, loadResults } from './test-results.js';
9
+ /**
10
+ * The test run of a feature (decision 88): `agjan test` runs the feature's test commands
11
+ * and records what ran, how it ended and the change it ran on (the same tree hash as the
12
+ * reviews), so a passing run is evidence for that change and no other. The QA tests are
13
+ * part of the suite, so a run also repeats them on the current code without the QA agent.
14
+ */
15
+ export const TEST_RUN_FILE = 'tests.json';
16
+ /** The areas of a feature's tasks, by short name. */
17
+ export function featureAreas(config, feature) {
18
+ return [...new Set((feature.tasks?.parsed.tasks ?? []).map((t) => resolveArea(config, t.area)?.name).filter((name) => Boolean(name)))];
19
+ }
20
+ /** The test commands of a feature's areas; `npm test` when none names one. */
21
+ export function testCommands(config, feature) {
22
+ const commands = [...new Set(featureAreas(config, feature).map((a) => config.verify?.[a]?.test).filter((c) => Boolean(c)))];
23
+ return commands.length ? commands : ['npm test'];
24
+ }
25
+ export function readTestRun(feature) {
26
+ return readJson(join(feature.dir, TEST_RUN_FILE));
27
+ }
28
+ /**
29
+ * Where the evidence stands: `none` (no run recorded), `failed` (a command or the UI tests
30
+ * failed), `stale` (files changed after the run) or `passed`.
31
+ */
32
+ export function testRunState(root, config, feature) {
33
+ const run = readTestRun(feature);
34
+ if (!run)
35
+ return { state: 'none', run: null };
36
+ if (run.tree_hash !== treeHash(root, config))
37
+ return { state: 'stale', run };
38
+ if (run.runs.some((r) => r.exit !== 0) || run.ui?.state === 'failed')
39
+ return { state: 'failed', run };
40
+ return { state: 'passed', run };
41
+ }
42
+ /** What the run lacks, or null when it is evidence for the current change. */
43
+ export function testRunProblem(root, config, feature) {
44
+ const { state, run } = testRunState(root, config, feature);
45
+ if (state === 'none')
46
+ return 'the tests have not run on this change: npx agjan test';
47
+ if (state === 'stale')
48
+ return `files changed after the test run (${run.at_utc}): npx agjan test`;
49
+ if (state === 'failed') {
50
+ const failed = [...run.runs.filter((r) => r.exit !== 0).map((r) => r.command), ...(run.ui.state === 'failed' ? [`npm run ${UI_SCRIPT}`] : [])];
51
+ return `the test run failed (${failed.join(', ')}): fix the code, then npx agjan test`;
52
+ }
53
+ return null;
54
+ }
55
+ /** Runs one command in the project; its output goes to `out` only when it fails. */
56
+ function runCommand(root, command, out) {
57
+ const start = Date.now();
58
+ const result = spawnSync(command, { cwd: root, shell: true, encoding: 'utf8', timeout: 1_800_000, maxBuffer: 64 * 1024 * 1024 });
59
+ const ms = Date.now() - start;
60
+ const exit = result.status;
61
+ if (exit !== 0) {
62
+ const lines = `${result.stdout ?? ''}${result.stderr ?? ''}`.trimEnd().split('\n');
63
+ out(`--- ${command}: last ${Math.min(lines.length, 60)} lines ---`);
64
+ for (const line of lines.slice(-60))
65
+ out(line);
66
+ }
67
+ return { command, exit, ms };
68
+ }
69
+ /**
70
+ * Runs the feature's test commands and its UI tests (where a browser can start), reads the
71
+ * results files they wrote, and records the run in the feature's folder.
72
+ */
73
+ export function runTests(root, config, feature, now, out) {
74
+ const startedMs = Date.now();
75
+ const runs = testCommands(config, feature).map((command) => runCommand(root, command, out));
76
+ let ui = { state: 'none' };
77
+ if (hasUiTests(root)) {
78
+ const browser = probeBrowser(root);
79
+ if (!browser.ready)
80
+ ui = { state: 'skipped', reason: browser.reason };
81
+ else
82
+ ui = { state: runCommand(root, `npm run ${UI_SCRIPT}`, out).exit === 0 ? 'passed' : 'failed' };
83
+ }
84
+ // Only results files this run wrote describe it.
85
+ const loaded = loadResults(root, config, featureAreas(config, feature));
86
+ loaded.files = loaded.files.filter((f) => f.mtimeMs >= startedMs - 2000);
87
+ const results = loaded.files.length ? Object.fromEntries(acResults(loaded, feature.key)) : null;
88
+ return recordTestRun(root, config, feature, { runs, ui, results }, now());
89
+ }
90
+ /** Records a finished run for the change as it is now. */
91
+ export function recordTestRun(root, config, feature, outcome, at) {
92
+ const run = {
93
+ schema: 1,
94
+ at_utc: at,
95
+ tree_hash: treeHash(root, config),
96
+ head_commit: git(root, ['rev-parse', '--verify', '--quiet', 'HEAD'], { allowFail: true })?.trim() ?? null,
97
+ ...outcome,
98
+ };
99
+ writeJson(join(feature.dir, TEST_RUN_FILE), run);
100
+ return run;
101
+ }
package/dist/types.js CHANGED
@@ -1,5 +1 @@
1
- /**
2
- * The shapes of agjan's records and configuration, as the JSON schemas in schemas/
3
- * describe them (approvals, reviews, log, tasks, config). Types only: nothing here runs.
4
- */
5
1
  export {};