agjan 0.0.11 → 0.0.13

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 (114) hide show
  1. package/README.md +2 -2
  2. package/bin/agjan.mjs +9 -2
  3. package/dist/adapters/claude-code.js +136 -0
  4. package/dist/adapters/copilot.js +110 -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 +170 -0
  9. package/dist/commands/branch.js +71 -0
  10. package/dist/commands/check.js +424 -0
  11. package/dist/commands/fix.js +122 -0
  12. package/dist/commands/gates.js +475 -0
  13. package/dist/commands/lint.js +76 -0
  14. package/dist/commands/log.js +74 -0
  15. package/dist/commands/map.js +47 -0
  16. package/dist/commands/models.js +90 -0
  17. package/dist/commands/new.js +65 -0
  18. package/dist/commands/pr-summary.js +176 -0
  19. package/dist/commands/progress.js +42 -0
  20. package/dist/commands/report.js +105 -0
  21. package/dist/commands/review.js +149 -0
  22. package/dist/commands/setup.js +393 -0
  23. package/dist/commands/status.js +323 -0
  24. package/dist/commands/ui-test.js +39 -0
  25. package/dist/config.js +114 -0
  26. package/dist/context.js +56 -0
  27. package/dist/copilot-mcp.js +56 -0
  28. package/dist/documents.js +207 -0
  29. package/dist/errors.js +15 -0
  30. package/dist/feature.js +221 -0
  31. package/dist/fix.js +117 -0
  32. package/dist/git.js +88 -0
  33. package/{src/hash.mjs → dist/hash.js} +11 -14
  34. package/dist/hook.js +47 -0
  35. package/dist/json-file.js +26 -0
  36. package/dist/log.js +50 -0
  37. package/dist/managed.js +182 -0
  38. package/dist/mcp-config.js +76 -0
  39. package/dist/mcp.js +187 -0
  40. package/dist/plan.js +40 -0
  41. package/dist/progress-view.js +494 -0
  42. package/dist/progress.js +106 -0
  43. package/dist/qa.js +77 -0
  44. package/dist/review-policy.js +84 -0
  45. package/dist/review.js +534 -0
  46. package/dist/scope.js +34 -0
  47. package/dist/terminal.js +127 -0
  48. package/dist/test-results.js +101 -0
  49. package/dist/tests-map.js +29 -0
  50. package/dist/types.js +5 -0
  51. package/dist/ui.js +136 -0
  52. package/dist/usage.js +116 -0
  53. package/dist/validate.js +46 -0
  54. package/docs/guide.md +80 -40
  55. package/kit/hooks/guard.mjs +48 -119
  56. package/kit/skills/agjan-build/SKILL.md +6 -2
  57. package/kit/skills/agjan-design/SKILL.md +9 -2
  58. package/kit/skills/agjan-fix/SKILL.md +8 -16
  59. package/kit/skills/agjan-map/SKILL.md +8 -16
  60. package/kit/skills/agjan-spec/SKILL.md +24 -17
  61. package/kit/skills/agjan-verify/SKILL.md +50 -16
  62. package/kit/skills/qa-tester/SKILL.md +74 -0
  63. package/kit/templates/agents-block.md +3 -3
  64. package/package.json +11 -3
  65. package/schemas/approvals.schema.json +23 -2
  66. package/schemas/config.schema.json +3 -7
  67. package/schemas/log.schema.json +1 -1
  68. package/schemas/reviews.schema.json +3 -1
  69. package/src/adapters/claude-code.mjs +0 -121
  70. package/src/adapters/copilot.mjs +0 -89
  71. package/src/baseline.mjs +0 -66
  72. package/src/browser.mjs +0 -49
  73. package/src/cli.mjs +0 -165
  74. package/src/commands/branch.mjs +0 -95
  75. package/src/commands/check.mjs +0 -376
  76. package/src/commands/fix.mjs +0 -116
  77. package/src/commands/gates.mjs +0 -267
  78. package/src/commands/lint.mjs +0 -74
  79. package/src/commands/log.mjs +0 -60
  80. package/src/commands/map.mjs +0 -47
  81. package/src/commands/new.mjs +0 -53
  82. package/src/commands/pr-summary.mjs +0 -137
  83. package/src/commands/progress.mjs +0 -40
  84. package/src/commands/report.mjs +0 -115
  85. package/src/commands/review.mjs +0 -141
  86. package/src/commands/setup.mjs +0 -393
  87. package/src/commands/status.mjs +0 -250
  88. package/src/commands/ui-test.mjs +0 -38
  89. package/src/config.mjs +0 -122
  90. package/src/context.mjs +0 -67
  91. package/src/copilot-mcp.mjs +0 -56
  92. package/src/documents.mjs +0 -188
  93. package/src/errors.mjs +0 -16
  94. package/src/feature.mjs +0 -225
  95. package/src/fix.mjs +0 -108
  96. package/src/git.mjs +0 -83
  97. package/src/hook.mjs +0 -48
  98. package/src/json-file.mjs +0 -24
  99. package/src/log.mjs +0 -51
  100. package/src/managed.mjs +0 -178
  101. package/src/mcp-config.mjs +0 -83
  102. package/src/mcp.mjs +0 -147
  103. package/src/plan.mjs +0 -45
  104. package/src/progress-view.mjs +0 -466
  105. package/src/progress.mjs +0 -85
  106. package/src/review-policy.mjs +0 -91
  107. package/src/review.mjs +0 -416
  108. package/src/scope.mjs +0 -30
  109. package/src/terminal.mjs +0 -118
  110. package/src/test-results.mjs +0 -111
  111. package/src/tests-map.mjs +0 -29
  112. package/src/ui.mjs +0 -136
  113. package/src/usage.mjs +0 -118
  114. package/src/validate.mjs +0 -41
