agjan 0.0.20 → 0.0.21

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 (56) hide show
  1. package/dist/adapters/claude-code.js +9 -3
  2. package/dist/auto.js +4 -0
  3. package/dist/baseline.js +11 -8
  4. package/dist/commands/check.js +65 -13
  5. package/dist/commands/gates.js +9 -1
  6. package/dist/commands/lint.js +16 -5
  7. package/dist/commands/new.js +4 -3
  8. package/dist/commands/setup.js +91 -81
  9. package/dist/config.js +24 -0
  10. package/dist/fix.js +13 -10
  11. package/dist/git.js +57 -9
  12. package/dist/launcher.js +9 -3
  13. package/dist/progress-view.js +35 -23
  14. package/dist/progress.js +103 -38
  15. package/dist/qa.js +10 -5
  16. package/dist/review-policy.js +4 -1
  17. package/dist/review.js +82 -35
  18. package/dist/schema.js +85 -0
  19. package/dist/scope.js +12 -4
  20. package/dist/tests-map.js +17 -11
  21. package/docs/guide.md +25 -7
  22. package/kit/domains/btp/domain.json +2 -2
  23. package/kit/hooks/guard.mjs +53 -9
  24. package/kit/skills/agjan-design/SKILL.md +13 -0
  25. package/kit/skills/agjan-fix/SKILL.md +1 -1
  26. package/kit/skills/agjan-spec/SKILL.md +7 -1
  27. package/kit/skills/agjan-spec/references/elicitation.md +135 -0
  28. package/kit/skills/btp-architect/SKILL.md +7 -2
  29. package/kit/skills/btp-architect/references/deployment.md +43 -0
  30. package/kit/skills/btp-architect/references/security.md +59 -4
  31. package/kit/skills/cap-developer/SKILL.md +19 -7
  32. package/kit/skills/cap-developer/references/agents.md +90 -0
  33. package/kit/skills/cap-developer/references/handlers.md +88 -9
  34. package/kit/skills/cap-developer/references/modeling.md +41 -0
  35. package/kit/skills/cap-developer/references/project-setup.md +57 -7
  36. package/kit/skills/cap-developer/references/services.md +172 -7
  37. package/kit/skills/cap-developer/references/testing.md +79 -6
  38. package/kit/skills/cap-developer/references/typescript.md +8 -7
  39. package/kit/skills/cap-developer/references/validation-security.md +74 -2
  40. package/kit/skills/fiori-developer/SKILL.md +21 -1
  41. package/kit/skills/fiori-developer/references/accessibility.md +65 -0
  42. package/kit/skills/fiori-developer/references/app-setup.md +10 -3
  43. package/kit/skills/fiori-developer/references/elements-cookbook.md +71 -0
  44. package/kit/skills/fiori-developer/references/elements.md +82 -9
  45. package/kit/skills/fiori-developer/references/freestyle-ts.md +27 -0
  46. package/kit/skills/fiori-developer/references/testing.md +5 -0
  47. package/kit/skills/fiori-developer/references/ui5-basics.md +34 -1
  48. package/kit/skills/qa-tester/SKILL.md +11 -4
  49. package/kit/skills/qa-tester/references/techniques.md +123 -0
  50. package/kit/skills/solution-reviewer/SKILL.md +10 -0
  51. package/kit/skills/solution-reviewer/references/defects.md +154 -0
  52. package/kit/templates/agents-block.md +1 -1
  53. package/kit/templates/agjan-ci.yml +3 -0
  54. package/package.json +1 -1
  55. package/schemas/config.schema.json +1 -1
  56. package/schemas/reviews.schema.json +1 -1
