agjan 0.0.10 → 0.0.12

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 (119) hide show
  1. package/README.md +2 -2
  2. package/bin/agjan.mjs +9 -2
  3. package/dist/adapters/claude-code.js +105 -0
  4. package/dist/adapters/copilot.js +80 -0
  5. package/dist/auto.js +24 -0
  6. package/dist/baseline.js +66 -0
  7. package/dist/browser.js +46 -0
  8. package/dist/cli.js +164 -0
  9. package/dist/commands/branch.js +71 -0
  10. package/dist/commands/check.js +420 -0
  11. package/dist/commands/fix.js +122 -0
  12. package/dist/commands/gates.js +462 -0
  13. package/dist/commands/lint.js +76 -0
  14. package/dist/commands/log.js +72 -0
  15. package/dist/commands/map.js +47 -0
  16. package/dist/commands/new.js +65 -0
  17. package/dist/commands/pr-summary.js +168 -0
  18. package/dist/commands/progress.js +42 -0
  19. package/dist/commands/report.js +105 -0
  20. package/dist/commands/review.js +146 -0
  21. package/dist/commands/setup.js +393 -0
  22. package/dist/commands/status.js +303 -0
  23. package/dist/commands/ui-test.js +39 -0
  24. package/dist/config.js +110 -0
  25. package/dist/context.js +56 -0
  26. package/dist/copilot-mcp.js +56 -0
  27. package/dist/documents.js +207 -0
  28. package/dist/errors.js +15 -0
  29. package/dist/feature.js +221 -0
  30. package/dist/fix.js +117 -0
  31. package/dist/git.js +88 -0
  32. package/{src/hash.mjs → dist/hash.js} +11 -14
  33. package/dist/hook.js +47 -0
  34. package/dist/json-file.js +26 -0
  35. package/dist/log.js +50 -0
  36. package/dist/managed.js +182 -0
  37. package/dist/mcp-config.js +76 -0
  38. package/dist/mcp.js +142 -0
  39. package/dist/plan.js +40 -0
  40. package/dist/progress-view.js +494 -0
  41. package/dist/progress.js +106 -0
  42. package/{src/review-policy.mjs → dist/review-policy.js} +39 -47
  43. package/dist/review.js +435 -0
  44. package/dist/scope.js +30 -0
  45. package/dist/terminal.js +127 -0
  46. package/dist/test-results.js +101 -0
  47. package/dist/tests-map.js +29 -0
  48. package/dist/types.js +5 -0
  49. package/dist/ui.js +136 -0
  50. package/dist/usage.js +116 -0
  51. package/dist/validate.js +46 -0
  52. package/docs/guide.md +98 -37
  53. package/kit/domains/btp/domain.json +4 -4
  54. package/kit/hooks/guard.mjs +48 -119
  55. package/kit/skills/agjan-build/SKILL.md +14 -8
  56. package/kit/skills/agjan-design/SKILL.md +42 -6
  57. package/kit/skills/agjan-fix/SKILL.md +9 -10
  58. package/kit/skills/agjan-map/SKILL.md +9 -10
  59. package/kit/skills/agjan-spec/SKILL.md +22 -11
  60. package/kit/skills/agjan-verify/SKILL.md +46 -19
  61. package/kit/skills/cap-developer/SKILL.md +10 -2
  62. package/kit/skills/cap-developer/references/handlers.md +11 -9
  63. package/kit/skills/cap-developer/references/project-setup.md +21 -8
  64. package/kit/skills/cap-developer/references/testing.md +38 -14
  65. package/kit/skills/cap-developer/references/typescript.md +143 -0
  66. package/kit/skills/cap-developer/references/validation-security.md +26 -8
  67. package/kit/skills/fiori-developer/SKILL.md +20 -5
  68. package/kit/skills/fiori-developer/references/app-setup.md +91 -16
  69. package/kit/skills/fiori-developer/references/elements.md +19 -5
  70. package/kit/skills/fiori-developer/references/freestyle-ts.md +5 -1
  71. package/kit/skills/fiori-developer/references/testing.md +109 -15
  72. package/kit/templates/agents-block.md +7 -3
  73. package/package.json +11 -3
  74. package/schemas/approvals.schema.json +23 -2
  75. package/schemas/config.schema.json +0 -5
  76. package/schemas/log.schema.json +1 -1
  77. package/src/adapters/claude-code.mjs +0 -121
  78. package/src/adapters/copilot.mjs +0 -89
  79. package/src/baseline.mjs +0 -66
  80. package/src/cli.mjs +0 -155
  81. package/src/commands/branch.mjs +0 -60
  82. package/src/commands/check.mjs +0 -365
  83. package/src/commands/fix.mjs +0 -116
  84. package/src/commands/gates.mjs +0 -264
  85. package/src/commands/lint.mjs +0 -74
  86. package/src/commands/log.mjs +0 -60
  87. package/src/commands/map.mjs +0 -47
  88. package/src/commands/new.mjs +0 -53
  89. package/src/commands/pr-summary.mjs +0 -137
  90. package/src/commands/progress.mjs +0 -40
  91. package/src/commands/report.mjs +0 -115
  92. package/src/commands/review.mjs +0 -76
  93. package/src/commands/setup.mjs +0 -383
  94. package/src/commands/status.mjs +0 -248
  95. package/src/config.mjs +0 -122
  96. package/src/context.mjs +0 -67
  97. package/src/copilot-mcp.mjs +0 -56
  98. package/src/documents.mjs +0 -188
  99. package/src/errors.mjs +0 -16
  100. package/src/feature.mjs +0 -225
  101. package/src/fix.mjs +0 -108
  102. package/src/git.mjs +0 -83
  103. package/src/hook.mjs +0 -48
  104. package/src/json-file.mjs +0 -24
  105. package/src/log.mjs +0 -51
  106. package/src/managed.mjs +0 -178
  107. package/src/mcp-config.mjs +0 -83
  108. package/src/mcp.mjs +0 -147
  109. package/src/plan.mjs +0 -45
  110. package/src/progress-view.mjs +0 -466
  111. package/src/progress.mjs +0 -85
  112. package/src/review.mjs +0 -413
  113. package/src/scope.mjs +0 -30
  114. package/src/terminal.mjs +0 -118
  115. package/src/test-results.mjs +0 -111
  116. package/src/tests-map.mjs +0 -29
  117. package/src/ui.mjs +0 -136
  118. package/src/usage.mjs +0 -118
  119. package/src/validate.mjs +0 -41
