agjan 0.0.0-stage → 0.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/NOTICE +11 -0
- package/README.md +105 -2
- package/bin/agjan.mjs +12 -0
- package/docs/brand/agjan-icon.svg +14 -0
- package/docs/brand/agjan-logo-dark.svg +17 -0
- package/docs/brand/agjan-logo-light.svg +17 -0
- package/docs/guide.md +232 -0
- package/kit/domains/btp/domain.json +27 -0
- package/kit/hooks/guard.mjs +61 -0
- package/kit/mcp/servers.json +5 -0
- package/kit/skills/agjan-build/SKILL.md +61 -0
- package/kit/skills/agjan-design/SKILL.md +95 -0
- package/kit/skills/agjan-fix/SKILL.md +55 -0
- package/kit/skills/agjan-map/SKILL.md +51 -0
- package/kit/skills/agjan-spec/SKILL.md +111 -0
- package/kit/skills/agjan-verify/SKILL.md +60 -0
- package/kit/skills/btp-architect/SKILL.md +51 -0
- package/kit/skills/btp-architect/references/deployment.md +72 -0
- package/kit/skills/btp-architect/references/security.md +54 -0
- package/kit/skills/cap-developer/SKILL.md +49 -0
- package/kit/skills/cap-developer/references/handlers.md +47 -0
- package/kit/skills/cap-developer/references/modeling.md +52 -0
- package/kit/skills/cap-developer/references/services.md +53 -0
- package/kit/skills/cap-developer/references/testing.md +39 -0
- package/kit/skills/cap-developer/references/validation-security.md +49 -0
- package/kit/skills/fiori-developer/SKILL.md +64 -0
- package/kit/skills/fiori-developer/references/elements.md +77 -0
- package/kit/skills/fiori-developer/references/freestyle-ts.md +45 -0
- package/kit/skills/fiori-developer/references/testing.md +32 -0
- package/kit/skills/fiori-developer/references/ui5-basics.md +52 -0
- package/kit/skills/solution-reviewer/SKILL.md +51 -0
- package/kit/templates/agents-block.md +20 -0
- package/kit/templates/agjan-ci.yml +40 -0
- package/kit/templates/design.md +17 -0
- package/kit/templates/project.md +28 -0
- package/kit/templates/spec.md +33 -0
- package/kit/templates/tasks.md +13 -0
- package/package.json +50 -4
- package/schemas/approvals.schema.json +93 -0
- package/schemas/config.schema.json +79 -0
- package/schemas/log.schema.json +30 -0
- package/schemas/reviews.schema.json +68 -0
- package/schemas/tasks.schema.json +26 -0
- package/src/adapters/claude-code.mjs +115 -0
- package/src/adapters/copilot.mjs +88 -0
- package/src/baseline.mjs +66 -0
- package/src/cli.mjs +133 -0
- package/src/commands/check.mjs +363 -0
- package/src/commands/fix.mjs +116 -0
- package/src/commands/gates.mjs +264 -0
- package/src/commands/log.mjs +53 -0
- package/src/commands/map.mjs +47 -0
- package/src/commands/new.mjs +53 -0
- package/src/commands/pr-summary.mjs +134 -0
- package/src/commands/report.mjs +110 -0
- package/src/commands/review.mjs +49 -0
- package/src/commands/setup.mjs +269 -0
- package/src/commands/status.mjs +176 -0
- package/src/config.mjs +98 -0
- package/src/context.mjs +58 -0
- package/src/documents.mjs +188 -0
- package/src/errors.mjs +16 -0
- package/src/feature.mjs +214 -0
- package/src/fix.mjs +108 -0
- package/src/git.mjs +66 -0
- package/src/hash.mjs +33 -0
- package/src/hook.mjs +48 -0
- package/src/json-file.mjs +24 -0
- package/src/log.mjs +37 -0
- package/src/managed.mjs +178 -0
- package/src/mcp-config.mjs +83 -0
- package/src/mcp.mjs +142 -0
- package/src/plan.mjs +41 -0
- package/src/progress.mjs +85 -0
- package/src/review-policy.mjs +49 -0
- package/src/review.mjs +336 -0
- package/src/scope.mjs +30 -0
- package/src/terminal.mjs +98 -0
- package/src/test-results.mjs +111 -0
- package/src/tests-map.mjs +29 -0
- package/src/ui.mjs +110 -0
- package/src/usage.mjs +118 -0
- package/src/validate.mjs +41 -0
package/src/progress.mjs
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { git, mergeBase, resolveBase } from './git.mjs';
|
|
2
|
+
import { resolveArea } from './config.mjs';
|
|
3
|
+
import { matcher } from './scope.mjs';
|
|
4
|
+
import { latestReview } from './feature.mjs';
|
|
5
|
+
import { treeHash } from './review.mjs';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Build progress, derived from commits (design 8.3): a task is done when a commit on
|
|
9
|
+
* the branch has a subject starting with `<KEY>-<task id>:`, for example `ORDF-T1: …`.
|
|
10
|
+
* `history` searches the whole history instead, for a feature already on the base branch.
|
|
11
|
+
*/
|
|
12
|
+
export function taskCommits(root, config, feature, { history = false } = {}) {
|
|
13
|
+
const from = history ? null : mergeBase(root, resolveBase(root, config.git?.base));
|
|
14
|
+
const range = from ? `${from}..HEAD` : 'HEAD';
|
|
15
|
+
const log = git(root, ['log', '--format=%H%x09%s', range], { allowFail: true }) ?? '';
|
|
16
|
+
const done = new Map();
|
|
17
|
+
const prefix = new RegExp(`^${feature.key}-(T[1-9][0-9]*):`);
|
|
18
|
+
// git log lists newest first; keep the newest commit of each task.
|
|
19
|
+
for (const line of log.split('\n').filter(Boolean)) {
|
|
20
|
+
const [sha, subject] = line.split('\t');
|
|
21
|
+
const match = prefix.exec(subject ?? '');
|
|
22
|
+
if (match && !done.has(match[1])) done.set(match[1], sha);
|
|
23
|
+
}
|
|
24
|
+
return done;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function filesOf(root, sha) {
|
|
28
|
+
return (git(root, ['show', '--name-only', '--format=', sha]) ?? '').split('\n').filter(Boolean);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function isAncestor(root, ancestor, descendant) {
|
|
32
|
+
if (!ancestor || !descendant) return false;
|
|
33
|
+
return git(root, ['merge-base', '--is-ancestor', ancestor, descendant], { allowFail: true }) !== null;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** A passing review of `step` that saw the given commit (its head contains the commit). */
|
|
37
|
+
function reviewedSince(root, feature, step, sha) {
|
|
38
|
+
return feature.reviews.records.some((r) => r.step === step && r.verdict !== 'blocked' && isAncestor(root, sha, r.head_commit));
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Tasks with their state, the next task, and the build reviews that are due
|
|
43
|
+
* (design 7.3): per completed area by default, per task with `review.build: task`, and
|
|
44
|
+
* always per task for tasks whose commit touched a risk path.
|
|
45
|
+
*/
|
|
46
|
+
export function buildProgress(root, config, feature, options = {}) {
|
|
47
|
+
const tasks = feature.tasks?.parsed.tasks ?? [];
|
|
48
|
+
const done = taskCommits(root, config, feature, options);
|
|
49
|
+
const isRisk = matcher(config.risk_paths ?? []);
|
|
50
|
+
const list = tasks.map((t) => ({
|
|
51
|
+
...t,
|
|
52
|
+
areaName: resolveArea(config, t.area ?? '')?.name ?? t.area,
|
|
53
|
+
commit: done.get(t.id) ?? null,
|
|
54
|
+
}));
|
|
55
|
+
const due = [];
|
|
56
|
+
const perTask = config.review?.build === 'task';
|
|
57
|
+
for (const task of list.filter((t) => t.commit)) {
|
|
58
|
+
const risky = filesOf(root, task.commit).some(isRisk);
|
|
59
|
+
if ((perTask || risky) && !reviewedSince(root, feature, `build:${task.id}`, task.commit)) {
|
|
60
|
+
due.push({ step: `build:${task.id}`, reason: risky ? 'touches a risk path' : 'review per task' });
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
if (!perTask) {
|
|
64
|
+
for (const area of [...new Set(list.map((t) => t.areaName))]) {
|
|
65
|
+
const areaTasks = list.filter((t) => t.areaName === area);
|
|
66
|
+
if (areaTasks.some((t) => !t.commit)) continue;
|
|
67
|
+
const last = areaTasks.map((t) => t.commit).find((sha) => areaTasks.every((o) => isAncestor(root, o.commit, sha)));
|
|
68
|
+
if (!reviewedSince(root, feature, `build:${area}`, last)) due.push({ step: `build:${area}`, reason: 'all tasks of the area are done' });
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
const next = list.find((t) => !t.commit) ?? null;
|
|
72
|
+
return { tasks: list, next, due, complete: list.length > 0 && !next };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* The final verify review (design 8.4): `none`, `blocked`, `stale` (files changed after
|
|
77
|
+
* it) or `current`. Shared by `check --ci` and `status`.
|
|
78
|
+
*/
|
|
79
|
+
export function verifyState(root, config, feature) {
|
|
80
|
+
const record = latestReview(feature.reviews, ['verify']);
|
|
81
|
+
if (!record) return { state: 'none', record: null };
|
|
82
|
+
if (record.verdict === 'blocked') return { state: 'blocked', record };
|
|
83
|
+
if (record.tree_hash !== treeHash(root, config, feature.slug)) return { state: 'stale', record };
|
|
84
|
+
return { state: 'current', record };
|
|
85
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Review settings from agjan.config.json (design 7.3, 7.4): which reviewer agent runs a
|
|
3
|
+
* step (`review.tiers`), how many correction rounds a step gets (`review.rounds`), and
|
|
4
|
+
* how many attempts the writer has for failing deterministic checks
|
|
5
|
+
* (`build.fix_attempts`). `agjan status` shows them; the skills follow `status`.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/** Default tier per kind of review step. */
|
|
9
|
+
export const DEFAULT_TIERS = {
|
|
10
|
+
spec: 'balanced',
|
|
11
|
+
'design:light': 'balanced',
|
|
12
|
+
design: 'deep',
|
|
13
|
+
build: 'balanced',
|
|
14
|
+
verify: 'deep',
|
|
15
|
+
fix: 'balanced',
|
|
16
|
+
map: 'balanced',
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
/** `build:cap` and `build:T2` are both of kind `build`. */
|
|
20
|
+
export function stepKind(step) {
|
|
21
|
+
return step.startsWith('build:') ? 'build' : step;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** The generated reviewer agent for a step. There is no fast agent; `fast` uses the balanced one. */
|
|
25
|
+
export function reviewerFor(config, step) {
|
|
26
|
+
const kind = stepKind(step);
|
|
27
|
+
const tier = config.review?.tiers?.[kind] ?? DEFAULT_TIERS[kind] ?? 'balanced';
|
|
28
|
+
return tier === 'deep' ? 'agjan-reviewer-deep' : 'agjan-reviewer';
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function roundLimit(config) {
|
|
32
|
+
return config.review?.rounds ?? 3;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function fixAttempts(config) {
|
|
36
|
+
return config.build?.fix_attempts ?? 3;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The state of one review step: its latest round and verdict, and whether the round limit
|
|
41
|
+
* is reached with the step still blocked (design 7.4: stop and hand over to the human).
|
|
42
|
+
*/
|
|
43
|
+
export function roundState(feature, config, step) {
|
|
44
|
+
const records = feature.reviews.records.filter((r) => r.step === step);
|
|
45
|
+
const last = records.at(-1) ?? null;
|
|
46
|
+
const limit = roundLimit(config);
|
|
47
|
+
const round = last?.round ?? 0;
|
|
48
|
+
return { last, round, limit, exhausted: last?.verdict === 'blocked' && round >= limit };
|
|
49
|
+
}
|
package/src/review.mjs
ADDED
|
@@ -0,0 +1,336 @@
|
|
|
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
|
+
|
|
17
|
+
export const REVIEW_MD = 'review.md';
|
|
18
|
+
const CONTEXT_DIR = '.agjan/review-contexts';
|
|
19
|
+
/** Limit for diffs inside a review context, so a huge change cannot flood the reviewer. */
|
|
20
|
+
const MAX_DIFF_BYTES = 200_000;
|
|
21
|
+
const SEVERITIES = ['blocker', 'major', 'minor'];
|
|
22
|
+
const VERDICTS = ['pass', 'pass-with-notes', 'blocked'];
|
|
23
|
+
|
|
24
|
+
/** Script-owned files of a feature: they change during a review by design. */
|
|
25
|
+
function scriptOwned(slug) {
|
|
26
|
+
return new Set([APPROVALS_FILE, REVIEWS_FILE, REVIEW_MD, LOG_FILE, 'report.md', 'fix.json', 'fix.md'].map((f) => `${FEATURES_DIR}/${slug}/${f}`));
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* What a changed path holds now: the file's bytes, a symbolic link's target, or null when
|
|
31
|
+
* it is deleted. A folder (an untracked link to one, a nested repository) is never read.
|
|
32
|
+
*/
|
|
33
|
+
function currentContent(path) {
|
|
34
|
+
let stat;
|
|
35
|
+
try {
|
|
36
|
+
stat = lstatSync(path);
|
|
37
|
+
} catch {
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
if (stat.isSymbolicLink()) return Buffer.from(`symbolic link to ${readlinkSync(path)}`);
|
|
41
|
+
if (!stat.isFile()) return Buffer.from(stat.isDirectory() ? '(folder)' : '(not a regular file)');
|
|
42
|
+
return readFileSync(path);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Hash of the change as it stands: every file changed relative to the merge-base
|
|
47
|
+
* (committed, staged, unstaged, untracked) with its current content, except the
|
|
48
|
+
* feature's script-owned files. Any write to the working tree changes it.
|
|
49
|
+
*/
|
|
50
|
+
export function treeHash(root, config, slug) {
|
|
51
|
+
const skip = scriptOwned(slug);
|
|
52
|
+
const hash = createHash('sha256');
|
|
53
|
+
for (const file of changedFiles(root, resolveBase(root, config.git?.base))) {
|
|
54
|
+
if (skip.has(file) || file.startsWith('.agjan/')) continue;
|
|
55
|
+
const content = currentContent(join(root, file));
|
|
56
|
+
hash.update(file).update('\0');
|
|
57
|
+
hash.update(content ? createHash('sha256').update(content).digest('hex') : 'deleted').update('\0');
|
|
58
|
+
}
|
|
59
|
+
return `sha256:${hash.digest('hex')}`;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Parses a review step. Features: spec, design, design:light, verify, build:<area>,
|
|
64
|
+
* build:<task>. A fix has only the step fix, a map run only map.
|
|
65
|
+
*/
|
|
66
|
+
export function parseStep(step, feature, config) {
|
|
67
|
+
if (feature.kind === 'fix' || feature.kind === 'map') {
|
|
68
|
+
if (step !== feature.kind) throw new AgjanError(`a ${feature.kind} record has only the review step '${feature.kind}'`);
|
|
69
|
+
return { step, kind: step };
|
|
70
|
+
}
|
|
71
|
+
if (step === 'fix' || step === 'map') throw new AgjanError(`'${step}' reviews belong to a ${step} record, not to a feature`);
|
|
72
|
+
if (['spec', 'design', 'design:light', 'verify'].includes(step)) return { step, kind: step };
|
|
73
|
+
const match = /^build:(.+)$/.exec(step ?? '');
|
|
74
|
+
if (!match) throw new AgjanError(`unknown review step '${step}'; use spec, design, design:light, build:<area>, build:<task> or verify`);
|
|
75
|
+
const tasks = feature.tasks?.parsed.tasks ?? [];
|
|
76
|
+
const byTask = tasks.filter((t) => t.id === match[1]);
|
|
77
|
+
if (byTask.length) return { step, kind: 'build', tasks: byTask };
|
|
78
|
+
const area = resolveArea(config, match[1]);
|
|
79
|
+
const byArea = area ? tasks.filter((t) => resolveArea(config, t.area)?.id === area.id) : [];
|
|
80
|
+
if (byArea.length === 0) throw new AgjanError(`'${match[1]}' is neither a task id nor an area with tasks in tasks.md`);
|
|
81
|
+
return { step: `build:${area.name}`, kind: 'build', tasks: byArea };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function capped(text) {
|
|
85
|
+
if (Buffer.byteLength(text) <= MAX_DIFF_BYTES) return text;
|
|
86
|
+
return `${text.slice(0, MAX_DIFF_BYTES)}\n\n[diff truncated at ${MAX_DIFF_BYTES} bytes; read the files directly]\n`;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Diff of the given path patterns against the merge-base, untracked files included. */
|
|
90
|
+
function diffOf(root, base, patterns) {
|
|
91
|
+
if (patterns.length === 0) return '(no changes)\n';
|
|
92
|
+
const from = mergeBase(root, base) ?? 'HEAD';
|
|
93
|
+
const specs = patterns.map((p) => `:(glob)${p.endsWith('/') ? `${p}**` : p}`);
|
|
94
|
+
let out = git(root, ['diff', '--no-color', '--no-ext-diff', from, '--', ...specs], { allowFail: true }) ?? '';
|
|
95
|
+
const untracked = git(root, ['ls-files', '--others', '--exclude-standard', '--', ...specs]).split('\n').filter(Boolean);
|
|
96
|
+
for (const file of untracked) {
|
|
97
|
+
out += `\n--- new file: ${file}\n${currentContent(join(root, file))?.toString('utf8') ?? '(deleted)'}`;
|
|
98
|
+
}
|
|
99
|
+
return capped(out || '(no changes)\n');
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function section(title, body) {
|
|
103
|
+
return `## ${title}\n\n${body.trimEnd()}\n`;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function fence(text, lang = '') {
|
|
107
|
+
const ticks = text.includes('```') ? '````' : '```';
|
|
108
|
+
return `${ticks}${lang}\n${text.trimEnd()}\n${ticks}`;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function acsText(feature, ids) {
|
|
112
|
+
return feature.spec.parsed.acs
|
|
113
|
+
.filter((ac) => !ids || ids.has(ac.id))
|
|
114
|
+
.map((ac) => {
|
|
115
|
+
const lines = feature.spec.text.split(/\r?\n/);
|
|
116
|
+
const start = ac.line - 1;
|
|
117
|
+
let end = lines.findIndex((l, i) => i > start && /^#{2,3} /.test(l));
|
|
118
|
+
if (end === -1) end = lines.length;
|
|
119
|
+
return lines.slice(start, end).join('\n').trim();
|
|
120
|
+
})
|
|
121
|
+
.join('\n\n');
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function reviewHistory(feature) {
|
|
125
|
+
if (feature.reviews.records.length === 0) return '(none)';
|
|
126
|
+
return feature.reviews.records
|
|
127
|
+
.map((r) => `- ${r.id} ${r.step} round ${r.round}: ${r.verdict}, ${r.findings?.length ?? 0} finding(s)`)
|
|
128
|
+
.join('\n');
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function openFindings(feature, steps) {
|
|
132
|
+
const open = feature.findings.filter((f) => f.status === 'open' && (!steps || steps.includes(f.step)));
|
|
133
|
+
if (open.length === 0) return '(none)';
|
|
134
|
+
return open.map((f) => `- ${f.id} [${f.severity}] ${f.file ? `${f.file}${f.line ? `:${f.line}` : ''} ` : ''}${f.issue}`).join('\n');
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const CHECKLISTS = {
|
|
138
|
+
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.',
|
|
139
|
+
'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, every AC covered.',
|
|
140
|
+
design: 'Every AC covered by tasks. Areas and app types justified with alternatives. Open technical questions answered. Nothing beyond the spec.',
|
|
141
|
+
build: 'Each covered AC is met by the diff. Tests exist and carry the AC id in their names. Project conventions. Security basics (authorization, input validation, no secrets).',
|
|
142
|
+
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).',
|
|
143
|
+
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.',
|
|
144
|
+
verify: 'Cross-task consistency. Every AC covered by a passing test or marked manual. The baseline (project.md) updated if a service, application or BTP service was added. Do not re-review each task.',
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
/** Builds the reviewer's input for a step: the only material the reviewer should read. */
|
|
148
|
+
export function buildContextText(root, config, feature, parsed) {
|
|
149
|
+
const base = resolveBase(root, config.git?.base);
|
|
150
|
+
const parts = [`# Review context: ${feature.slug} (${feature.key}), step ${parsed.step}`, ''];
|
|
151
|
+
parts.push(section('Checklist', CHECKLISTS[parsed.kind]));
|
|
152
|
+
const baseline = join(root, FEATURES_DIR, 'project.md');
|
|
153
|
+
const baselineText = existsSync(baseline) ? readFileSync(baseline, 'utf8') : null;
|
|
154
|
+
|
|
155
|
+
if (parsed.kind === 'fix') {
|
|
156
|
+
const description = readJson(join(feature.dir, 'fix.json'))?.what ?? '(no description)';
|
|
157
|
+
const rules = fixRules(root, config);
|
|
158
|
+
const files = rules.files.map((f) => `- ${f.path} +${f.added}/-${f.deleted}${f.isNew ? ' (new)' : ''}`).join('\n') || '(none)';
|
|
159
|
+
const verdict = rules.problems.length ? rules.problems.map((p) => `- ${p}`).join('\n') : 'within the limits';
|
|
160
|
+
parts.push(section('Fix description', description));
|
|
161
|
+
parts.push(section('Fast-path rules', `${rules.total} changed lines (limit ${rules.limits.max_total}). ${verdict}\n\n${files}`));
|
|
162
|
+
parts.push(section('Diff', fence(diffOf(root, base, rules.files.map((f) => f.path)), 'diff')));
|
|
163
|
+
} else if (parsed.kind === 'map') {
|
|
164
|
+
if (!baselineText) throw new AgjanError(`${FEATURES_DIR}/project.md does not exist; write it first`);
|
|
165
|
+
const watched = Object.keys(watchedHashes(root, config));
|
|
166
|
+
parts.push(section('Watched files (models, services, apps, deployment)', watched.map((f) => `- ${f}`).join('\n') || '(none)'));
|
|
167
|
+
const files = repoFiles(root).filter((f) => !f.startsWith(`${FEATURES_DIR}/`));
|
|
168
|
+
parts.push(section('Repository files', `${files.slice(0, 300).map((f) => `- ${f}`).join('\n')}${files.length > 300 ? `\n- … ${files.length - 300} more` : ''}`));
|
|
169
|
+
} else if (!feature.spec) {
|
|
170
|
+
throw new AgjanError('spec.md does not exist');
|
|
171
|
+
} else if (parsed.kind === 'spec') {
|
|
172
|
+
parts.push(section('spec.md', fence(feature.spec.text, 'md')));
|
|
173
|
+
} else if (parsed.kind === 'design' || parsed.kind === 'design:light') {
|
|
174
|
+
if (!feature.design || !feature.tasks) throw new AgjanError('design.md and tasks.md must exist for a design review');
|
|
175
|
+
parts.push(section('spec.md', fence(feature.spec.text, 'md')));
|
|
176
|
+
parts.push(section('design.md', fence(feature.design.text, 'md')));
|
|
177
|
+
parts.push(section('tasks.md', fence(feature.tasks.text, 'md')));
|
|
178
|
+
} else if (parsed.kind === 'build') {
|
|
179
|
+
const ids = new Set(parsed.tasks.flatMap((t) => t.covers));
|
|
180
|
+
const paths = parsed.tasks.flatMap((t) => t.paths);
|
|
181
|
+
const taskIds = new Set(parsed.tasks.map((t) => t.id));
|
|
182
|
+
for (const a of feature.amendments) if (a.status === 'approved' && taskIds.has(a.task)) paths.push(...a.paths);
|
|
183
|
+
parts.push(section('Tasks', fence(toYaml(parsed.tasks.map(({ verify, ...t }) => (verify ? { ...t, verify } : t))), 'yaml')));
|
|
184
|
+
parts.push(section('Acceptance criteria covered', acsText(feature, ids)));
|
|
185
|
+
parts.push(section('Diff of the task paths', fence(diffOf(root, base, paths), 'diff')));
|
|
186
|
+
} else if (parsed.kind === 'verify') {
|
|
187
|
+
if (!feature.design || !feature.tasks) throw new AgjanError('design.md and tasks.md must exist for the verify review');
|
|
188
|
+
const areaNames = [...new Set(feature.tasks.parsed.tasks.map((t) => resolveArea(config, t.area)?.name).filter(Boolean))];
|
|
189
|
+
const tests = acTestFiles(root, config, areaNames, feature.key);
|
|
190
|
+
const loaded = loadResults(root, config, areaNames);
|
|
191
|
+
const results = loaded.files.length ? acResults(loaded, feature.key) : null;
|
|
192
|
+
const coverage = feature.spec.parsed.acs
|
|
193
|
+
.map((ac) => `| ${ac.id} | ${ac.verification} | ${[...(tests.get(ac.id) ?? [])].join(', ') || '-'} | ${results ? resultLabel(results.get(ac.id)) : 'no results'} |`)
|
|
194
|
+
.join('\n');
|
|
195
|
+
const changed = changedFiles(root, base).filter((f) => !scriptOwned(feature.slug).has(f) && !f.startsWith('.agjan/'));
|
|
196
|
+
parts.push(section('Acceptance criteria', acsText(feature)));
|
|
197
|
+
parts.push(section('AC coverage (test files mentioning the AC id, and test results)', `| AC | verification | test files | result |\n|---|---|---|---|\n${coverage}`));
|
|
198
|
+
parts.push(section('design.md', fence(feature.design.text, 'md')));
|
|
199
|
+
parts.push(section('tasks.md', fence(feature.tasks.text, 'md')));
|
|
200
|
+
parts.push(section('Changed files', changed.map((f) => `- ${f}`).join('\n') || '(none)'));
|
|
201
|
+
parts.push(section('Full diff', fence(diffOf(root, base, changed), 'diff')));
|
|
202
|
+
}
|
|
203
|
+
if (baselineText && parsed.kind !== 'build' && parsed.kind !== 'fix') parts.push(section('Baseline (docs/agjan/project.md)', fence(baselineText, 'md')));
|
|
204
|
+
parts.push(section('Earlier reviews', reviewHistory(feature)));
|
|
205
|
+
parts.push(section('Open findings', openFindings(feature)));
|
|
206
|
+
parts.push(
|
|
207
|
+
section(
|
|
208
|
+
'How to record your result',
|
|
209
|
+
'Call review_record with this context_id, a verdict (pass, pass-with-notes, blocked), your findings ' +
|
|
210
|
+
'(severity blocker, major or minor; file and line where possible; issue; suggestion), and in `resolves` the ids ' +
|
|
211
|
+
'of open findings that this change has fixed. A blocker finding requires the verdict blocked.',
|
|
212
|
+
),
|
|
213
|
+
);
|
|
214
|
+
return parts.join('\n');
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** review_context: builds the context, stores its metadata, returns id and text. */
|
|
218
|
+
export function createReviewContext(root, config, { feature: slug, step }) {
|
|
219
|
+
const feature = loadFeature(root, slug);
|
|
220
|
+
const parsed = parseStep(step, feature, config);
|
|
221
|
+
const text = buildContextText(root, config, feature, parsed);
|
|
222
|
+
const id = `${feature.key}-C${randomBytes(4).toString('hex')}`;
|
|
223
|
+
const base = resolveBase(root, config.git?.base);
|
|
224
|
+
const meta = {
|
|
225
|
+
id,
|
|
226
|
+
feature: feature.slug,
|
|
227
|
+
step: parsed.step,
|
|
228
|
+
documents: { spec: feature.spec?.hash, design: feature.designHash ?? undefined },
|
|
229
|
+
inputs_hash: sha256(text),
|
|
230
|
+
tree_hash: treeHash(root, config, feature.slug),
|
|
231
|
+
base_commit: mergeBase(root, base),
|
|
232
|
+
head_commit: git(root, ['rev-parse', '--verify', '--quiet', 'HEAD'], { allowFail: true })?.trim() ?? null,
|
|
233
|
+
};
|
|
234
|
+
const dir = join(root, CONTEXT_DIR);
|
|
235
|
+
mkdirSync(dir, { recursive: true });
|
|
236
|
+
writeJson(join(dir, `${id}.json`), meta);
|
|
237
|
+
return { id, text };
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function validFinding(f, i) {
|
|
241
|
+
const where = `findings[${i}]`;
|
|
242
|
+
if (typeof f !== 'object' || f === null) return `${where} must be an object`;
|
|
243
|
+
if (!SEVERITIES.includes(f.severity)) return `${where}.severity must be one of ${SEVERITIES.join(', ')}`;
|
|
244
|
+
if (typeof f.issue !== 'string' || f.issue.trim() === '') return `${where}.issue is required`;
|
|
245
|
+
if (f.file !== undefined && (typeof f.file !== 'string' || f.file.includes('\\'))) return `${where}.file must be a POSIX path`;
|
|
246
|
+
if (f.line !== undefined && !(Number.isInteger(f.line) && f.line > 0)) return `${where}.line must be a positive integer`;
|
|
247
|
+
if (f.suggestion !== undefined && typeof f.suggestion !== 'string') return `${where}.suggestion must be a string`;
|
|
248
|
+
const extra = Object.keys(f).filter((k) => !['severity', 'file', 'line', 'issue', 'suggestion'].includes(k));
|
|
249
|
+
if (extra.length) return `${where} has unknown field(s): ${extra.join(', ')}`;
|
|
250
|
+
return null;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* review_record: validates the reviewer's result against its context and appends it.
|
|
255
|
+
* Refuses when anything in the working tree changed since the context was produced.
|
|
256
|
+
*/
|
|
257
|
+
export function recordReview(root, config, { context_id: contextId, verdict, findings = [], resolves = [] }, { host = 'unknown', isolation = 'unknown', now }) {
|
|
258
|
+
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');
|
|
259
|
+
const metaFile = join(root, CONTEXT_DIR, `${contextId}.json`);
|
|
260
|
+
const meta = readJson(metaFile);
|
|
261
|
+
if (!meta) throw new AgjanError(`unknown context ${contextId}; call review_context first`);
|
|
262
|
+
if (meta.recorded) throw new AgjanError(`context ${contextId} was already used for ${meta.recorded}; call review_context again`);
|
|
263
|
+
if (!VERDICTS.includes(verdict)) throw new AgjanError(`verdict must be one of ${VERDICTS.join(', ')}`);
|
|
264
|
+
if (!Array.isArray(findings) || findings.length > 50) throw new AgjanError('findings must be a list of at most 50 items');
|
|
265
|
+
const problems = findings.map(validFinding).filter(Boolean);
|
|
266
|
+
if (problems.length) throw new AgjanError(problems.join('; '));
|
|
267
|
+
const hasBlocker = findings.some((f) => f.severity === 'blocker');
|
|
268
|
+
if (hasBlocker && verdict !== 'blocked') throw new AgjanError('a blocker finding requires the verdict blocked');
|
|
269
|
+
if (verdict === 'blocked' && !hasBlocker) throw new AgjanError('the verdict blocked requires at least one blocker finding');
|
|
270
|
+
if (verdict === 'pass' && findings.length) throw new AgjanError('the verdict pass allows no findings; use pass-with-notes');
|
|
271
|
+
|
|
272
|
+
const feature = loadFeature(root, meta.feature);
|
|
273
|
+
if (!Array.isArray(resolves) || resolves.some((id) => typeof id !== 'string')) throw new AgjanError('resolves must be a list of finding ids');
|
|
274
|
+
const open = new Set(feature.findings.filter((f) => f.status === 'open').map((f) => f.id));
|
|
275
|
+
const unknown = resolves.filter((id) => !open.has(id));
|
|
276
|
+
if (unknown.length) throw new AgjanError(`resolves lists findings that are not open: ${unknown.join(', ')}`);
|
|
277
|
+
|
|
278
|
+
if (treeHash(root, config, feature.slug) !== meta.tree_hash) {
|
|
279
|
+
throw new AgjanError(
|
|
280
|
+
'the working tree changed since review_context was called; nothing was recorded. ' +
|
|
281
|
+
'A reviewer must not change files. Call review_context again and review the current state.',
|
|
282
|
+
);
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
const records = feature.reviews.records;
|
|
286
|
+
let next = feature.findings.length;
|
|
287
|
+
const record = {
|
|
288
|
+
id: `${feature.key}-R${records.length + 1}`,
|
|
289
|
+
step: meta.step,
|
|
290
|
+
round: records.filter((r) => r.step === meta.step).length + 1,
|
|
291
|
+
at_utc: now(),
|
|
292
|
+
reviewer: { host, model: null, isolation },
|
|
293
|
+
context: contextId,
|
|
294
|
+
documents: meta.documents,
|
|
295
|
+
inputs_hash: meta.inputs_hash,
|
|
296
|
+
tree_hash: meta.tree_hash,
|
|
297
|
+
base_commit: meta.base_commit,
|
|
298
|
+
head_commit: meta.head_commit,
|
|
299
|
+
verdict,
|
|
300
|
+
resolves,
|
|
301
|
+
findings: findings.map((f) => ({ id: `${feature.key}-F${++next}`, ...f })),
|
|
302
|
+
};
|
|
303
|
+
records.push(record);
|
|
304
|
+
writeJson(join(feature.dir, REVIEWS_FILE), { schema: 1, records });
|
|
305
|
+
writeFileSync(join(feature.dir, REVIEW_MD), renderReviewMd(loadFeature(root, feature.slug)));
|
|
306
|
+
writeJson(metaFile, { ...meta, recorded: record.id });
|
|
307
|
+
appendLog(feature.dir, record.at_utc, 'review-recorded', {
|
|
308
|
+
review: record.id,
|
|
309
|
+
step: record.step,
|
|
310
|
+
round: record.round,
|
|
311
|
+
verdict: record.verdict,
|
|
312
|
+
findings: record.findings.length,
|
|
313
|
+
blockers: record.findings.filter((f) => f.severity === 'blocker').length,
|
|
314
|
+
isolation,
|
|
315
|
+
});
|
|
316
|
+
return record;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/** Renders review.md from reviews.json (design 8.5). Generated; never edited by hand. */
|
|
320
|
+
export function renderReviewMd(feature) {
|
|
321
|
+
const out = [`# Reviews: ${feature.slug} (${feature.key})`, '', '<!-- Generated by agjan from reviews.json. Do not edit. -->', ''];
|
|
322
|
+
const status = new Map(feature.findings.map((f) => [f.id, f.status]));
|
|
323
|
+
for (const r of feature.reviews.records) {
|
|
324
|
+
out.push(`## ${r.id} ${r.step}, round ${r.round}: ${r.verdict}`, '');
|
|
325
|
+
out.push(`${r.at_utc} · reviewer: ${r.reviewer?.host ?? 'unknown'}, isolation ${r.reviewer?.isolation ?? 'unknown'}`, '');
|
|
326
|
+
if (r.resolves?.length) out.push(`Resolves: ${r.resolves.join(', ')}`, '');
|
|
327
|
+
for (const f of r.findings ?? []) {
|
|
328
|
+
const where = f.file ? ` ${f.file}${f.line ? `:${f.line}` : ''}` : '';
|
|
329
|
+
out.push(`- **${f.id}** [${f.severity}]${where} (${status.get(f.id)})`);
|
|
330
|
+
out.push(` - Issue: ${f.issue}`);
|
|
331
|
+
if (f.suggestion) out.push(` - Suggestion: ${f.suggestion}`);
|
|
332
|
+
}
|
|
333
|
+
if (r.findings?.length) out.push('');
|
|
334
|
+
}
|
|
335
|
+
return `${out.join('\n').trimEnd()}\n`;
|
|
336
|
+
}
|
package/src/scope.mjs
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
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
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
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 for one line on the controlling terminal with `initial` already typed, so the human
|
|
63
|
+
* can edit it in place (cursor keys, backspace) or press Enter to keep it. Without line
|
|
64
|
+
* editing (a console that is not a TTY stream) it falls back to "Enter keeps, text replaces".
|
|
65
|
+
*/
|
|
66
|
+
export async function editOnTerminal(prompt, initial) {
|
|
67
|
+
const tty = openTerminal();
|
|
68
|
+
if (!tty) throw new AgjanError('this command needs a human at an interactive terminal');
|
|
69
|
+
let input;
|
|
70
|
+
let output;
|
|
71
|
+
try {
|
|
72
|
+
if (!isatty(tty.input)) throw new Error('not a TTY');
|
|
73
|
+
input = new ReadStream(tty.input);
|
|
74
|
+
// A second stream on the same descriptor must not close it; ReadStream owns it.
|
|
75
|
+
output = new WriteStream(tty.output === tty.input ? openSync(process.platform === 'win32' ? 'CONOUT$' : '/dev/tty', 'w') : tty.output);
|
|
76
|
+
} catch {
|
|
77
|
+
try {
|
|
78
|
+
writeSync(tty.output, `${prompt}${initial}\nPress Enter to keep it, or type a new one: `);
|
|
79
|
+
const answer = readLine(tty.input).trim();
|
|
80
|
+
return answer === '' ? initial : answer;
|
|
81
|
+
} finally {
|
|
82
|
+
closeSync(tty.input);
|
|
83
|
+
if (tty.output !== tty.input) closeSync(tty.output);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
const rl = createInterface({ input, output, terminal: true });
|
|
87
|
+
try {
|
|
88
|
+
return await new Promise((resolve) => {
|
|
89
|
+
rl.on('SIGINT', () => resolve(''));
|
|
90
|
+
rl.question(prompt, resolve);
|
|
91
|
+
rl.write(initial);
|
|
92
|
+
});
|
|
93
|
+
} finally {
|
|
94
|
+
rl.close();
|
|
95
|
+
input.destroy();
|
|
96
|
+
output.destroy();
|
|
97
|
+
}
|
|
98
|
+
}
|