package/dist/review.js CHANGED
@@ -2,18 +2,19 @@ import { createHash, randomBytes } from 'node:crypto';
2
2
  import { existsSync, lstatSync, mkdirSync, readFileSync, readlinkSync, writeFileSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
4
  import { stringify as toYaml } from 'yaml';
5
- import { git, changedFiles, mergeBase, resolveBase } from './git.js';
5
+ import { git, changedFiles, contentIds, mergeBase, paths, resolveBase } from './git.js';
6
6
  import { resolveArea } from './config.js';
7
7
  import { sha256 } from './hash.js';
8
+ import { matcher } from './scope.js';
8
9
  import { readJson, writeJson } from './json-file.js';
9
- import { APPROVALS_FILE, FEATURES_DIR, REVIEWS_FILE, loadFeature } from './feature.js';
10
+ import { APPROVALS_FILE, FEATURES_DIR, REVIEWS_FILE, loadFeature, unitOf } from './feature.js';
10
11
  import { acTestFiles, repoFiles } from './tests-map.js';
11
12
  import { fixRules } from './fix.js';
12
13
  import { watchedHashes } from './baseline.js';
13
14
  import { acResults, loadResults, resultLabel } from './test-results.js';
14
15
  import { LOG_FILE, appendLog } from './log.js';
15
16
  import { AgjanError } from './errors.js';
16
- import { nextRound } from './review-policy.js';
17
+ import { nextRound, roundState } from './review-policy.js';
17
18
  import { designProblems, documentProblems } from './validate.js';
18
19
  import { QA_STEP, qaApplies, qaDirs, qaProblem, qaState, qaTestFiles, qaTestsHash } from './qa.js';
19
20
  import { buildProgress } from './progress.js';
@@ -23,9 +24,16 @@ const CONTEXT_DIR = '.agjan/review-contexts';
23
24
  const MAX_DIFF_BYTES = 200_000;
24
25
  const SEVERITIES = ['blocker', 'major', 'minor'];
25
26
  const VERDICTS = ['pass', 'pass-with-notes', 'blocked'];
26
- /** The files of a unit that agjan writes itself (records): outside every review's tree hash. */
27
- export function scriptOwned(slug) {
28
- return new Set([APPROVALS_FILE, REVIEWS_FILE, REVIEW_MD, LOG_FILE, 'report.md', 'progress.md', 'fix.json', 'fix.md'].map((f) => `${FEATURES_DIR}/${slug}/${f}`));
27
+ /** 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']);
29
+ /**
30
+ * Whether a path is a record agjan writes itself (approvals, reviews, log, progress, …) in
31
+ * the folder of any unit. Records are outside every review's tree hash: recording a review
32
+ * or a decision for one feature must not make another feature's review stale.
33
+ */
34
+ export function isRecord(path) {
35
+ const unit = unitOf(path);
36
+ return unit !== null && RECORD_FILES.has(path.slice(`${FEATURES_DIR}/${unit}/`.length));
29
37
  }
30
38
  /**
31
39
  * What a changed path holds now: the file's bytes, a symbolic link's target, or null when
@@ -47,19 +55,18 @@ function currentContent(path) {
47
55
  }
48
56
  /**
49
57
  * Hash of the change as it stands: every file changed relative to the merge-base
50
- * (committed, staged, unstaged, untracked) with its current content, except the
51
- * feature's script-owned files. Any write to the working tree changes it.
58
+ * (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.
60
+ * The content is taken as git stores it (`contentIds`), so the hash is the same in a CRLF
61
+ * checkout on Windows and in CI.
52
62
  */
53
- export function treeHash(root, config, slug, except = []) {
54
- const skip = scriptOwned(slug);
63
+ export function treeHash(root, config, except = []) {
64
+ const files = changedFiles(root, resolveBase(root, config.git?.base))
65
+ .filter((file) => !isRecord(file) && !file.startsWith('.agjan/') && !except.some((dir) => file.startsWith(dir)));
66
+ const ids = contentIds(root, files);
55
67
  const hash = createHash('sha256');
56
- for (const file of changedFiles(root, resolveBase(root, config.git?.base))) {
57
- if (skip.has(file) || file.startsWith('.agjan/') || except.some((dir) => file.startsWith(dir)))
58
- continue;
59
- const content = currentContent(join(root, file));
60
- hash.update(file).update('\0');
61
- hash.update(content ? createHash('sha256').update(content).digest('hex') : 'deleted').update('\0');
62
- }
68
+ for (const file of files)
69
+ hash.update(file).update('\0').update(ids.get(file) ?? 'deleted').update('\0');
63
70
  return `sha256:${hash.digest('hex')}`;
64
71
  }
65
72
  /**
@@ -90,23 +97,49 @@ export function parseStep(step, feature, config) {
90
97
  return { step: `build:${area.name}`, kind: 'build', tasks: byArea };
91
98
  }
92
99
  function capped(text) {
93
- if (Buffer.byteLength(text) <= MAX_DIFF_BYTES)
100
+ const bytes = Buffer.from(text);
101
+ if (bytes.length <= MAX_DIFF_BYTES)
94
102
  return text;
95
- return `${text.slice(0, MAX_DIFF_BYTES)}\n\n[diff truncated at ${MAX_DIFF_BYTES} bytes; read the files directly]\n`;
103
+ return `${bytes.subarray(0, MAX_DIFF_BYTES).toString('utf8')}\n\n[diff truncated at ${MAX_DIFF_BYTES} bytes; read the files directly]\n`;
96
104
  }
97
- /** Diff of the given path patterns against the merge-base, untracked files included. */
98
- function diffOf(root, base, patterns) {
99
- if (patterns.length === 0)
105
+ /** Files per `git diff` call: short enough for any command line, Windows included. */
106
+ const DIFF_BATCH = 100;
107
+ /** Diff of the given changed files against the merge-base, untracked files included. */
108
+ function diffOfFiles(root, base, files) {
109
+ if (files.length === 0)
100
110
  return '(no changes)\n';
101
- const from = mergeBase(root, base) ?? 'HEAD';
102
- const specs = patterns.map((p) => `:(glob)${p.endsWith('/') ? `${p}**` : p}`);
103
- let out = git(root, ['diff', '--no-color', '--no-ext-diff', from, '--', ...specs], { allowFail: true }) ?? '';
104
- const untracked = git(root, ['ls-files', '--others', '--exclude-standard', '--', ...specs]).split('\n').filter(Boolean);
105
- for (const file of untracked) {
111
+ const from = mergeBase(root, base) ?? (git(root, ['rev-parse', '--verify', '--quiet', 'HEAD'], { allowFail: true }) ? 'HEAD' : null);
112
+ const untracked = new Set(paths(git(root, ['ls-files', '--others', '--exclude-standard', '-z'])));
113
+ const tracked = files.filter((f) => !untracked.has(f));
114
+ let out = '';
115
+ for (let i = 0; i < tracked.length; i += DIFF_BATCH) {
116
+ // Literal paths: a file name with [ ] or * names that file only.
117
+ const specs = tracked.slice(i, i + DIFF_BATCH).map((f) => `:(literal)${f}`);
118
+ try {
119
+ // Without a commit yet, the change is what is staged (and untracked, below).
120
+ // core.quotePath=false: file names with non-ASCII characters as they are, not as octal escapes.
121
+ out += git(root, ['-c', 'core.quotePath=false', 'diff', '--no-color', '--no-ext-diff', ...(from ? [from] : ['--cached']), '--', ...specs]);
122
+ }
123
+ catch (error) {
124
+ // Never "(no changes)" for a diff that failed: the reviewer would judge a change it did not see.
125
+ out += `(the diff could not be produced: ${error.message}; read the changed files directly)\n`;
126
+ break;
127
+ }
128
+ }
129
+ for (const file of files.filter((f) => untracked.has(f))) {
106
130
  out += `\n--- new file: ${file}\n${currentContent(join(root, file))?.toString('utf8') ?? '(deleted)'}`;
107
131
  }
108
132
  return capped(out || '(no changes)\n');
109
133
  }
134
+ /**
135
+ * Diff of the changed files that the path patterns allow, read with the same matcher as the
136
+ * scope check: the reviewer sees exactly what `agjan check` counts as in scope (git's own
137
+ * pathspecs differ, for example on braces).
138
+ */
139
+ function diffOf(root, base, patterns) {
140
+ const allowed = matcher(patterns);
141
+ return diffOfFiles(root, base, changedFiles(root, base).filter((f) => allowed(f)));
142
+ }
110
143
  function section(title, body) {
111
144
  return `## ${title}\n\n${body.trimEnd()}\n`;
112
145
  }
@@ -194,7 +227,7 @@ export function buildContextText(root, config, feature, parsed) {
194
227
  const verdict = rules.problems.length ? rules.problems.map((p) => `- ${p}`).join('\n') : 'within the limits';
195
228
  parts.push(section('Fix description', description));
196
229
  parts.push(section('Fast-path rules', `${rules.total} changed lines (limit ${rules.limits.max_total}). ${verdict}\n\n${files}`));
197
- parts.push(section('Diff', fence(diffOf(root, base, rules.files.map((f) => f.path)), 'diff')));
230
+ parts.push(section('Diff', fence(diffOfFiles(root, base, rules.files.map((f) => f.path)), 'diff')));
198
231
  }
199
232
  else if (parsed.kind === 'map') {
200
233
  if (!baselineText)
@@ -239,7 +272,7 @@ export function buildContextText(root, config, feature, parsed) {
239
272
  const unrecorded = results
240
273
  ? ''
241
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.';
242
- const changed = changedFiles(root, base).filter((f) => !scriptOwned(feature.slug).has(f) && !f.startsWith('.agjan/'));
275
+ const changed = changedFiles(root, base).filter((f) => !isRecord(f) && !f.startsWith('.agjan/'));
243
276
  parts.push(section('Acceptance criteria', acsText(feature)));
244
277
  parts.push(section('AC coverage (test files mentioning the AC id, and test results)', `| AC | verification | test files | result |\n|---|---|---|---|\n${coverage}${unrecorded}`));
245
278
  parts.push(section(docPath(feature, 'design.md'), fence(feature.design.text, 'md')));
@@ -253,7 +286,7 @@ export function buildContextText(root, config, feature, parsed) {
253
286
  ? `${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
287
  : 'not run'));
255
288
  }
256
- parts.push(section('Full diff', fence(diffOf(root, base, changed), 'diff')));
289
+ parts.push(section('Full diff', fence(diffOfFiles(root, base, changed), 'diff')));
257
290
  }
258
291
  if (baselineText && parsed.kind !== 'build' && parsed.kind !== 'fix')
259
292
  parts.push(section('Baseline (docs/agjan/project.md)', fence(baselineText, 'md')));
@@ -303,17 +336,30 @@ function unfinishedDocuments(feature, config, step) {
303
336
  return;
304
337
  throw new AgjanError(`the documents are not ready for the ${step} review; complete them first:\n${problems.map((p) => ` - ${p}`).join('\n')}`);
305
338
  }
339
+ /**
340
+ * A step still blocked at its round limit (design 7.4) gets no new round until the user
341
+ * granted one (`agjan review extend`): the limit bounds the cost, and the grant is the record
342
+ * that a person decided to go on.
343
+ */
344
+ function withinRoundLimit(feature, config, step) {
345
+ const rounds = roundState(feature, config, step);
346
+ if (!rounds.exhausted)
347
+ return;
348
+ throw new AgjanError(`the ${step} step is still blocked after ${rounds.round} of ${rounds.limit} rounds; no new round without the user. ` +
349
+ `The main agent asks the user whether to run another round, and after a yes runs: npx agjan review extend ${step}`);
350
+ }
306
351
  export function createReviewContext(root, config, { feature: slug, step }) {
307
352
  const feature = loadFeature(root, slug);
308
353
  const parsed = parseStep(step, feature, config);
309
354
  unfinishedDocuments(feature, config, parsed.step);
310
355
  if (parsed.step === QA_STEP)
311
356
  throw new AgjanError('step qa is done by the QA agent (agjan-qa, qa_context), not by a reviewer');
357
+ withinRoundLimit(feature, config, parsed.step);
312
358
  // The final review comes after QA (decision 81).
313
359
  const qa = parsed.step === 'verify' ? qaProblem(root, config, feature) : null;
314
360
  if (qa)
315
361
  throw new AgjanError(`the final review waits for QA: ${qa}`);
316
- const tree = treeHash(root, config, feature.slug);
362
+ const tree = treeHash(root, config);
317
363
  unchangedSinceFindings(feature, parsed.step, tree);
318
364
  const text = buildContextText(root, config, feature, parsed);
319
365
  const id = `${feature.key}-C${randomBytes(4).toString('hex')}`;
@@ -430,7 +476,7 @@ function storeRecord(root, result, { host = 'unknown', isolation = 'unknown', no
430
476
  */
431
477
  export function recordReview(root, config, input, recorder) {
432
478
  const result = validResult(root, input, 'review');
433
- if (treeHash(root, config, result.feature.slug) !== result.meta.tree_hash) {
479
+ if (treeHash(root, config) !== result.meta.tree_hash) {
434
480
  throw new AgjanError('the working tree changed since review_context was called; nothing was recorded. ' +
435
481
  'A reviewer must not change files. Call review_context again and review the current state.');
436
482
  }
@@ -450,6 +496,7 @@ export function createQaContext(root, config, { feature: slug }) {
450
496
  const progress = buildProgress(root, config, feature);
451
497
  if (!progress.complete || progress.due.length)
452
498
  throw new AgjanError('QA runs after the build: every task committed and its reviews done (npx agjan status)');
499
+ withinRoundLimit(feature, config, QA_STEP);
453
500
  const dirs = qaDirs(feature.slug);
454
501
  const baseline = join(root, FEATURES_DIR, 'project.md');
455
502
  const runLocally = existsSync(baseline) ? (/^## Run locally\s*$([\s\S]*?)(?=^## |\s*$(?![\s\S]))/m.exec(readFileSync(baseline, 'utf8'))?.[1] ?? '').trim() : '';
@@ -483,7 +530,7 @@ export function createQaContext(root, config, { feature: slug }) {
483
530
  step: QA_STEP,
484
531
  documents: { spec: feature.spec.hash, design: feature.designHash ?? undefined },
485
532
  inputs_hash: sha256(text),
486
- tree_hash: treeHash(root, config, feature.slug, dirs),
533
+ tree_hash: treeHash(root, config, dirs),
487
534
  base_commit: mergeBase(root, base),
488
535
  head_commit: git(root, ['rev-parse', '--verify', '--quiet', 'HEAD'], { allowFail: true })?.trim() ?? null,
489
536
  };
@@ -499,12 +546,12 @@ export function createQaContext(root, config, { feature: slug }) {
499
546
  export function recordQa(root, config, input, recorder) {
500
547
  const result = validResult(root, input, 'qa');
501
548
  const slug = result.feature.slug;
502
- if (treeHash(root, config, slug, qaDirs(slug)) !== result.meta.tree_hash) {
549
+ if (treeHash(root, config, qaDirs(slug)) !== result.meta.tree_hash) {
503
550
  throw new AgjanError(`files outside the QA folders (${qaDirs(slug).join(', ')}) changed since qa_context was called; nothing was recorded. ` +
504
551
  'QA writes only its own tests. Undo the other changes, then call qa_context again.');
505
552
  }
506
553
  return storeRecord(root, result, recorder, {
507
- tree_hash: treeHash(root, config, slug),
554
+ tree_hash: treeHash(root, config),
508
555
  qa_tests_hash: qaTestsHash(root, slug),
509
556
  qa_tests: qaTestFiles(root, slug),
510
557
  });
package/dist/schema.js ADDED
@@ -0,0 +1,85 @@
1
+ import { readFileSync } from 'node:fs';
2
+ const cache = new Map();
3
+ export function loadSchema(name) {
4
+ let schema = cache.get(name);
5
+ if (!schema) {
6
+ schema = JSON.parse(readFileSync(new URL(`../schemas/${name}.schema.json`, import.meta.url), 'utf8'));
7
+ cache.set(name, schema);
8
+ }
9
+ return schema;
10
+ }
11
+ function typeOf(value) {
12
+ if (value === null)
13
+ return 'null';
14
+ if (Array.isArray(value))
15
+ return 'array';
16
+ if (Number.isInteger(value))
17
+ return 'integer';
18
+ return typeof value;
19
+ }
20
+ function matchesType(value, type) {
21
+ const actual = typeOf(value);
22
+ return actual === type || (type === 'number' && actual === 'integer');
23
+ }
24
+ /** `ci.policy_changes`, `records[2].verdict`: where a problem is, for people. */
25
+ function at(path) {
26
+ return path || '(the file)';
27
+ }
28
+ /** The problems of `value` against `schema`; empty when it is valid. */
29
+ export function validate(schema, value, root = schema, path = '') {
30
+ if (schema.$ref) {
31
+ const target = String(schema.$ref).replace(/^#\//, '').split('/').reduce((node, key) => node[key], root);
32
+ return validate(target, value, root, path);
33
+ }
34
+ if (schema.oneOf) {
35
+ const results = schema.oneOf.map((option) => validate(option, value, root, path));
36
+ const valid = results.filter((r) => r.length === 0).length;
37
+ if (valid === 1)
38
+ return [];
39
+ return valid === 0 ? results.reduce((a, b) => (b.length < a.length ? b : a)) : [`${at(path)}: matches more than one allowed form`];
40
+ }
41
+ if (schema.type) {
42
+ const types = Array.isArray(schema.type) ? schema.type : [schema.type];
43
+ if (!types.some((t) => matchesType(value, t)))
44
+ return [`${at(path)}: must be ${types.join(' or ')}, not ${typeOf(value)}`];
45
+ }
46
+ const errors = [];
47
+ if ('const' in schema && value !== schema.const)
48
+ errors.push(`${at(path)}: must be ${JSON.stringify(schema.const)}`);
49
+ if (schema.enum && !schema.enum.includes(value))
50
+ errors.push(`${at(path)}: ${JSON.stringify(value)} is not one of ${schema.enum.map((e) => JSON.stringify(e)).join(', ')}`);
51
+ if (typeof value === 'string') {
52
+ if (schema.pattern && !new RegExp(schema.pattern).test(value))
53
+ errors.push(`${at(path)}: '${value}' does not match ${schema.pattern}`);
54
+ if (schema.minLength !== undefined && value.length < schema.minLength)
55
+ errors.push(`${at(path)}: too short`);
56
+ }
57
+ if (typeof value === 'number' && schema.minimum !== undefined && value < schema.minimum)
58
+ errors.push(`${at(path)}: must be at least ${schema.minimum}`);
59
+ if (Array.isArray(value)) {
60
+ if (schema.minItems !== undefined && value.length < schema.minItems)
61
+ errors.push(`${at(path)}: needs at least ${schema.minItems} item(s)`);
62
+ if (schema.maxItems !== undefined && value.length > schema.maxItems)
63
+ errors.push(`${at(path)}: at most ${schema.maxItems} item(s)`);
64
+ if (schema.items)
65
+ value.forEach((item, i) => errors.push(...validate(schema.items, item, root, `${path}[${i}]`)));
66
+ }
67
+ if (typeOf(value) === 'object') {
68
+ const object = value;
69
+ for (const key of schema.required ?? [])
70
+ if (!(key in object))
71
+ errors.push(`${at(path)}: '${key}' is missing`);
72
+ for (const [key, item] of Object.entries(object)) {
73
+ if (item === undefined)
74
+ continue;
75
+ const where = path ? `${path}.${key}` : key;
76
+ if (schema.properties?.[key])
77
+ errors.push(...validate(schema.properties[key], item, root, where));
78
+ else if (schema.additionalProperties === false)
79
+ errors.push(`${where}: unknown ${path ? 'key' : 'setting'}`);
80
+ else if (typeof schema.additionalProperties === 'object')
81
+ errors.push(...validate(schema.additionalProperties, item, root, where));
82
+ }
83
+ }
84
+ return errors;
85
+ }
package/dist/scope.js CHANGED
@@ -1,15 +1,23 @@
1
1
  import picomatch from 'picomatch';
2
2
  import { resolveArea } from './config.js';
3
3
  import { qaDirs } from './qa.js';
4
- /** A path ending in '/' means the whole folder. */
5
- function toGlob(pattern) {
6
- return pattern.endsWith('/') ? `${pattern}**` : pattern;
4
+ /** Characters that make a pattern a glob. */
5
+ const GLOB = /[*?[\]{}()!+@]/;
6
+ /**
7
+ * The globs of one pattern. A path ending in '/' means the whole folder. A plain path (no
8
+ * glob characters) names a file or a folder, as git reads it, so `srv/lib` also covers
9
+ * `srv/lib/util.js` (a path cannot be both a file and a folder).
10
+ */
11
+ function toGlobs(pattern) {
12
+ if (pattern.endsWith('/'))
13
+ return [`${pattern}**`];
14
+ return GLOB.test(pattern) ? [pattern] : [pattern, `${pattern}/**`];
7
15
  }
8
16
  /** Case-sensitive matcher for POSIX repository paths, the same on every OS (design 4.5). */
9
17
  export function matcher(patterns) {
10
18
  if (patterns.length === 0)
11
19
  return () => false;
12
- return picomatch(patterns.map(toGlob), { dot: true, nocase: false, windows: false });
20
+ return picomatch(patterns.flatMap(toGlobs), { dot: true, nocase: false, windows: false });
13
21
  }
14
22
  /**
15
23
  * The patterns a feature in Build may change: its task paths, the implicit allowlist of
package/dist/tests-map.js CHANGED
@@ -1,24 +1,30 @@
1
1
  import { readFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
- import { git } from './git.js';
3
+ import { git, paths } from './git.js';
4
4
  import { matcher } from './scope.js';
5
5
  /** Tracked and untracked (not ignored) files of the repository. */
6
6
  export function repoFiles(root) {
7
- return git(root, ['ls-files', '--cached', '--others', '--exclude-standard']).split('\n').filter(Boolean);
7
+ return paths(git(root, ['ls-files', '--cached', '--others', '--exclude-standard', '-z']));
8
8
  }
9
- /** For each AC id of the feature key, the test files that mention it. */
10
- export function acTestFiles(root, config, areaNames, key) {
9
+ /** For each AC id of the feature key, the test files that mention it. `memo` shares the reads between units. */
10
+ export function acTestFiles(root, config, areaNames, key, memo) {
11
11
  const isTest = matcher(areaNames.flatMap((name) => config.tests[name] ?? []));
12
12
  const pattern = new RegExp(`\\b${key}-AC[1-9][0-9]*\\b`, 'g');
13
13
  const found = new Map();
14
- for (const file of repoFiles(root).filter(isTest)) {
15
- let text;
16
- try {
17
- text = readFileSync(join(root, file), 'utf8');
18
- }
19
- catch {
20
- continue; // deleted in the working tree
14
+ const files = memo ? (memo.repoFiles ??= repoFiles(root)) : repoFiles(root);
15
+ for (const file of files.filter(isTest)) {
16
+ let text = memo?.texts.get(file);
17
+ if (text === undefined) {
18
+ try {
19
+ text = readFileSync(join(root, file), 'utf8');
20
+ }
21
+ catch {
22
+ text = null; // deleted in the working tree
23
+ }
24
+ memo?.texts.set(file, text);
21
25
  }
26
+ if (text === null)
27
+ continue;
22
28
  for (const match of text.matchAll(pattern)) {
23
29
  if (!found.has(match[0]))
24
30
  found.set(match[0], new Set());
package/docs/guide.md CHANGED
@@ -78,7 +78,9 @@ The global `agjan` runs `init`, `--help` and `--version` itself. Every other com
78
78
  in the agjan the project pins in `node_modules`. If that is not installed (a fresh clone),
79
79
  the command offers to run the install first; without a terminal it fails and says how
80
80
  (`agjan --yes <command>` installs without asking). Without a global install, `npx agjan init
81
- <folder>` works the same.
81
+ <folder>` works the same. `AGJAN_LAUNCHER=0` turns the launcher off: the agjan you started runs
82
+ the command itself. The CI workflow uses it to check pull requests with the version pinned on
83
+ the base branch.
82
84
 
83
85
  The global install is for starting projects. Day to day, use `npx agjan <command>` in the
84
86
  project: it runs the pinned copy directly and works on every machine, with or without a
@@ -386,7 +388,9 @@ it is plain text. `NO_COLOR=1` turns colors off, `FORCE_COLOR=1` turns them on.
386
388
  ## Configuration
387
389
 
388
390
  `agjan.config.json` is layered over the package and domain defaults: objects merge,
389
- lists replace. The schema is `node_modules/agjan/schemas/config.schema.json`.
391
+ lists replace. The schema is `node_modules/agjan/schemas/config.schema.json`; every command
392
+ checks the file against it and stops with the reasons when a setting is unknown or a value
393
+ is wrong, so a typo is never a silent default.
390
394
 
391
395
  ```json
392
396
  {
@@ -422,7 +426,7 @@ lists replace. The schema is `node_modules/agjan/schemas/config.schema.json`.
422
426
  | `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`) |
423
427
  | `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 |
424
428
  | `mcp.servers.<name>` | documentation MCP servers: `command`, `args`, `env`, `areas`, `enabled` |
425
- | `ci.policy_changes`, `ci.untracked_changes` | `warn` or `fail` in `check --ci` |
429
+ | `ci.policy_changes`, `ci.untracked_changes` | `warn` or `fail` in `check --ci`; CI reads them from the base branch, so a pull request cannot lower them for itself |
426
430
 
427
431
  `npx agjan status` prints the language, the round limit and the attempts in its first
428
432
  line; the skills take these values, and the reviewer agent per step, from `status`.
@@ -473,8 +477,11 @@ so that is where the last check belongs.
473
477
  Actions workflow. On every pull request, GitHub runs `agjan check --ci` and shows the
474
478
  result as a check named **agjan-check** on the pull request: green, or red with the
475
479
  reason (a document changed after its approval, code outside the approved paths, a stale
476
- final review). It uses the agjan version pinned on `main`, so a pull request cannot
477
- bring its own, weaker checker.
480
+ final review). It runs the agjan version pinned on `main`, fetched from the npm registry,
481
+ with `AGJAN_LAUNCHER=0` so that it does not hand the check to a version the pull request
482
+ pins; a pull request cannot bring its own, weaker checker. The `ci` settings of
483
+ `agjan.config.json` come from `main` too. Any other change to the configuration is reported
484
+ as a policy change, a warning unless `ci.policy_changes` is `fail`.
478
485
 
479
486
  **What you turn on.** By default, GitHub lets you merge even when a check is red. A
480
487
  *branch rule* makes the check, and a review, required:
@@ -492,22 +499,33 @@ bring its own, weaker checker.
492
499
 
493
500
  **Optionally, owners for the rules.** A `CODEOWNERS` file names who must review changes
494
501
  to certain files. With **Require review from Code Owners** turned on in the same rule,
495
- changes to agjan's configuration, approvals, hooks and workflows need your review.
496
- Create `.github/CODEOWNERS` (replace `@<owner>` with your GitHub user or team):
502
+ changes to agjan's configuration, records, agent instructions, hooks and workflows need
503
+ your review. Create `.github/CODEOWNERS` (replace `@<owner>` with your GitHub user or team):
497
504
 
498
505
  ```text
499
506
  # agjan: changes to the rules need an owner's review
500
507
  /agjan.config.json @<owner>
501
508
  /agjan.lock.json @<owner>
502
509
  /docs/agjan/**/approvals.json @<owner>
510
+ /docs/agjan/**/reviews.json @<owner>
511
+ /AGENTS.md @<owner>
512
+ /CLAUDE.md @<owner>
503
513
  /.claude/ @<owner>
504
514
  /.github/agents/ @<owner>
505
515
  /.github/hooks/ @<owner>
506
516
  /.github/workflows/ @<owner>
517
+ /.github/CODEOWNERS @<owner>
518
+ /.mcp.json @<owner>
519
+ /.vscode/mcp.json @<owner>
520
+ /.husky/ @<owner>
507
521
  /package.json @<owner>
508
522
  /package-lock.json @<owner>
509
523
  ```
510
524
 
525
+ `reviews.json` holds the reviewer's verdicts, which the gates and CI rely on; `.vscode/mcp.json`
526
+ says how isolated a VS Code review is; `.husky/` holds the pre-commit hook when the project
527
+ uses husky.
528
+
511
529
  Good to know:
512
530
 
513
531
  - GitHub Actions minutes: private repositories have a monthly quota. When it is used up,
@@ -22,7 +22,7 @@
22
22
  "verify": {}
23
23
  }
24
24
  },
25
- "risk_paths": ["xs-security.json", "mta.yaml", "srv/**/*auth*", "srv/**/*-access.cds"],
26
- "protected": ["mta.yaml", "xs-security.json", "srv/**/*.cds"],
25
+ "risk_paths": ["xs-security.json", "ams/**", "mta.yaml", "srv/**/*auth*", "srv/**/*-access.cds"],
26
+ "protected": ["mta.yaml", "xs-security.json", "ams/**", "srv/**/*.cds"],
27
27
  "watched": ["db/*.cds", "srv/*.cds", "app/*/webapp/manifest.json", "mta.yaml"]
28
28
  }
@@ -6,13 +6,16 @@
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
  *
9
+ * It denies shell commands that start the agjan MCP server or call its record tools: they
10
+ * belong to the reviewer and QA agents (design decision 52).
11
+ *
9
12
  * It denies file edits by shell or script commands (python/node scripts that write files,
10
13
  * sed -i, cat > file, …) so that agents use their file edit tool, unless the project sets
11
14
  * `agent.script_edits` to "allow" (design decision 63).
12
15
  *
13
16
  * File edit tools (Copilot `edit`/`create`, Claude Code `Edit`/`Write`/`MultiEdit`): hand
14
- * edits of agjan's records (approvals.json, reviews.json, review.md, log.jsonl, …) are always
15
- * denied.
17
+ * edits of agjan's records (approvals.json, reviews.json, review.md, log.jsonl, the review
18
+ * contexts in .agjan/, …) are always denied.
16
19
  *
17
20
  * The guard only denies. Everything else is left to the host, which asks the user as it
18
21
  * is configured to (design decision 76).
@@ -38,8 +41,43 @@ import { fileURLToPath } from 'node:url';
38
41
  const REASON =
39
42
  '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
43
 
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|models\s+set)\b/;
44
+ /**
45
+ * agjan started as a command, up to its subcommand: the bin (`agjan`, `agjan.mjs`, the Windows
46
+ * shims `agjan.cmd` and `agjan.ps1`) or a package spec (`npx agjan@0.0.20`, `agjan@latest`),
47
+ * then any of the launcher's `--yes` / `-y` and npm exec's `--`.
48
+ */
49
+ const AGJAN = String.raw`\bagjan(?:\.(?:mjs|cmd|ps1))?(?:@[\w.^~*-]+)?["']?(?:\s+(?:--|-y|--yes)(?=\s))*\s+["']?`;
50
+
51
+ /** agjan followed by a human-only command. */
52
+ const HUMAN_ONLY = new RegExp(`${AGJAN}(approve|accept|reject|auto|models\\s+set)\\b`);
53
+
54
+ /**
55
+ * A human-only command named only as text, not run: quoted, as the pattern of a search
56
+ * (`grep`, `rg`, `git grep`, `git log --grep`) or a commit message, with nothing else in the
57
+ * line that could run it: no other command, pipe or redirect, no command substitution (a
58
+ * shell expands it even inside double quotes), no option that runs a command (`rg --pre`, a
59
+ * pager).
60
+ */
61
+ function onlyMentioned(/** @type {string} */ command) {
62
+ const plain = unquoted(command);
63
+ if (HUMAN_ONLY.test(plain) || /`|\$\(/.test(command) || /[|;&<>()]/.test(plain)) return false;
64
+ if (/\s(?:--pre|--pager|--open-files-in-pager|--ext-diff|--textconv)\b|\s-O/.test(plain)) return false;
65
+ return /^\s*(?:grep|egrep|fgrep|rg|ack|git\s+(?:grep|log|commit))\s/.test(plain);
66
+ }
67
+
68
+ const REVIEW_REASON =
69
+ 'The agjan MCP server and its tools belong to the reviewer and QA agents, which the host starts for them. Do not start agjan mcp or call review_record or qa_record yourself: delegate the review to the reviewer agent, as the skill says.';
70
+
71
+ /**
72
+ * Starting the agjan MCP server from a shell, or naming its record tools (a JSON-RPC call
73
+ * piped into it, a script that calls them): the main agent would record its own review
74
+ * (design decision 52). The hosts start the reviewer's server themselves, not through a
75
+ * shell tool, so the reviewer and the QA agent keep their tools.
76
+ */
77
+ const REVIEW_SERVER = new RegExp(`${AGJAN}mcp\\b`);
78
+ const RECORD_TOOLS = /\b(?:review_record|qa_record|recordReview|recordQa)\b/;
79
+ /** The review contexts in .agjan/, which review_record checks a result against. */
80
+ const CONTEXT_FILES = /\.agjan[\\/]+review-contexts\b/;
43
81
 
44
82
  const BRANCH_REASON =
45
83
  '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>).';
@@ -48,13 +86,14 @@ const BRANCH_REASON =
48
86
  * Commands that create or rename a branch: git switch -c/-C, git checkout -b/-B/--orphan,
49
87
  * git branch <name> (also -m/-c), git worktree add -b. Always denied: agents create branches
50
88
  * with npx agjan branch after asking the user (design decision 62); git options such as
51
- * `-C <dir>` may come before.
89
+ * `-C <dir>` may come before. `git branch` followed by a pipe, a redirect (`2>/dev/null`) or
90
+ * another command only lists the branches.
52
91
  */
53
92
  const BRANCH_CREATE = new RegExp(
54
93
  String.raw`\bgit(?:\s+-[cC]\s+\S+|\s+--[\w-]+(?:=\S+)?)*\s+` +
55
94
  String.raw`(?:switch\s+(?:\S+\s+)*?(?:-c|-C|--create|--force-create)\b` +
56
95
  String.raw`|checkout\s+(?:\S+\s+)*?(?:-b|-B|--orphan)\b` +
57
- String.raw`|branch\s+(?:(?:-[mMcCf]|--move|--copy|--force)\s+)*[^-\s]` +
96
+ String.raw`|branch\s+(?:(?:-[mMcCf]|--move|--copy|--force)\s+)*(?!\d*[<>])[^-\s|&;<>()]` +
58
97
  String.raw`|worktree\s+add\s+(?:\S+\s+)*?-[bB]\b)`,
59
98
  );
60
99
 
@@ -92,8 +131,12 @@ function unquoted(command) {
92
131
  const RECORD_REASON =
93
132
  'agjan writes this file itself (approvals, reviews, logs, progress, fix records, baseline). Never edit it by hand; use the agjan commands.';
94
133
 
95
- /** agjan's records inside docs/agjan/: never edited by an agent's edit tool. */
96
- const RECORD = /^docs\/agjan\/(?:.+\/)?(?:approvals\.json|reviews\.json|review\.md|log\.jsonl|progress\.md|report\.md|fix\.json|fix\.md)$|^docs\/agjan\/baseline\.json$|^\.agjan\/auto\.json$/;
134
+ /**
135
+ * agjan's records inside docs/agjan/, and what it keeps for them in .agjan/ (the auto mode
136
+ * default, the review contexts that review_record checks a result against): never edited by
137
+ * an agent's edit tool.
138
+ */
139
+ const RECORD = /^docs\/agjan\/(?:.+\/)?(?:approvals\.json|reviews\.json|review\.md|log\.jsonl|progress\.md|report\.md|fix\.json|fix\.md)$|^docs\/agjan\/baseline\.json$|^\.agjan\/auto\.json$|^\.agjan\/review-contexts\//;
97
140
 
98
141
  const AUTO_REASON =
99
142
  'The auto mode default (.agjan/auto.json) is the user\'s, set with npx agjan auto on --default in their terminal. Do not read, write, copy or remove it.';
@@ -141,7 +184,8 @@ export function decide(payload, config = {}, root = process.env.CLAUDE_PROJECT_D
141
184
  if (EDIT_TOOLS.has(payload?.toolName ?? payload?.tool_name ?? '')) return decideEdit(payload, root);
142
185
  const command = payload?.toolArgs?.command ?? payload?.tool_input?.command;
143
186
  if (typeof command !== 'string') return null;
144
- if (HUMAN_ONLY.test(command)) return answer(payload, 'deny', REASON);
187
+ if (HUMAN_ONLY.test(command) && !onlyMentioned(command)) return answer(payload, 'deny', REASON);
188
+ if (REVIEW_SERVER.test(command) || RECORD_TOOLS.test(command) || CONTEXT_FILES.test(command)) return answer(payload, 'deny', REVIEW_REASON);
145
189
  if (BRANCH_CREATE.test(command)) return answer(payload, 'deny', BRANCH_REASON);
146
190
  if (AUTO_FILE.test(command)) return answer(payload, 'deny', AUTO_REASON);
147
191
  if (config?.agent?.script_edits !== 'allow' && SCRIPT_EDITS.some((matches) => matches(command))) return answer(payload, 'deny', EDIT_REASON);
@@ -48,6 +48,19 @@ entity; "no draft" is only for read-only apps or apps that change data through a
48
48
  (fiori-developer). An AC the design cannot meet in the UI is a design error, not a
49
49
  build problem.
50
50
 
51
+ Then check the decisions for production, with the rules of the role skills you read:
52
+
53
+ | Area | Decide for the feature |
54
+ |---|---|
55
+ | `cap` (rule 6) | rows and paging, who changes a row at the same time (draft lock or `@odata.etag`), the fields only the server sets, personal data, where demo rows go |
56
+ | `btp` (rules 6 and 7) | how each new app is served, how persisted data moves when the model renames or deletes it, the identity service |
57
+ | `fiori` ("What every elements app gets right") | side effects and per-row availability of actions, confirmations, parameter labels, messages, value helps |
58
+
59
+ Write a decision for each point that applies, or one line under `## Risks and trade-offs`
60
+ why it does not. Each non-functional requirement of the spec gets a decision that meets
61
+ it. This is how the feature is built, not more scope: add nothing the spec does not ask
62
+ for.
63
+
51
64
  Then fill `## Answers to open technical questions` (one answer per question in the
52
65
  spec) and `## Risks and trade-offs`.
53
66
 
@@ -6,7 +6,7 @@ description: Fast path for a small agjan change (a bug fix, a label, a small cor
6
6
  # /agjan-fix
7
7
 
8
8
  A small change to existing files, checked by script and reviewed, without Spec and
9
- Design. Gate 3 (the human merge) still applies.
9
+ Design. A human still reviews and merges the pull request.
10
10
 
11
11
  ## 1. Is it a fix?
12
12