@@ -4,44 +4,36 @@
4
4
  * how many attempts the writer has for failing deterministic checks
5
5
  * (`build.fix_attempts`). `agjan status` shows them; the skills follow `status`.
6
6
  */
7
-
8
- import { stillBlocked } from './feature.mjs';
9
- import { readLog } from './log.mjs';
10
-
7
+ import { stillBlocked } from './feature.js';
8
+ import { readLog } from './log.js';
11
9
  /** Default tier per kind of review step. */
12
10
  export const DEFAULT_TIERS = {
13
- spec: 'balanced',
14
- 'design:light': 'balanced',
15
- design: 'deep',
16
- build: 'balanced',
17
- verify: 'deep',
18
- fix: 'balanced',
19
- map: 'balanced',
11
+ spec: 'balanced',
12
+ 'design:light': 'balanced',
13
+ design: 'deep',
14
+ build: 'balanced',
15
+ verify: 'deep',
16
+ fix: 'balanced',
17
+ map: 'balanced',
20
18
  };
21
-
22
19
  /** `build:cap` and `build:T2` are both of kind `build`. */
23
20
  export function stepKind(step) {
24
- return step.startsWith('build:') ? 'build' : step;
21
+ return step.startsWith('build:') ? 'build' : step;
25
22
  }
26
-
27
23
  /** The generated reviewer agent for a step. There is no fast agent; `fast` uses the balanced one. */
28
24
  export function reviewerFor(config, step) {
29
- const kind = stepKind(step);
30
- const tier = config.review?.tiers?.[kind] ?? DEFAULT_TIERS[kind] ?? 'balanced';
31
- return tier === 'deep' ? 'agjan-reviewer-deep' : 'agjan-reviewer';
25
+ const kind = stepKind(step);
26
+ const tier = config.review?.tiers?.[kind] ?? DEFAULT_TIERS[kind] ?? 'balanced';
27
+ return tier === 'deep' ? 'agjan-reviewer-deep' : 'agjan-reviewer';
32
28
  }
33
-
34
29
  export function roundLimit(config) {
35
- return config.review?.rounds ?? 3;
30
+ return config.review?.rounds ?? 3;
36
31
  }
37
-
38
32
  export function fixAttempts(config) {
39
- return config.build?.fix_attempts ?? 3;
33
+ return config.build?.fix_attempts ?? 3;
40
34
  }
41
-
42
35
  /** The gate approvals that close a correction loop of a review step. */
43
36
  const CLOSING_APPROVALS = { spec: ['spec'], design: ['design'], 'design:light': ['spec', 'design'] };
44
-
45
37
  /**
46
38
  * The round the next review of `step` gets (design 7.4). Rounds count within one
47
39
  * correction loop: a loop ends with a review without findings (`pass`), with the gate's
@@ -50,42 +42,42 @@ const CLOSING_APPROVALS = { spec: ['spec'], design: ['design'], 'design:light':
50
42
  * round 1.
51
43
  */
52
44
  export function nextRound(feature, step) {
53
- const records = feature.reviews.records.filter((r) => r.step === step);
54
- const approvals = (CLOSING_APPROVALS[step] ?? []).map((gate) => feature.approvals.approvals[gate]?.at_utc).filter(Boolean);
55
- if (step.startsWith('build:')) {
56
- const verified = feature.reviews.records.filter((r) => r.step === 'verify' && !stillBlocked(feature, r));
57
- approvals.push(...verified.map((r) => r.at_utc));
58
- }
59
- let round = 1;
60
- for (let i = records.length - 1; i >= 0; i--) {
61
- const r = records[i];
62
- if (r.verdict === 'pass' || approvals.some((at) => at >= r.at_utc)) break;
63
- round += 1;
64
- }
65
- return round;
45
+ const records = feature.reviews.records.filter((r) => r.step === step);
46
+ const approvals = (CLOSING_APPROVALS[step] ?? []).map((gate) => feature.approvals.approvals[gate]?.at_utc).filter((at) => Boolean(at));
47
+ if (step.startsWith('build:')) {
48
+ const verified = feature.reviews.records.filter((r) => r.step === 'verify' && !stillBlocked(feature, r));
49
+ approvals.push(...verified.map((r) => r.at_utc));
50
+ }
51
+ let round = 1;
52
+ for (let i = records.length - 1; i >= 0; i--) {
53
+ const r = records[i];
54
+ if (r.verdict === 'pass' || approvals.some((at) => at >= r.at_utc))
55
+ break;
56
+ round += 1;
57
+ }
58
+ return round;
66
59
  }