package/src/review.mjs DELETED
@@ -1,416 +0,0 @@
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.mjs';
6
- import { resolveArea } from './config.mjs';
7
- import { sha256 } from './hash.mjs';
8
- import { readJson, writeJson } from './json-file.mjs';
9
- import { APPROVALS_FILE, FEATURES_DIR, REVIEWS_FILE, loadFeature } from './feature.mjs';
10
- import { acTestFiles, repoFiles } from './tests-map.mjs';
11
- import { fixRules } from './fix.mjs';
12
- import { watchedHashes } from './baseline.mjs';
13
- import { acResults, loadResults, resultLabel } from './test-results.mjs';
14
- import { LOG_FILE, appendLog } from './log.mjs';
15
- import { AgjanError } from './errors.mjs';
16
- import { nextRound } from './review-policy.mjs';
17
- import { designProblems, documentProblems } from './validate.mjs';
18
-
19
- export const REVIEW_MD = 'review.md';
20
- const CONTEXT_DIR = '.agjan/review-contexts';
21
- /** Limit for diffs inside a review context, so a huge change cannot flood the reviewer. */
22
- const MAX_DIFF_BYTES = 200_000;
23
- const SEVERITIES = ['blocker', 'major', 'minor'];
24
- const VERDICTS = ['pass', 'pass-with-notes', 'blocked'];
25
-
26
- /** Script-owned files of a feature: they change during a review by design. */
27
- 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}`));
29
- }
30
-
31
- /**
32
- * What a changed path holds now: the file's bytes, a symbolic link's target, or null when
33
- * it is deleted. A folder (an untracked link to one, a nested repository) is never read.
34
- */
35
- function currentContent(path) {
36
- let stat;
37
- try {
38
- stat = lstatSync(path);
39
- } catch {
40
- return null;
41
- }
42
- if (stat.isSymbolicLink()) return Buffer.from(`symbolic link to ${readlinkSync(path)}`);
43
- if (!stat.isFile()) return Buffer.from(stat.isDirectory() ? '(folder)' : '(not a regular file)');
44
- return readFileSync(path);
45
- }
46
-
47
- /**
48
- * Hash of the change as it stands: every file changed relative to the merge-base
49
- * (committed, staged, unstaged, untracked) with its current content, except the
50
- * feature's script-owned files. Any write to the working tree changes it.
51
- */
52
- export function treeHash(root, config, slug) {
53
- const skip = scriptOwned(slug);
54
- const hash = createHash('sha256');
55
- for (const file of changedFiles(root, resolveBase(root, config.git?.base))) {
56
- if (skip.has(file) || file.startsWith('.agjan/')) 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
- /**
65
- * Parses a review step. Features: spec, design, design:light, verify, build:<area>,
66
- * build:<task>. A fix has only the step fix, a map run only map.
67
- */
68
- export function parseStep(step, feature, config) {
69
- if (feature.kind === 'fix' || feature.kind === 'map') {
70
- if (step !== feature.kind) 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') throw new AgjanError(`'${step}' reviews belong to a ${step} record, not to a feature`);
74
- if (['spec', 'design', 'design:light', 'verify'].includes(step)) return { step, kind: step };
75
- const match = /^build:(.+)$/.exec(step ?? '');
76
- if (!match) throw new AgjanError(`unknown review step '${step}'; use spec, design, design:light, build:<area>, build:<task> or verify`);
77
- const tasks = feature.tasks?.parsed.tasks ?? [];
78
- const byTask = tasks.filter((t) => t.id === match[1]);
79
- if (byTask.length) return { step, kind: 'build', tasks: byTask };
80
- const area = resolveArea(config, match[1]);
81
- const byArea = area ? tasks.filter((t) => resolveArea(config, t.area)?.id === area.id) : [];
82
- if (byArea.length === 0) throw new AgjanError(`'${match[1]}' is neither a task id nor an area with tasks in tasks.md`);
83
- return { step: `build:${area.name}`, kind: 'build', tasks: byArea };
84
- }
85
-
86
- function capped(text) {
87
- if (Buffer.byteLength(text) <= MAX_DIFF_BYTES) return text;
88
- return `${text.slice(0, MAX_DIFF_BYTES)}\n\n[diff truncated at ${MAX_DIFF_BYTES} bytes; read the files directly]\n`;
89
- }
90
-
91
- /** Diff of the given path patterns against the merge-base, untracked files included. */
92
- function diffOf(root, base, patterns) {
93
- if (patterns.length === 0) return '(no changes)\n';
94
- const from = mergeBase(root, base) ?? 'HEAD';
95
- const specs = patterns.map((p) => `:(glob)${p.endsWith('/') ? `${p}**` : p}`);
96
- let out = git(root, ['diff', '--no-color', '--no-ext-diff', from, '--', ...specs], { allowFail: true }) ?? '';
97
- const untracked = git(root, ['ls-files', '--others', '--exclude-standard', '--', ...specs]).split('\n').filter(Boolean);
98
- for (const file of untracked) {
99
- out += `\n--- new file: ${file}\n${currentContent(join(root, file))?.toString('utf8') ?? '(deleted)'}`;
100
- }
101
- return capped(out || '(no changes)\n');
102
- }
103
-
104
- function section(title, body) {
105
- return `## ${title}\n\n${body.trimEnd()}\n`;
106
- }
107
-
108
- function fence(text, lang = '') {
109
- const ticks = text.includes('```') ? '````' : '```';
110
- return `${ticks}${lang}\n${text.trimEnd()}\n${ticks}`;
111
- }
112
-
113
- function acsText(feature, ids) {
114
- return feature.spec.parsed.acs
115
- .filter((ac) => !ids || ids.has(ac.id))
116
- .map((ac) => {
117
- const lines = feature.spec.text.split(/\r?\n/);
118
- const start = ac.line - 1;
119
- let end = lines.findIndex((l, i) => i > start && /^#{2,3} /.test(l));
120
- if (end === -1) end = lines.length;
121
- return lines.slice(start, end).join('\n').trim();
122
- })
123
- .join('\n\n');
124
- }
125
-
126
- function reviewHistory(feature) {
127
- if (feature.reviews.records.length === 0) return '(none)';
128
- return feature.reviews.records
129
- .map((r) => `- ${r.id} ${r.step} round ${r.round}: ${r.verdict}, ${r.findings?.length ?? 0} finding(s)`)
130
- .join('\n');
131
- }
132
-
133
- function openFindings(feature, steps) {
134
- const open = feature.findings.filter((f) => f.status === 'open' && (!steps || steps.includes(f.step)));
135
- if (open.length === 0) return '(none)';
136
- return open.map((f) => `- ${f.id} [${f.severity}] ${f.file ? `${f.file}${f.line ? `:${f.line}` : ''} ` : ''}${f.issue}`).join('\n');
137
- }
138
-
139
- const CHECKLISTS = {
140
- 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.',
141
- '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.',
142
- 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.',
143
- 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.',
144
- 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).',
145
- 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.',
146
- 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.',
147
- };
148
-
149
- /**
150
- * What the given tasks may change (design 6.5), as `agjan check` judges it: the task paths,
151
- * the implicit paths of their areas (lockfiles, i18n, fixtures, package.json), and approved
152
- * amendments. The reviewer sees the same scope as the script.
153
- */
154
- function scopeOf(config, feature, tasks) {
155
- const taskIds = new Set(tasks.map((t) => t.id));
156
- const own = tasks.flatMap((t) => t.paths);
157
- const areas = [...new Set(tasks.map((t) => resolveArea(config, t.area ?? '')?.name).filter(Boolean))];
158
- const implicit = [...new Set(areas.flatMap((a) => config.scope.implicit[a] ?? []))];
159
- const amended = feature.amendments.filter((a) => a.status === 'approved' && taskIds.has(a.task)).flatMap((a) => a.paths);
160
- return { own, implicit, amended, all: [...new Set([...own, ...implicit, ...amended])] };
161
- }
162
-
163
- function scopeText(scope) {
164
- const list = (items) => (items.length ? items.map((p) => `\`${p}\``).join(', ') : '(none)');
165
- return [
166
- `- Task paths: ${list(scope.own)}`,
167
- `- Implicit for the tasks' areas: ${list(scope.implicit)}`,
168
- `- Approved amendments: ${list(scope.amended)}`,
169
- ].join('\n');
170
- }
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
-
177
- /** Builds the reviewer's input for a step: the only material the reviewer should read. */
178
- export function buildContextText(root, config, feature, parsed) {
179
- const base = resolveBase(root, config.git?.base);
180
- const parts = [
181
- `# Review context: ${feature.slug} (${feature.key}), step ${parsed.step}`,
182
- '',
183
- `The unit's folder is \`${FEATURES_DIR}/${feature.slug}/\`. Cite files with the repository paths used below.`,
184
- '',
185
- ];
186
- parts.push(section('Checklist', CHECKLISTS[parsed.kind]));
187
- const baseline = join(root, FEATURES_DIR, 'project.md');
188
- const baselineText = existsSync(baseline) ? readFileSync(baseline, 'utf8') : null;
189
-
190
- if (parsed.kind === 'fix') {
191
- const description = readJson(join(feature.dir, 'fix.json'))?.what ?? '(no description)';
192
- const rules = fixRules(root, config);
193
- const files = rules.files.map((f) => `- ${f.path} +${f.added}/-${f.deleted}${f.isNew ? ' (new)' : ''}`).join('\n') || '(none)';
194
- const verdict = rules.problems.length ? rules.problems.map((p) => `- ${p}`).join('\n') : 'within the limits';
195
- parts.push(section('Fix description', description));
196
- 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')));
198
- } else if (parsed.kind === 'map') {
199
- if (!baselineText) 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
- } else if (!feature.spec) {
205
- throw new AgjanError('spec.md does not exist');
206
- } else if (parsed.kind === 'spec') {
207
- parts.push(section(docPath(feature, 'spec.md'), fence(feature.spec.text, 'md')));
208
- } else if (parsed.kind === 'design' || parsed.kind === 'design:light') {
209
- if (!feature.design || !feature.tasks) throw new AgjanError('design.md and tasks.md must exist for a design review');
210
- parts.push(section(docPath(feature, 'spec.md'), fence(feature.spec.text, 'md')));
211
- parts.push(section(docPath(feature, 'design.md'), fence(feature.design.text, 'md')));
212
- parts.push(section(docPath(feature, 'tasks.md'), fence(feature.tasks.text, 'md')));
213
- } else if (parsed.kind === 'build') {
214
- const ids = new Set(parsed.tasks.flatMap((t) => t.covers));
215
- const scope = scopeOf(config, feature, parsed.tasks);
216
- parts.push(section('Tasks', fence(toYaml(parsed.tasks.map(({ verify, ...t }) => (verify ? { ...t, verify } : t))), 'yaml')));
217
- parts.push(section('Allowed paths (scope, enforced by agjan check)', scopeText(scope)));
218
- parts.push(section('Acceptance criteria covered', acsText(feature, ids)));
219
- parts.push(section('Diff of the allowed paths', fence(diffOf(root, base, scope.all), 'diff')));
220
- } else if (parsed.kind === 'verify') {
221
- if (!feature.design || !feature.tasks) throw new AgjanError('design.md and tasks.md must exist for the verify review');
222
- const areaNames = [...new Set(feature.tasks.parsed.tasks.map((t) => resolveArea(config, t.area)?.name).filter(Boolean))];
223
- const tests = acTestFiles(root, config, areaNames, feature.key);
224
- const loaded = loadResults(root, config, areaNames);
225
- const results = loaded.files.length ? acResults(loaded, feature.key) : null;
226
- const coverage = feature.spec.parsed.acs
227
- .map((ac) => `| ${ac.id} | ${ac.verification} | ${[...(tests.get(ac.id) ?? [])].join(', ') || '-'} | ${results ? resultLabel(results.get(ac.id)) : 'not recorded'} |`)
228
- .join('\n');
229
- const unrecorded = results
230
- ? ''
231
- : '\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.';
232
- const changed = changedFiles(root, base).filter((f) => !scriptOwned(feature.slug).has(f) && !f.startsWith('.agjan/'));
233
- parts.push(section('Acceptance criteria', acsText(feature)));
234
- parts.push(section('AC coverage (test files mentioning the AC id, and test results)', `| AC | verification | test files | result |\n|---|---|---|---|\n${coverage}${unrecorded}`));
235
- parts.push(section(docPath(feature, 'design.md'), fence(feature.design.text, 'md')));
236
- parts.push(section(docPath(feature, 'tasks.md'), fence(feature.tasks.text, 'md')));
237
- parts.push(section('Allowed paths (scope, enforced by agjan check)', scopeText(scopeOf(config, feature, feature.tasks.parsed.tasks))));
238
- parts.push(section('Changed files', changed.map((f) => `- ${f}`).join('\n') || '(none)'));
239
- parts.push(section('Full diff', fence(diffOf(root, base, changed), 'diff')));
240
- }
241
- if (baselineText && parsed.kind !== 'build' && parsed.kind !== 'fix') parts.push(section('Baseline (docs/agjan/project.md)', fence(baselineText, 'md')));
242
- parts.push(section('Earlier reviews', reviewHistory(feature)));
243
- parts.push(section('Open findings', openFindings(feature)));
244
- parts.push(
245
- section(
246
- 'How to record your result',
247
- 'Call review_record with this context_id, a verdict (pass, pass-with-notes, blocked), your findings ' +
248
- '(severity blocker, major or minor; file and line where possible, with the repository paths used in this context; ' +
249
- 'issue; suggestion; evidence for a claim that an API, annotation or syntax is wrong), and in `resolves` the ids ' +
250
- 'of open findings that this change has fixed. A blocker finding requires the verdict blocked.',
251
- ),
252
- );
253
- return parts.join('\n');
254
- }
255
-
256
- /** review_context: builds the context, stores its metadata, returns id and text. */
257
- /**
258
- * A new round of a step is pointless when nothing changed since its last round raised
259
- * findings: the reviewer would see the same files. It happens when a writer starts the
260
- * review before (or in parallel with) its edits, and it costs one of the step's rounds.
261
- */
262
- function unchangedSinceFindings(feature, step, tree) {
263
- const last = feature.reviews.records.filter((r) => r.step === step).at(-1);
264
- if (!last || last.verdict === 'pass' || last.tree_hash !== tree) return;
265
- throw new AgjanError(
266
- `nothing changed since ${last.id} (${last.verdict}); address its findings and save the changes before the next round. ` +
267
- 'A finding that needs no change is accepted by the human (agjan accept), not reviewed again.',
268
- );
269
- }
270
-
271
- /**
272
- * Spec and design reviews need complete documents: the same structural checks the gate
273
- * runs (sections, areas, every AC covered by a task with a title and paths). A review of
274
- * an unfinished template only reports that and costs one of the step's rounds.
275
- */
276
- function unfinishedDocuments(feature, config, step) {
277
- if (!['spec', 'design', 'design:light'].includes(step)) return;
278
- const problems = [];
279
- if (!feature.spec) problems.push('spec.md does not exist');
280
- if (step !== 'spec') {
281
- if (!feature.design) problems.push('design.md does not exist');
282
- if (!feature.tasks) problems.push('tasks.md does not exist');
283
- }
284
- const names = step === 'spec' ? ['spec.md'] : ['spec.md', 'design.md', 'tasks.md'];
285
- problems.push(...documentProblems(feature).filter((p) => names.some((n) => p.startsWith(n))));
286
- if (step !== 'spec') problems.push(...designProblems(feature, config));
287
- if (problems.length === 0) return;
288
- throw new AgjanError(
289
- `the documents are not ready for the ${step} review; complete them first:\n${problems.map((p) => ` - ${p}`).join('\n')}`,
290
- );
291
- }
292
-
293
- export function createReviewContext(root, config, { feature: slug, step }) {
294
- const feature = loadFeature(root, slug);
295
- const parsed = parseStep(step, feature, config);
296
- unfinishedDocuments(feature, config, parsed.step);
297
- const tree = treeHash(root, config, feature.slug);
298
- unchangedSinceFindings(feature, parsed.step, tree);
299
- const text = buildContextText(root, config, feature, parsed);
300
- const id = `${feature.key}-C${randomBytes(4).toString('hex')}`;
301
- const base = resolveBase(root, config.git?.base);
302
- const meta = {
303
- id,
304
- feature: feature.slug,
305
- step: parsed.step,
306
- documents: { spec: feature.spec?.hash, design: feature.designHash ?? undefined },
307
- inputs_hash: sha256(text),
308
- tree_hash: tree,
309
- base_commit: mergeBase(root, base),
310
- head_commit: git(root, ['rev-parse', '--verify', '--quiet', 'HEAD'], { allowFail: true })?.trim() ?? null,
311
- };
312
- const dir = join(root, CONTEXT_DIR);
313
- mkdirSync(dir, { recursive: true });
314
- writeJson(join(dir, `${id}.json`), meta);
315
- return { id, text };
316
- }
317
-
318
- function validFinding(f, i) {
319
- const where = `findings[${i}]`;
320
- if (typeof f !== 'object' || f === null) return `${where} must be an object`;
321
- if (!SEVERITIES.includes(f.severity)) return `${where}.severity must be one of ${SEVERITIES.join(', ')}`;
322
- if (typeof f.issue !== 'string' || f.issue.trim() === '') return `${where}.issue is required`;
323
- if (f.file !== undefined && (typeof f.file !== 'string' || f.file.includes('\\'))) return `${where}.file must be a POSIX path`;
324
- if (f.line !== undefined && !(Number.isInteger(f.line) && f.line > 0)) return `${where}.line must be a positive integer`;
325
- if (f.suggestion !== undefined && typeof f.suggestion !== 'string') return `${where}.suggestion must be a string`;
326
- if (f.evidence !== undefined && typeof f.evidence !== 'string') return `${where}.evidence must be a string`;
327
- const extra = Object.keys(f).filter((k) => !['severity', 'file', 'line', 'issue', 'suggestion', 'evidence'].includes(k));
328
- if (extra.length) return `${where} has unknown field(s): ${extra.join(', ')}`;
329
- return null;
330
- }
331
-
332
- /**
333
- * review_record: validates the reviewer's result against its context and appends it.
334
- * Refuses when anything in the working tree changed since the context was produced.
335
- */
336
- export function recordReview(root, config, { context_id: contextId, verdict, findings = [], resolves = [] }, { host = 'unknown', isolation = 'unknown', now }) {
337
- if (typeof contextId !== 'string' || !/^[A-Z][A-Z0-9]{1,5}-C[0-9a-f]{8}$/.test(contextId)) throw new AgjanError('context_id is missing or malformed');
338
- const metaFile = join(root, CONTEXT_DIR, `${contextId}.json`);
339
- const meta = readJson(metaFile);
340
- if (!meta) throw new AgjanError(`unknown context ${contextId}; call review_context first`);
341
- if (meta.recorded) throw new AgjanError(`context ${contextId} was already used for ${meta.recorded}; call review_context again`);
342
- if (!VERDICTS.includes(verdict)) throw new AgjanError(`verdict must be one of ${VERDICTS.join(', ')}`);
343
- if (!Array.isArray(findings) || findings.length > 50) throw new AgjanError('findings must be a list of at most 50 items');
344
- const problems = findings.map(validFinding).filter(Boolean);
345
- if (problems.length) throw new AgjanError(problems.join('; '));
346
- const hasBlocker = findings.some((f) => f.severity === 'blocker');
347
- if (hasBlocker && verdict !== 'blocked') throw new AgjanError('a blocker finding requires the verdict blocked');
348
- if (verdict === 'blocked' && !hasBlocker) throw new AgjanError('the verdict blocked requires at least one blocker finding');
349
- if (verdict === 'pass' && findings.length) throw new AgjanError('the verdict pass allows no findings; use pass-with-notes');
350
-
351
- const feature = loadFeature(root, meta.feature);
352
- if (!Array.isArray(resolves) || resolves.some((id) => typeof id !== 'string')) throw new AgjanError('resolves must be a list of finding ids');
353
- const open = new Set(feature.findings.filter((f) => f.status === 'open').map((f) => f.id));
354
- const unknown = resolves.filter((id) => !open.has(id));
355
- if (unknown.length) throw new AgjanError(`resolves lists findings that are not open: ${unknown.join(', ')}`);
356
-
357
- if (treeHash(root, config, feature.slug) !== meta.tree_hash) {
358
- throw new AgjanError(
359
- 'the working tree changed since review_context was called; nothing was recorded. ' +
360
- 'A reviewer must not change files. Call review_context again and review the current state.',
361
- );
362
- }
363
-
364
- const records = feature.reviews.records;
365
- let next = feature.findings.length;
366
- const record = {
367
- id: `${feature.key}-R${records.length + 1}`,
368
- step: meta.step,
369
- round: nextRound(feature, meta.step),
370
- at_utc: now(),
371
- reviewer: { host, model: null, isolation },
372
- context: contextId,
373
- documents: meta.documents,
374
- inputs_hash: meta.inputs_hash,
375
- tree_hash: meta.tree_hash,
376
- base_commit: meta.base_commit,
377
- head_commit: meta.head_commit,
378
- verdict,
379
- resolves,
380
- findings: findings.map((f) => ({ id: `${feature.key}-F${++next}`, ...f })),
381
- };
382
- records.push(record);
383
- writeJson(join(feature.dir, REVIEWS_FILE), { schema: 1, records });
384
- writeFileSync(join(feature.dir, REVIEW_MD), renderReviewMd(loadFeature(root, feature.slug)));
385
- writeJson(metaFile, { ...meta, recorded: record.id });
386
- appendLog(feature.dir, record.at_utc, 'review-recorded', {
387
- review: record.id,
388
- step: record.step,
389
- round: record.round,
390
- verdict: record.verdict,
391
- findings: record.findings.length,
392
- blockers: record.findings.filter((f) => f.severity === 'blocker').length,
393
- isolation,
394
- });
395
- return record;
396
- }
397
-
398
- /** Renders review.md from reviews.json (design 8.5). Generated; never edited by hand. */
399
- export function renderReviewMd(feature) {
400
- const out = [`# Reviews: ${feature.slug} (${feature.key})`, '', '<!-- Generated by agjan from reviews.json. Do not edit. -->', ''];
401
- const status = new Map(feature.findings.map((f) => [f.id, f.status]));
402
- for (const r of feature.reviews.records) {
403
- out.push(`## ${r.id} ${r.step}, round ${r.round}: ${r.verdict}`, '');
404
- out.push(`${r.at_utc} · reviewer: ${r.reviewer?.host ?? 'unknown'}, isolation ${r.reviewer?.isolation ?? 'unknown'}`, '');
405
- if (r.resolves?.length) out.push(`Resolves: ${r.resolves.join(', ')}`, '');
406
- for (const f of r.findings ?? []) {
407
- const where = f.file ? ` ${f.file}${f.line ? `:${f.line}` : ''}` : '';
408
- out.push(`- **${f.id}** [${f.severity}]${where} (${status.get(f.id)})`);
409
- out.push(` - Issue: ${f.issue}`);
410
- if (f.suggestion) out.push(` - Suggestion: ${f.suggestion}`);
411
- if (f.evidence) out.push(` - Evidence: ${f.evidence}`);
412
- }
413
- if (r.findings?.length) out.push('');
414
- }
415
- return `${out.join('\n').trimEnd()}\n`;
416
- }
package/src/scope.mjs DELETED
@@ -1,30 +0,0 @@
1
- import picomatch from 'picomatch';
2
- import { resolveArea } from './config.mjs';
3
-
4
- /** A path ending in '/' means the whole folder. */
5
- function toGlob(pattern) {
6
- return pattern.endsWith('/') ? `${pattern}**` : pattern;
7
- }
8
-
9
- /** Case-sensitive matcher for POSIX repository paths, the same on every OS (design 4.5). */
10
- export function matcher(patterns) {
11
- if (patterns.length === 0) return () => false;
12
- return picomatch(patterns.map(toGlob), { dot: true, nocase: false, windows: false });
13
- }
14
-
15
- /**
16
- * The patterns a feature in Build may change: its task paths, the implicit allowlist of
17
- * the task areas, and approved amendments (design 6.5).
18
- */
19
- export function allowedPatterns(feature, config) {
20
- const patterns = [];
21
- for (const task of feature.tasks?.parsed.tasks ?? []) {
22
- patterns.push(...task.paths);
23
- const area = resolveArea(config, task.area ?? '');
24
- if (area) patterns.push(...(config.scope.implicit[area.name] ?? []));
25
- }
26
- for (const amendment of feature.amendments) {
27
- if (amendment.status === 'approved') patterns.push(...amendment.paths);
28
- }
29
- return patterns;
30
- }
package/src/terminal.mjs DELETED
@@ -1,118 +0,0 @@
1
- import { openSync, readSync, writeSync, closeSync } from 'node:fs';
2
- import { createInterface } from 'node:readline';
3
- import { ReadStream, WriteStream, isatty } from 'node:tty';
4
- import { AgjanError } from './errors.mjs';
5
-
6
- /**
7
- * Opens the controlling terminal, bypassing stdin and stdout, so that piped input
8
- * cannot answer a confirmation (design 9.4). Returns null when there is none, which is
9
- * the case for commands run by an agent's shell tool.
10
- */
11
- function openTerminal() {
12
- try {
13
- if (process.platform === 'win32') {
14
- return { input: openSync('CONIN$', 'r'), output: openSync('CONOUT$', 'w') };
15
- }
16
- const fd = openSync('/dev/tty', 'r+');
17
- return { input: fd, output: fd };
18
- } catch {
19
- return null;
20
- }
21
- }
22
-
23
- function readLine(fd) {
24
- const bytes = [];
25
- const buffer = Buffer.alloc(1);
26
- for (;;) {
27
- let n;
28
- try {
29
- n = readSync(fd, buffer, 0, 1, null);
30
- } catch (error) {
31
- if (error.code === 'EAGAIN') continue;
32
- throw error;
33
- }
34
- if (n === 0 || buffer[0] === 0x0a) break;
35
- bytes.push(buffer[0]);
36
- }
37
- return Buffer.from(bytes).toString('utf8').replace(/\r$/, '');
38
- }
39
-
40
- /**
41
- * Shows `summary` on the terminal and asks the human to type `expected`.
42
- * Returns true when they did. Throws when no terminal is available.
43
- */
44
- export function confirmOnTerminal(summary, expected) {
45
- const tty = openTerminal();
46
- if (!tty) {
47
- throw new AgjanError(
48
- 'this command needs a human at an interactive terminal; agents must not run it.\n' +
49
- 'Run it yourself in a terminal (for example the VS Code integrated terminal).',
50
- );
51
- }
52
- try {
53
- writeSync(tty.output, `${summary}\nType ${expected} to confirm, anything else to cancel: `);
54
- return readLine(tty.input).trim() === expected;
55
- } finally {
56
- closeSync(tty.input);
57
- if (tty.output !== tty.input) closeSync(tty.output);
58
- }
59
- }
60
-
61
- /**
62
- * Asks a yes/no question on the controlling terminal. Returns true or false, or null when
63
- * there is no terminal (a script, CI or an agent): the caller then keeps its default.
64
- */
65
- export function askOnTerminal(question, { defaultYes = false } = {}) {
66
- const tty = openTerminal();
67
- if (!tty) return null;
68
- try {
69
- // The capital letter is the default (Enter), also in bold.
70
- const bold = (t) => (process.env.NO_COLOR !== undefined ? t : `\x1b[1m\x1b[36m${t}\x1b[0m`);
71
- writeSync(tty.output, `${question} ${defaultYes ? `[${bold('Y')}/n]` : `[y/${bold('N')}]`} `);
72
- const answer = readLine(tty.input).trim();
73
- if (answer === '') return defaultYes;
74
- return /^y(es)?$/i.test(answer);
75
- } finally {
76
- closeSync(tty.input);
77
- if (tty.output !== tty.input) closeSync(tty.output);
78
- }
79
- }
80
-
81
- /**
82
- * Asks for one line on the controlling terminal with `initial` already typed, so the human
83
- * can edit it in place (cursor keys, backspace) or press Enter to keep it. Without line
84
- * editing (a console that is not a TTY stream) it falls back to "Enter keeps, text replaces".
85
- */
86
- export async function editOnTerminal(prompt, initial) {
87
- const tty = openTerminal();
88
- if (!tty) throw new AgjanError('this command needs a human at an interactive terminal');
89
- let input;
90
- let output;
91
- try {
92
- if (!isatty(tty.input)) throw new Error('not a TTY');
93
- input = new ReadStream(tty.input);
94
- // A second stream on the same descriptor must not close it; ReadStream owns it.
95
- output = new WriteStream(tty.output === tty.input ? openSync(process.platform === 'win32' ? 'CONOUT$' : '/dev/tty', 'w') : tty.output);
96
- } catch {
97
- try {
98
- writeSync(tty.output, `${prompt}${initial}\nPress Enter to keep it, or type a new one: `);
99
- const answer = readLine(tty.input).trim();
100
- return answer === '' ? initial : answer;
101
- } finally {
102
- closeSync(tty.input);
103
- if (tty.output !== tty.input) closeSync(tty.output);
104
- }
105
- }
106
- const rl = createInterface({ input, output, terminal: true });
107
- try {
108
- return await new Promise((resolve) => {
109
- rl.on('SIGINT', () => resolve(''));
110
- rl.question(prompt, resolve);
111
- rl.write(initial);
112
- });
113
- } finally {
114
- rl.close();
115
- input.destroy();
116
- output.destroy();
117
- }
118
- }