67
-
68
60
  /**
69
61
  * The state of one review step: its latest round and verdict, and whether the round limit
70
62
  * (with the rounds the user granted) is reached with the step still blocked (design 7.4:
71
63
  * ask the user for another round, or hand over).
72
64
  */
73
65
  export function roundState(feature, config, step) {
74
- const records = feature.reviews.records.filter((r) => r.step === step);
75
- const last = records.at(-1) ?? null;
76
- const extra = extraRounds(feature, step);
77
- const limit = roundLimit(config) + extra;
78
- const round = last?.round ?? 0;
79
- return { last, round, next: nextRound(feature, step), limit, extra, exhausted: stillBlocked(feature, last) && round >= limit };
66
+ const records = feature.reviews.records.filter((r) => r.step === step);
67
+ const last = records.at(-1) ?? null;
68
+ const extra = extraRounds(feature, step);
69
+ const limit = roundLimit(config) + extra;
70
+ const round = last?.round ?? 0;
71
+ return { last, round, next: nextRound(feature, step), limit, extra, exhausted: stillBlocked(feature, last) && round >= limit };
80
72
  }
81
-
82
73
  /**
83
74
  * Rounds the user granted beyond the limit in the current correction loop of `step`
84
75
  * (`agjan review extend`, design 7.4): each grant adds one round. A new loop starts at
85
76
  * round 1 with the configured limit again.
86
77
  */
87
78
  export function extraRounds(feature, step) {
88
- const loopStart = feature.reviews.records.filter((r) => r.step === step && r.round === 1).at(-1)?.at_utc;
89
- if (!loopStart) return 0;
90
- return readLog(feature.dir).filter((e) => e.event === 'round-granted' && e.step === step && e.at_utc >= loopStart).length;
79
+ const loopStart = feature.reviews.records.filter((r) => r.step === step && r.round === 1).at(-1)?.at_utc;
80
+ if (!loopStart)
81
+ return 0;
82
+ return readLog(feature.dir).filter((e) => e.event === 'round-granted' && e.step === step && e.at_utc >= loopStart).length;
91
83
  }
package/dist/review.js ADDED
@@ -0,0 +1,435 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readlinkSync, writeFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { stringify as toYaml } from 'yaml';
5
+ import { git, changedFiles, mergeBase, resolveBase } from './git.js';
6
+ import { resolveArea } from './config.js';
7
+ import { sha256 } from './hash.js';
8
+ import { readJson, writeJson } from './json-file.js';
9
+ import { APPROVALS_FILE, FEATURES_DIR, REVIEWS_FILE, loadFeature } from './feature.js';
10
+ import { acTestFiles, repoFiles } from './tests-map.js';
11
+ import { fixRules } from './fix.js';
12
+ import { watchedHashes } from './baseline.js';
13
+ import { acResults, loadResults, resultLabel } from './test-results.js';
14
+ import { LOG_FILE, appendLog } from './log.js';
15
+ import { AgjanError } from './errors.js';
16
+ import { nextRound } from './review-policy.js';
17
+ import { designProblems, documentProblems } from './validate.js';
18
+ export const REVIEW_MD = 'review.md';
19
+ const CONTEXT_DIR = '.agjan/review-contexts';
20
+ /** Limit for diffs inside a review context, so a huge change cannot flood the reviewer. */
21
+ const MAX_DIFF_BYTES = 200_000;
22
+ const SEVERITIES = ['blocker', 'major', 'minor'];
23
+ const VERDICTS = ['pass', 'pass-with-notes', 'blocked'];
24
+ /** The files of a unit that agjan writes itself (records): outside every review's tree hash. */
25
+ export function scriptOwned(slug) {
26
+ 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
+ }
28
+ /**
29
+ * What a changed path holds now: the file's bytes, a symbolic link's target, or null when
30
+ * it is deleted. A folder (an untracked link to one, a nested repository) is never read.
31
+ */
32
+ function currentContent(path) {
33
+ let stat;
34
+ try {
35
+ stat = lstatSync(path);
36
+ }
37
+ catch {
38
+ return null;
39
+ }
40
+ if (stat.isSymbolicLink())
41
+ return Buffer.from(`symbolic link to ${readlinkSync(path)}`);
42
+ if (!stat.isFile())
43
+ return Buffer.from(stat.isDirectory() ? '(folder)' : '(not a regular file)');
44
+ return readFileSync(path);
45
+ }
46
+ /**
47
+ * Hash of the change as it stands: every file changed relative to the merge-base
48
+ * (committed, staged, unstaged, untracked) with its current content, except the
49
+ * feature's script-owned files. Any write to the working tree changes it.
50
+ */
51
+ export function treeHash(root, config, slug) {
52
+ const skip = scriptOwned(slug);
53
+ const hash = createHash('sha256');
54
+ for (const file of changedFiles(root, resolveBase(root, config.git?.base))) {
55
+ if (skip.has(file) || file.startsWith('.agjan/'))
56
+ continue;
57
+ const content = currentContent(join(root, file));
58
+ hash.update(file).update('\0');
59
+ hash.update(content ? createHash('sha256').update(content).digest('hex') : 'deleted').update('\0');
60
+ }
61
+ return `sha256:${hash.digest('hex')}`;
62
+ }
63
+ /**
64
+ * Parses a review step. Features: spec, design, design:light, verify, build:<area>,
65
+ * build:<task>. A fix has only the step fix, a map run only map.
66
+ */
67
+ export function parseStep(step, feature, config) {
68
+ if (feature.kind === 'fix' || feature.kind === 'map') {
69
+ if (step !== feature.kind)
70
+ throw new AgjanError(`a ${feature.kind} record has only the review step '${feature.kind}'`);
71
+ return { step, kind: step };
72
+ }
73
+ if (step === 'fix' || step === 'map')
74
+ throw new AgjanError(`'${step}' reviews belong to a ${step} record, not to a feature`);
75
+ if (['spec', 'design', 'design:light', 'verify'].includes(step))
76
+ return { step, kind: step };
77
+ const match = /^build:(.+)$/.exec(step ?? '');
78
+ if (!match)
79
+ throw new AgjanError(`unknown review step '${step}'; use spec, design, design:light, build:<area>, build:<task> or verify`);
80
+ const tasks = feature.tasks?.parsed.tasks ?? [];
81
+ const byTask = tasks.filter((t) => t.id === match[1]);
82
+ if (byTask.length)
83
+ return { step, kind: 'build', tasks: byTask };
84
+ const area = resolveArea(config, match[1]);
85
+ const byArea = area ? tasks.filter((t) => resolveArea(config, t.area)?.id === area.id) : [];
86
+ if (byArea.length === 0)
87
+ throw new AgjanError(`'${match[1]}' is neither a task id nor an area with tasks in tasks.md`);
88
+ return { step: `build:${area.name}`, kind: 'build', tasks: byArea };
89
+ }
90
+ function capped(text) {
91
+ if (Buffer.byteLength(text) <= MAX_DIFF_BYTES)
92
+ return text;
93
+ return `${text.slice(0, MAX_DIFF_BYTES)}\n\n[diff truncated at ${MAX_DIFF_BYTES} bytes; read the files directly]\n`;
94
+ }
95
+ /** Diff of the given path patterns against the merge-base, untracked files included. */
96
+ function diffOf(root, base, patterns) {
97
+ if (patterns.length === 0)
98
+ return '(no changes)\n';
99
+ const from = mergeBase(root, base) ?? 'HEAD';
100
+ const specs = patterns.map((p) => `:(glob)${p.endsWith('/') ? `${p}**` : p}`);
101
+ let out = git(root, ['diff', '--no-color', '--no-ext-diff', from, '--', ...specs], { allowFail: true }) ?? '';
102
+ const untracked = git(root, ['ls-files', '--others', '--exclude-standard', '--', ...specs]).split('\n').filter(Boolean);
103
+ for (const file of untracked) {
104
+ out += `\n--- new file: ${file}\n${currentContent(join(root, file))?.toString('utf8') ?? '(deleted)'}`;
105
+ }
106
+ return capped(out || '(no changes)\n');
107
+ }
108
+ function section(title, body) {
109
+ return `## ${title}\n\n${body.trimEnd()}\n`;
110
+ }
111
+ function fence(text, lang = '') {
112
+ const ticks = text.includes('```') ? '````' : '```';
113
+ return `${ticks}${lang}\n${text.trimEnd()}\n${ticks}`;
114
+ }
115
+ function acsText(feature, ids) {
116
+ const spec = feature.spec;
117
+ return spec.parsed.acs
118
+ .filter((ac) => !ids || ids.has(ac.id))
119
+ .map((ac) => {
120
+ const lines = spec.text.split(/\r?\n/);
121
+ const start = ac.line - 1;
122
+ let end = lines.findIndex((l, i) => i > start && /^#{2,3} /.test(l));
123
+ if (end === -1)
124
+ end = lines.length;
125
+ return lines.slice(start, end).join('\n').trim();
126
+ })
127
+ .join('\n\n');
128
+ }
129
+ function reviewHistory(feature) {
130
+ if (feature.reviews.records.length === 0)
131
+ return '(none)';
132
+ return feature.reviews.records
133
+ .map((r) => `- ${r.id} ${r.step} round ${r.round}: ${r.verdict}, ${r.findings?.length ?? 0} finding(s)`)
134
+ .join('\n');
135
+ }
136
+ function openFindings(feature, steps) {
137
+ const open = feature.findings.filter((f) => f.status === 'open' && (!steps || steps.includes(f.step)));
138
+ if (open.length === 0)
139
+ return '(none)';
140
+ return open.map((f) => `- ${f.id} [${f.severity}] ${f.file ? `${f.file}${f.line ? `:${f.line}` : ''} ` : ''}${f.issue}`).join('\n');
141
+ }
142
+ const CHECKLISTS = {
143
+ spec: 'No unrequested technical decisions. Technical questions listed under Open technical questions are expected and are not decisions: never ask to remove that section; Design answers them. Every AC testable and complete; an AC without a Verification line is automated, which is the default and not a finding; flag only ACs that cannot be tested automatically but are not marked manual. Non-functional and authorization requirements considered. Scope consistent.',
144
+ 'design:light': 'The spec checks, plus: light mode is justified (nothing new: no new service, application, BTP service, authorization or deployment change). Tasks: paths plausible and including where the tests of their ACs go, every AC covered. In a Fiori elements app, creating or editing records needs a draft-enabled entity.',
145
+ 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.',
146
+ 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
+ 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
+ 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.',
150
+ };
151
+ /**
152
+ * What the given tasks may change (design 6.5), as `agjan check` judges it: the task paths,
153
+ * the implicit paths of their areas (lockfiles, i18n, fixtures, package.json), and approved
154
+ * amendments. The reviewer sees the same scope as the script.
155
+ */
156
+ function scopeOf(config, feature, tasks) {
157
+ const taskIds = new Set(tasks.map((t) => t.id));
158
+ const own = tasks.flatMap((t) => t.paths);
159
+ const areas = [...new Set(tasks.map((t) => resolveArea(config, t.area ?? '')?.name).filter((a) => Boolean(a)))];
160
+ const implicit = [...new Set(areas.flatMap((a) => config.scope.implicit[a] ?? []))];
161
+ const amended = feature.amendments.filter((a) => a.status === 'approved' && taskIds.has(a.task)).flatMap((a) => a.paths);
162
+ return { own, implicit, amended, all: [...new Set([...own, ...implicit, ...amended])] };
163
+ }
164
+ function scopeText(scope) {
165
+ const list = (items) => (items.length ? items.map((p) => `\`${p}\``).join(', ') : '(none)');
166
+ return [
167
+ `- Task paths: ${list(scope.own)}`,
168
+ `- Implicit for the tasks' areas: ${list(scope.implicit)}`,
169
+ `- Approved amendments: ${list(scope.amended)}`,
170
+ ].join('\n');
171
+ }
172
+ /** A document's repository path, as findings should cite it. */
173
+ function docPath(feature, name) {
174
+ return `${FEATURES_DIR}/${feature.slug}/${name}`;
175
+ }
176
+ /** Builds the reviewer's input for a step: the only material the reviewer should read. */
177
+ export function buildContextText(root, config, feature, parsed) {
178
+ const base = resolveBase(root, config.git?.base);
179
+ const parts = [
180
+ `# Review context: ${feature.slug} (${feature.key}), step ${parsed.step}`,
181
+ '',
182
+ `The unit's folder is \`${FEATURES_DIR}/${feature.slug}/\`. Cite files with the repository paths used below.`,
183
+ '',
184
+ ];
185
+ parts.push(section('Checklist', CHECKLISTS[parsed.kind]));
186
+ const baseline = join(root, FEATURES_DIR, 'project.md');
187
+ const baselineText = existsSync(baseline) ? readFileSync(baseline, 'utf8') : null;
188
+ if (parsed.kind === 'fix') {
189
+ const description = readJson(join(feature.dir, 'fix.json'))?.what ?? '(no description)';
190
+ const rules = fixRules(root, config);
191
+ const files = rules.files.map((f) => `- ${f.path} +${f.added}/-${f.deleted}${f.isNew ? ' (new)' : ''}`).join('\n') || '(none)';
192
+ const verdict = rules.problems.length ? rules.problems.map((p) => `- ${p}`).join('\n') : 'within the limits';
193
+ parts.push(section('Fix description', description));
194
+ parts.push(section('Fast-path rules', `${rules.total} changed lines (limit ${rules.limits.max_total}). ${verdict}\n\n${files}`));
195
+ parts.push(section('Diff', fence(diffOf(root, base, rules.files.map((f) => f.path)), 'diff')));
196
+ }
197
+ else if (parsed.kind === 'map') {
198
+ if (!baselineText)
199
+ throw new AgjanError(`${FEATURES_DIR}/project.md does not exist; write it first`);
200
+ const watched = Object.keys(watchedHashes(root, config));
201
+ parts.push(section('Watched files (models, services, apps, deployment)', watched.map((f) => `- ${f}`).join('\n') || '(none)'));
202
+ const files = repoFiles(root).filter((f) => !f.startsWith(`${FEATURES_DIR}/`));
203
+ parts.push(section('Repository files', `${files.slice(0, 300).map((f) => `- ${f}`).join('\n')}${files.length > 300 ? `\n- … ${files.length - 300} more` : ''}`));
204
+ }
205
+ else if (!feature.spec) {
206
+ throw new AgjanError('spec.md does not exist');
207
+ }
208
+ else if (parsed.kind === 'spec') {
209
+ parts.push(section(docPath(feature, 'spec.md'), fence(feature.spec.text, 'md')));
210
+ }
211
+ else if (parsed.kind === 'design' || parsed.kind === 'design:light') {
212
+ if (!feature.design || !feature.tasks)
213
+ throw new AgjanError('design.md and tasks.md must exist for a design review');
214
+ parts.push(section(docPath(feature, 'spec.md'), fence(feature.spec.text, 'md')));
215
+ parts.push(section(docPath(feature, 'design.md'), fence(feature.design.text, 'md')));
216
+ parts.push(section(docPath(feature, 'tasks.md'), fence(feature.tasks.text, 'md')));
217
+ }
218
+ else if (parsed.kind === 'build') {
219
+ const tasks = parsed.tasks ?? [];
220
+ const ids = new Set(tasks.flatMap((t) => t.covers));
221
+ const scope = scopeOf(config, feature, tasks);
222
+ parts.push(section('Tasks', fence(toYaml(tasks.map(({ verify, ...t }) => (verify ? { ...t, verify } : t))), 'yaml')));
223
+ parts.push(section('Allowed paths (scope, enforced by agjan check)', scopeText(scope)));
224
+ parts.push(section('Acceptance criteria covered', acsText(feature, ids)));
225
+ parts.push(section('Diff of the allowed paths', fence(diffOf(root, base, scope.all), 'diff')));
226
+ }
227
+ else if (parsed.kind === 'verify') {
228
+ if (!feature.design || !feature.tasks)
229
+ throw new AgjanError('design.md and tasks.md must exist for the verify review');
230
+ const areaNames = [...new Set(feature.tasks.parsed.tasks.map((t) => resolveArea(config, t.area)?.name).filter((a) => Boolean(a)))];
231
+ const tests = acTestFiles(root, config, areaNames, feature.key);
232
+ const loaded = loadResults(root, config, areaNames);
233
+ const results = loaded.files.length ? acResults(loaded, feature.key) : null;
234
+ const coverage = feature.spec.parsed.acs
235
+ .map((ac) => `| ${ac.id} | ${ac.verification} | ${[...(tests.get(ac.id) ?? [])].join(', ') || '-'} | ${results ? resultLabel(results.get(ac.id)) : 'not recorded'} |`)
236
+ .join('\n');
237
+ const unrecorded = results
238
+ ? ''
239
+ : '\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.';
240
+ const changed = changedFiles(root, base).filter((f) => !scriptOwned(feature.slug).has(f) && !f.startsWith('.agjan/'));
241
+ parts.push(section('Acceptance criteria', acsText(feature)));
242
+ parts.push(section('AC coverage (test files mentioning the AC id, and test results)', `| AC | verification | test files | result |\n|---|---|---|---|\n${coverage}${unrecorded}`));
243
+ parts.push(section(docPath(feature, 'design.md'), fence(feature.design.text, 'md')));
244
+ parts.push(section(docPath(feature, 'tasks.md'), fence(feature.tasks.text, 'md')));
245
+ parts.push(section('Allowed paths (scope, enforced by agjan check)', scopeText(scopeOf(config, feature, feature.tasks.parsed.tasks))));
246
+ parts.push(section('Changed files', changed.map((f) => `- ${f}`).join('\n') || '(none)'));
247
+ parts.push(section('Full diff', fence(diffOf(root, base, changed), 'diff')));
248
+ }
249
+ if (baselineText && parsed.kind !== 'build' && parsed.kind !== 'fix')
250
+ parts.push(section('Baseline (docs/agjan/project.md)', fence(baselineText, 'md')));
251
+ parts.push(section('Earlier reviews', reviewHistory(feature)));
252
+ parts.push(section('Open findings', openFindings(feature)));
253
+ parts.push(section('How to record your result', 'Call review_record with this context_id, a verdict (pass, pass-with-notes, blocked), your findings ' +
254
+ '(severity blocker, major or minor; file and line where possible, with the repository paths used in this context; ' +
255
+ 'issue; suggestion; evidence for a claim that an API, annotation or syntax is wrong), and in `resolves` the ids ' +
256
+ 'of open findings that this change has fixed. A blocker finding requires the verdict blocked.'));
257
+ return parts.join('\n');
258
+ }
259
+ /** review_context: builds the context, stores its metadata, returns id and text. */
260
+ /**
261
+ * 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
263
+ * review before (or in parallel with) its edits, and it costs one of the step's rounds.
264
+ */
265
+ function unchangedSinceFindings(feature, step, tree) {
266
+ const last = feature.reviews.records.filter((r) => r.step === step).at(-1);
267
+ if (!last || last.verdict === 'pass' || last.tree_hash !== tree)
268
+ return;
269
+ throw new AgjanError(`nothing changed since ${last.id} (${last.verdict}); address its findings and save the changes before the next round. ` +
270
+ 'A finding that needs no change is accepted by the human (agjan accept), not reviewed again.');
271
+ }
272
+ /**
273
+ * Spec and design reviews need complete documents: the same structural checks the gate
274
+ * runs (sections, areas, every AC covered by a task with a title and paths). A review of
275
+ * an unfinished template only reports that and costs one of the step's rounds.
276
+ */
277
+ function unfinishedDocuments(feature, config, step) {
278
+ if (!['spec', 'design', 'design:light'].includes(step))
279
+ return;
280
+ const problems = [];
281
+ if (!feature.spec)
282
+ problems.push('spec.md does not exist');
283
+ if (step !== 'spec') {
284
+ if (!feature.design)
285
+ problems.push('design.md does not exist');
286
+ if (!feature.tasks)
287
+ problems.push('tasks.md does not exist');
288
+ }
289
+ const names = step === 'spec' ? ['spec.md'] : ['spec.md', 'design.md', 'tasks.md'];
290
+ problems.push(...documentProblems(feature).filter((p) => names.some((n) => p.startsWith(n))));
291
+ if (step !== 'spec')
292
+ problems.push(...designProblems(feature, config));
293
+ if (problems.length === 0)
294
+ return;
295
+ throw new AgjanError(`the documents are not ready for the ${step} review; complete them first:\n${problems.map((p) => ` - ${p}`).join('\n')}`);
296
+ }
297
+ export function createReviewContext(root, config, { feature: slug, step }) {
298
+ const feature = loadFeature(root, slug);
299
+ const parsed = parseStep(step, feature, config);
300
+ unfinishedDocuments(feature, config, parsed.step);
301
+ const tree = treeHash(root, config, feature.slug);
302
+ unchangedSinceFindings(feature, parsed.step, tree);
303
+ const text = buildContextText(root, config, feature, parsed);
304
+ const id = `${feature.key}-C${randomBytes(4).toString('hex')}`;
305
+ const base = resolveBase(root, config.git?.base);
306
+ const meta = {
307
+ id,
308
+ feature: feature.slug,
309
+ step: parsed.step,
310
+ documents: { spec: feature.spec?.hash, design: feature.designHash ?? undefined },
311
+ inputs_hash: sha256(text),
312
+ tree_hash: tree,
313
+ base_commit: mergeBase(root, base),
314
+ head_commit: git(root, ['rev-parse', '--verify', '--quiet', 'HEAD'], { allowFail: true })?.trim() ?? null,
315
+ };
316
+ const dir = join(root, CONTEXT_DIR);
317
+ mkdirSync(dir, { recursive: true });
318
+ writeJson(join(dir, `${id}.json`), meta);
319
+ return { id, text };
320
+ }
321
+ function validFinding(f, i) {
322
+ const where = `findings[${i}]`;
323
+ if (typeof f !== 'object' || f === null)
324
+ return `${where} must be an object`;
325
+ if (!SEVERITIES.includes(f.severity))
326
+ return `${where}.severity must be one of ${SEVERITIES.join(', ')}`;
327
+ if (typeof f.issue !== 'string' || f.issue.trim() === '')
328
+ return `${where}.issue is required`;
329
+ if (f.file !== undefined && (typeof f.file !== 'string' || f.file.includes('\\')))
330
+ return `${where}.file must be a POSIX path`;
331
+ if (f.line !== undefined && !(Number.isInteger(f.line) && f.line > 0))
332
+ return `${where}.line must be a positive integer`;
333
+ if (f.suggestion !== undefined && typeof f.suggestion !== 'string')
334
+ return `${where}.suggestion must be a string`;
335
+ if (f.evidence !== undefined && typeof f.evidence !== 'string')
336
+ return `${where}.evidence must be a string`;
337
+ const extra = Object.keys(f).filter((k) => !['severity', 'file', 'line', 'issue', 'suggestion', 'evidence'].includes(k));
338
+ if (extra.length)
339
+ return `${where} has unknown field(s): ${extra.join(', ')}`;
340
+ return null;
341
+ }
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 }) {
347
+ if (typeof contextId !== 'string' || !/^[A-Z][A-Z0-9]{1,5}-C[0-9a-f]{8}$/.test(contextId))
348
+ throw new AgjanError('context_id is missing or malformed');
349
+ const metaFile = join(root, CONTEXT_DIR, `${contextId}.json`);
350
+ const meta = readJson(metaFile);
351
+ if (!meta)
352
+ throw new AgjanError(`unknown context ${contextId}; call review_context first`);
353
+ if (meta.recorded)
354
+ throw new AgjanError(`context ${contextId} was already used for ${meta.recorded}; call review_context again`);
355
+ if (typeof verdict !== 'string' || !VERDICTS.includes(verdict))
356
+ throw new AgjanError(`verdict must be one of ${VERDICTS.join(', ')}`);
357
+ if (!Array.isArray(findings) || findings.length > 50)
358
+ throw new AgjanError('findings must be a list of at most 50 items');
359
+ const problems = findings.map(validFinding).filter(Boolean);
360
+ if (problems.length)
361
+ throw new AgjanError(problems.join('; '));
362
+ const hasBlocker = findings.some((f) => f.severity === 'blocker');
363
+ if (hasBlocker && verdict !== 'blocked')
364
+ throw new AgjanError('a blocker finding requires the verdict blocked');
365
+ if (verdict === 'blocked' && !hasBlocker)
366
+ throw new AgjanError('the verdict blocked requires at least one blocker finding');
367
+ if (verdict === 'pass' && findings.length)
368
+ throw new AgjanError('the verdict pass allows no findings; use pass-with-notes');
369
+ const feature = loadFeature(root, meta.feature);
370
+ if (!Array.isArray(resolves) || resolves.some((id) => typeof id !== 'string'))
371
+ throw new AgjanError('resolves must be a list of finding ids');
372
+ const open = new Set(feature.findings.filter((f) => f.status === 'open').map((f) => f.id));
373
+ const unknown = resolves.filter((id) => !open.has(id));
374
+ if (unknown.length)
375
+ 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
+ }
380
+ const records = feature.reviews.records;
381
+ let next = feature.findings.length;
382
+ const record = {
383
+ id: `${feature.key}-R${records.length + 1}`,
384
+ step: meta.step,
385
+ round: nextRound(feature, meta.step),
386
+ at_utc: now(),
387
+ reviewer: { host, model: null, isolation },
388
+ context: contextId,
389
+ documents: meta.documents,
390
+ inputs_hash: meta.inputs_hash,
391
+ tree_hash: meta.tree_hash,
392
+ base_commit: meta.base_commit,
393
+ head_commit: meta.head_commit,
394
+ verdict: verdict,
395
+ resolves: resolves,
396
+ findings: findings.map((f) => ({ id: `${feature.key}-F${++next}`, ...f })),
397
+ };
398
+ records.push(record);
399
+ writeJson(join(feature.dir, REVIEWS_FILE), { schema: 1, records });
400
+ writeFileSync(join(feature.dir, REVIEW_MD), renderReviewMd(loadFeature(root, feature.slug)));
401
+ writeJson(metaFile, { ...meta, recorded: record.id });
402
+ appendLog(feature.dir, record.at_utc, 'review-recorded', {
403
+ review: record.id,
404
+ step: record.step,
405
+ round: record.round,
406
+ verdict: record.verdict,
407
+ findings: record.findings.length,
408
+ blockers: record.findings.filter((f) => f.severity === 'blocker').length,
409
+ isolation,
410
+ });
411
+ return record;
412
+ }
413
+ /** Renders review.md from reviews.json (design 8.5). Generated; never edited by hand. */
414
+ export function renderReviewMd(feature) {
415
+ const out = [`# Reviews: ${feature.slug} (${feature.key})`, '', '<!-- Generated by agjan from reviews.json. Do not edit. -->', ''];
416
+ const status = new Map(feature.findings.map((f) => [f.id, f.status]));
417
+ for (const r of feature.reviews.records) {
418
+ out.push(`## ${r.id} ${r.step}, round ${r.round}: ${r.verdict}`, '');
419
+ out.push(`${r.at_utc} · reviewer: ${r.reviewer?.host ?? 'unknown'}, isolation ${r.reviewer?.isolation ?? 'unknown'}`, '');
420
+ if (r.resolves?.length)
421
+ out.push(`Resolves: ${r.resolves.join(', ')}`, '');
422
+ for (const f of r.findings ?? []) {
423
+ const where = f.file ? ` ${f.file}${f.line ? `:${f.line}` : ''}` : '';
424
+ out.push(`- **${f.id}** [${f.severity}]${where} (${status.get(f.id)})`);
425
+ out.push(` - Issue: ${f.issue}`);
426
+ if (f.suggestion)
427
+ out.push(` - Suggestion: ${f.suggestion}`);
428
+ if (f.evidence)
429
+ out.push(` - Evidence: ${f.evidence}`);
430
+ }
431
+ if (r.findings?.length)
432
+ out.push('');
433
+ }
434
+ return `${out.join('\n').trimEnd()}\n`;
435
+ }
package/dist/scope.js ADDED
@@ -0,0 +1,30 @@
1
+ import picomatch from 'picomatch';
2
+ import { resolveArea } from './config.js';
3
+ /** A path ending in '/' means the whole folder. */
4
+ function toGlob(pattern) {
5
+ return pattern.endsWith('/') ? `${pattern}**` : pattern;
6
+ }
7
+ /** Case-sensitive matcher for POSIX repository paths, the same on every OS (design 4.5). */
8
+ export function matcher(patterns) {
9
+ if (patterns.length === 0)
10
+ return () => false;
11
+ return picomatch(patterns.map(toGlob), { dot: true, nocase: false, windows: false });
12
+ }
13
+ /**
14
+ * The patterns a feature in Build may change: its task paths, the implicit allowlist of
15
+ * the task areas, and approved amendments (design 6.5).
16
+ */
17
+ export function allowedPatterns(feature, config) {
18
+ const patterns = [];
19
+ for (const task of feature.tasks?.parsed.tasks ?? []) {
20
+ patterns.push(...task.paths);
21
+ const area = resolveArea(config, task.area ?? '');
22
+ if (area)
23
+ patterns.push(...(config.scope.implicit[area.name] ?? []));
24
+ }
25
+ for (const amendment of feature.amendments) {
26
+ if (amendment.status === 'approved')
27
+ patterns.push(...amendment.paths);
28
+ }
29
+ return patterns;
30
+ }