agjan 0.0.4 → 0.0.6

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.
@@ -0,0 +1,434 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { git } from './git.mjs';
4
+ import { loadConfig } from './config.mjs';
5
+ import { FEATURES_DIR, changedFeatures, listFeatures, loadFeature, stillBlocked } from './feature.mjs';
6
+ import { readLog } from './log.mjs';
7
+ import { buildProgress, verifyState } from './progress.mjs';
8
+ import { reviewerFor, roundLimit } from './review-policy.mjs';
9
+ import { acTestFiles } from './tests-map.mjs';
10
+ import { acResults, loadResults } from './test-results.mjs';
11
+ import { freshReview } from './fix.mjs';
12
+ import { spans } from './commands/report.mjs';
13
+
14
+ /**
15
+ * Progress pages (design decision 66): what happened in each unit (feature, fix, map run),
16
+ * who worked on it, how the review loops went, and whose turn it is. agjan regenerates them
17
+ * after every event it records:
18
+ * - docs/agjan/<unit>/progress.md: committed with the unit, visible in the pull request;
19
+ * - .agjan/progress.md and .agjan/progress.html: the project overview, local (not
20
+ * committed, so parallel branches do not conflict). The HTML is self-contained.
21
+ */
22
+ export const PROGRESS_MD = 'progress.md';
23
+ const LOCAL_DIR = '.agjan';
24
+ const TEMPLATE = new URL('../kit/templates/progress.html', import.meta.url);
25
+
26
+ const iso = (ms) => new Date(ms).toISOString().replace(/\.\d{3}Z$/, 'Z');
27
+
28
+ /** The unit's title: the first sentence of the spec's Summary, the fix's description, or the map run. */
29
+ function titleOf(unit) {
30
+ if (unit.kind === 'fix') {
31
+ const fix = JSON.parse(readFileSyncSafe(join(unit.dir, 'fix.json')) || '{}');
32
+ return fix.what ?? unit.slug;
33
+ }
34
+ if (unit.kind === 'map') return 'Map of the application (docs/agjan/project.md)';
35
+ const lines = (unit.spec?.text ?? '').split('\n');
36
+ const start = lines.findIndex((l) => l.trim() === '## Summary');
37
+ const text = start === -1 ? '' : lines.slice(start + 1).find((l) => l.trim() && !l.startsWith('#')) ?? '';
38
+ const sentence = text.split(/(?<=\.)\s/)[0].trim();
39
+ return sentence.length > 110 ? `${sentence.slice(0, 107)}…` : sentence || unit.slug;
40
+ }
41
+
42
+ function readFileSyncSafe(file) {
43
+ try {
44
+ return readFileSync(file, 'utf8');
45
+ } catch {
46
+ return '';
47
+ }
48
+ }
49
+
50
+ /** Commits of the unit anywhere in the history: subjects starting with `<KEY>:` or `<KEY>-T<n>:`. */
51
+ function unitCommits(root, key) {
52
+ const log = git(root, ['log', '--format=%h%x09%cI%x09%s', 'HEAD'], { allowFail: true }) ?? '';
53
+ const pattern = new RegExp(`^${key}(-T[1-9][0-9]*)?:`);
54
+ return log
55
+ .split('\n')
56
+ .filter(Boolean)
57
+ .map((line) => line.split('\t'))
58
+ .filter(([, , subject]) => pattern.test(subject ?? ''))
59
+ .map(([sha, at, subject]) => ({ sha, at: iso(Date.parse(at)), subject }))
60
+ .reverse();
61
+ }
62
+
63
+ /** Stage track and whose turn it is. */
64
+ function stageOf(ctx, unit, onBase, extra) {
65
+ const { progress, verify, review } = extra;
66
+ if (unit.kind !== 'feature') {
67
+ const names = unit.kind === 'fix' ? ['Fix', 'Review', 'Merged'] : ['Map', 'Review', 'Merged'];
68
+ const last = unit.reviews.records.at(-1);
69
+ if (onBase && last && !stillBlocked(unit, last)) return { names, at: 3, turn: 'merged', now: 'merged' };
70
+ if (review && !review.problem) return { names, at: 2, turn: 'you', now: 'review and merge the pull request' };
71
+ if (last) return { names, at: 1, turn: 'agent', now: review?.problem ?? 'review' };
72
+ return { names, at: 0, turn: 'agent', now: unit.kind === 'fix' ? 'making the change' : 'writing docs/agjan/project.md' };
73
+ }
74
+ const mode = unit.design?.parsed.mode;
75
+ const names = ['Spec', mode === 'light' ? 'Design (light)' : 'Design', 'Build', 'Verify', onBase ? 'Merged' : 'Gate 3'];
76
+ const events = readLog(unit.dir);
77
+ const lastGate = events.filter((e) => ['gate-requested', 'approved', 'rejected'].includes(e.event)).at(-1);
78
+ const waiting = lastGate?.event === 'gate-requested';
79
+ if (unit.stage === 'spec') {
80
+ return { names, at: 0, turn: waiting ? 'you' : 'agent', now: waiting ? `approve ${lastGate.gate} in a terminal (npx agjan approve ${lastGate.gate})` : 'writing and reviewing the spec' };
81
+ }
82
+ if (unit.stage === 'design') {
83
+ return { names, at: 1, turn: waiting ? 'you' : 'agent', now: waiting ? 'approve the design in a terminal (npx agjan approve design)' : 'writing and reviewing the design' };
84
+ }
85
+ const pending = unit.amendments.filter((a) => a.status === 'pending');
86
+ if (onBase && progress.complete && verify.record && !stillBlocked(unit, verify.record)) return { names, at: 5, turn: 'merged', now: 'merged' };
87
+ if (pending.length) return { names, at: 2, turn: 'you', now: `approve amendment ${pending[0].id} (npx agjan approve amendment ${pending[0].id})` };
88
+ if (!progress.complete) return { names, at: 2, turn: 'agent', now: progress.next ? `task ${progress.next.id}: ${progress.next.title}` : 'building' };
89
+ if (progress.due.length) return { names, at: 2, turn: 'agent', now: `review ${progress.due[0].step}` };
90
+ if (verify.state === 'current') return { names, at: 4, turn: 'you', now: 'review and merge the pull request (Gate 3)' };
91
+ return { names, at: 3, turn: 'agent', now: verify.state === 'none' ? 'verify' : `verify (${verify.state})` };
92
+ }
93
+
94
+ /** The data of one unit for the progress pages. */
95
+ export function unitModel(ctx, slug, { onBase = false, now = Date.now() } = {}) {
96
+ const unit = loadFeature(ctx.root, slug);
97
+ const config = ctx.config;
98
+ const events = readLog(unit.dir);
99
+ const isFeature = unit.kind === 'feature';
100
+ const progress = isFeature && unit.tasks ? buildProgress(ctx.root, config, unit, { history: onBase }) : null;
101
+ const verify = isFeature ? verifyState(ctx.root, config, unit) : null;
102
+ const review = !isFeature ? freshReview(ctx.root, config, unit, unit.kind) : null;
103
+ const stage = stageOf(ctx, unit, onBase, { progress, verify, review });
104
+ const commits = unitCommits(ctx.root, unit.key);
105
+
106
+ const times = [...events.map((e) => Date.parse(e.at_utc)), ...commits.map((c) => Date.parse(c.at))].filter(Number.isFinite);
107
+ const start = times.length ? Math.min(...times) : now;
108
+ const last = times.length ? Math.max(...times) : now;
109
+ // An open step runs until now only while the agent works; when it is a human's turn,
110
+ // the agent's work ended with the last activity and the rest is waiting.
111
+ const end = stage.turn === 'merged' ? last : Math.max(last, now);
112
+ const list = spans(events, stage.turn === 'agent' ? end : last).map((s) => (s.kind === 'gate' && s.open ? { ...s, to: end } : s));
113
+ const steps = list.filter((s) => s.kind === 'step');
114
+ const gates = list.filter((s) => s.kind === 'gate');
115
+ // Gate 3 (review and merge) has no event of its own: the wait since the verified state.
116
+ if (isFeature && stage.turn === 'you' && stage.at === 4) gates.push({ kind: 'gate', label: 'gate Gate 3', from: last, to: end, open: true });
117
+
118
+ const host = unit.reviews.records.find((r) => r.reviewer?.host)?.reviewer.host ?? events.find((e) => e.host)?.host ?? null;
119
+ const reviews = unit.reviews.records.map((r) => ({
120
+ id: r.id,
121
+ step: r.step,
122
+ round: r.round,
123
+ verdict: r.verdict,
124
+ at: r.at_utc,
125
+ tier: reviewerFor(config, r.step) === 'agjan-reviewer-deep' ? 'deep' : 'balanced',
126
+ host: r.reviewer?.host ?? null,
127
+ isolation: r.reviewer?.isolation ?? null,
128
+ findings: (r.findings ?? []).map((f) => f.id),
129
+ resolves: r.resolves ?? [],
130
+ }));
131
+ const resolvedBy = {};
132
+ for (const r of reviews) for (const id of r.resolves) resolvedBy[id] = r.id;
133
+ const accepted = new Map(unit.approvals.accepted.map((a) => [a.finding, a]));
134
+ const findings = {};
135
+ for (const f of unit.findings) {
136
+ findings[f.id] = {
137
+ severity: f.severity,
138
+ file: f.file ?? null,
139
+ issue: f.issue,
140
+ evidence: f.evidence ?? null,
141
+ status: f.status,
142
+ raisedBy: f.record,
143
+ resolvedBy: resolvedBy[f.id] ?? null,
144
+ acceptReason: accepted.get(f.id)?.reason ?? null,
145
+ };
146
+ }
147
+
148
+ const tasks = (progress?.tasks ?? []).map((t) => ({
149
+ id: t.id,
150
+ area: t.areaName,
151
+ title: t.title,
152
+ covers: t.covers,
153
+ done: Boolean(t.commit),
154
+ commits: commits.filter((c) => c.subject.startsWith(`${unit.key}-${t.id}:`)).map((c) => c.sha),
155
+ reviews: reviews.filter((r) => r.step === `build:${t.areaName}` || r.step === `build:${t.id}`).map((r) => r.id),
156
+ }));
157
+
158
+ let acs = null;
159
+ if (isFeature && unit.spec) {
160
+ const areaNames = [...new Set(tasks.map((t) => t.area))];
161
+ const automated = unit.spec.parsed.acs.filter((ac) => ac.verification !== 'manual');
162
+ const loaded = loadResults(ctx.root, config, areaNames);
163
+ const results = loaded.files.length ? acResults(loaded, unit.key) : null;
164
+ const tests = acTestFiles(ctx.root, config, areaNames, unit.key);
165
+ acs = {
166
+ total: unit.spec.parsed.acs.length,
167
+ automated: automated.length,
168
+ manual: unit.spec.parsed.acs.filter((ac) => ac.verification === 'manual').map((ac) => ac.id),
169
+ withTests: automated.filter((ac) => tests.has(ac.id)).length,
170
+ passing: results ? automated.filter((ac) => results.get(ac.id)?.passed && !results.get(ac.id)?.failed).length : null,
171
+ };
172
+ }
173
+
174
+ const decisions = [];
175
+ for (const [gate, a] of Object.entries(unit.approvals.approvals)) decisions.push({ at: a.at_utc, by: a.by, what: `approved ${gate}` });
176
+ for (const a of unit.approvals.accepted) decisions.push({ at: a.at_utc, by: a.by, what: `accepted ${a.finding}`, detail: a.reason });
177
+ for (const r of unit.approvals.rejections ?? []) decisions.push({ at: r.at_utc, by: r.by, what: `rejected ${r.gate}`, detail: r.reason });
178
+ for (const a of unit.amendments) if (a.approved_at_utc) decisions.push({ at: a.approved_at_utc, by: a.by, what: `approved amendment ${a.id}`, detail: a.paths.join(', ') });
179
+ decisions.sort((a, b) => a.at.localeCompare(b.at));
180
+ // A light-mode approval stamps spec and design at the same time: one decision.
181
+ const shown = [];
182
+ for (const d of decisions) {
183
+ const prev = shown.at(-1);
184
+ if (prev && prev.at === d.at && /^approved (spec|design)$/.test(prev.what) && /^approved (spec|design)$/.test(d.what)) prev.what = 'approved spec and design';
185
+ else shown.push({ ...d });
186
+ }
187
+
188
+ const tierModel = (tier) => {
189
+ const value = config.models?.[host]?.[tier];
190
+ return !value || value === 'session' ? 'session model' : value;
191
+ };
192
+ const reviewers = ['balanced', 'deep']
193
+ .map((tier) => {
194
+ const own = reviews.filter((r) => r.tier === tier);
195
+ return {
196
+ name: tier === 'deep' ? 'agjan-reviewer-deep' : 'agjan-reviewer',
197
+ tier,
198
+ model: tierModel(tier),
199
+ count: own.length,
200
+ steps: [...new Set(own.map((r) => r.step))],
201
+ isolated: own.every((r) => r.isolation === 'agent'),
202
+ };
203
+ })
204
+ .filter((r) => r.count);
205
+ const humans = [...new Set(decisions.map((d) => d.by))];
206
+
207
+ const open = Object.values(findings).filter((f) => f.status === 'open');
208
+ return {
209
+ key: unit.key,
210
+ slug: unit.slug,
211
+ kind: unit.kind,
212
+ title: titleOf(unit),
213
+ mode: unit.design?.parsed.mode ?? null,
214
+ areas: unit.design?.parsed.areas ?? [],
215
+ onBase,
216
+ stages: stage.names,
217
+ at: stage.at,
218
+ turn: stage.turn,
219
+ now: stage.now,
220
+ start: iso(start),
221
+ end: iso(end),
222
+ last: iso(last),
223
+ host,
224
+ writer: steps.map((s) => ({ from: iso(s.from), to: iso(s.to), label: s.label })),
225
+ gates: gates.map((g) => ({ from: iso(g.from), to: iso(g.to), label: g.label.replace(/^gate /, ''), open: Boolean(g.open) })),
226
+ events: events.map((e) => ({ at: e.at_utc, event: e.event, ...Object.fromEntries(Object.entries(e).filter(([k]) => !['at_utc', 'event'].includes(k))) })),
227
+ commits,
228
+ reviews,
229
+ findings,
230
+ tasks,
231
+ acs,
232
+ decisions: shown,
233
+ reviewers,
234
+ humans,
235
+ roundLimit: roundLimit(config),
236
+ stats: {
237
+ activeMs: steps.reduce((t, s) => t + (s.to - s.from), 0),
238
+ waitingMs: gates.reduce((t, s) => t + (s.to - s.from), 0),
239
+ reviews: reviews.length,
240
+ blocked: reviews.filter((r) => r.verdict === 'blocked').length,
241
+ openFindings: open.length,
242
+ openBlockers: open.filter((f) => f.severity === 'blocker').length,
243
+ totalFindings: Object.keys(findings).length,
244
+ },
245
+ };
246
+ }
247
+
248
+ /** Every unit of the project, the units changed on this branch first. */
249
+ export function projectModels(ctx, { now = Date.now() } = {}) {
250
+ const changed = new Set(changedFeatures(ctx.root, ctx.config));
251
+ const all = listFeatures(ctx.root);
252
+ const models = [];
253
+ for (const slug of all) {
254
+ try {
255
+ models.push(unitModel(ctx, slug, { onBase: !changed.has(slug), now }));
256
+ } catch {
257
+ // A damaged unit must not stop the pages; check reports it.
258
+ }
259
+ }
260
+ const order = { you: 0, agent: 1, idle: 2, merged: 3 };
261
+ return models.sort((a, b) => order[a.turn] - order[b.turn] || b.last.localeCompare(a.last));
262
+ }
263
+
264
+ // ---------------------------------------------------------------- Markdown
265
+
266
+ const VERDICT_MD = { pass: '✅ pass', 'pass-with-notes': '🟡 notes', blocked: '⛔ blocked' };
267
+ const TURN_MD = { you: '👤 your turn', agent: '🤖 agent working', merged: '✅ merged', idle: '⏸ idle' };
268
+
269
+ function duration(ms) {
270
+ if (ms < 60_000) return `${Math.max(Math.round(ms / 1000), 0)} s`;
271
+ const m = Math.round(ms / 60_000);
272
+ if (m < 60) return `${m} min`;
273
+ const h = Math.floor(m / 60);
274
+ return h < 48 ? `${h} h ${m % 60} min` : `${Math.floor(h / 24)} d ${h % 24} h`;
275
+ }
276
+
277
+ const hm = (at) => `${at.slice(5, 10)} ${at.slice(11, 16)}`;
278
+
279
+ function track(model) {
280
+ return model.stages
281
+ .map((name, i) => (i < model.at ? `✅ ${name}` : i === model.at ? (model.turn === 'you' ? `⏳ **${name}**` : `🔄 **${name}**`) : `⬜ ${name}`))
282
+ .join(' ── ');
283
+ }
284
+
285
+ function severities(ids, findings) {
286
+ const count = {};
287
+ for (const id of ids) count[findings[id].severity] = (count[findings[id].severity] ?? 0) + 1;
288
+ return ['blocker', 'major', 'minor'].filter((k) => count[k]).map((k) => `${count[k]} ${k}`).join(', ');
289
+ }
290
+
291
+ /** The timeline rows of a unit: steps, reviews, gates, decisions and commits, in order. */
292
+ export function timelineRows(model) {
293
+ const rows = [];
294
+ for (const e of model.events) {
295
+ if (e.event === 'step') rows.push([e.at, '🤖 writer', `${[e.stage, e.task, e.role].filter(Boolean).join(' ')} started`]);
296
+ if (e.event === 'gate-requested') rows.push([e.at, '🤖 writer', `asks you to approve ${e.gate}`]);
297
+ if (e.event === 'amendment-proposed') rows.push([e.at, '🤖 writer', `proposes amendment ${e.amendment ?? ''}`.trim()]);
298
+ }
299
+ for (const r of model.reviews) {
300
+ const what = r.findings.length ? ` (${severities(r.findings, model.findings)})` : '';
301
+ rows.push([r.at, `🔍 reviewer${r.tier === 'deep' ? ' (deep)' : ''}`, `${r.step} · round ${r.round} → ${VERDICT_MD[r.verdict]}${what}`]);
302
+ }
303
+ for (const d of model.decisions) rows.push([d.at, '👤 human', `${d.what}${d.detail ? `: ${d.detail}` : ''}`]);
304
+ for (const c of model.commits) rows.push([c.at, '🤖 writer', `commit \`${c.sha}\` ${c.subject}`]);
305
+ return rows.sort((a, b) => a[0].localeCompare(b[0]));
306
+ }
307
+
308
+ /** docs/agjan/<unit>/progress.md */
309
+ export function unitMarkdown(model, { generatedAt }) {
310
+ const out = [];
311
+ const md = (s) => String(s).replace(/\|/g, '\\|');
312
+ out.push(`# ${model.key} · ${model.slug}`, '');
313
+ out.push(`<!-- Generated by agjan at ${generatedAt}. Do not edit: every agjan command regenerates it. Overview: .agjan/progress.html (npx agjan progress --open). -->`, '');
314
+ out.push(`> ${md(model.title)}`, '');
315
+ out.push(track(model), '');
316
+ out.push(`**Now:** ${TURN_MD[model.turn]} · ${md(model.now)}`, '');
317
+ const s = model.stats;
318
+ out.push('| | |', '|---|---|');
319
+ out.push(`| Time | ${duration(s.activeMs)} agent work · ${duration(s.waitingMs)} waiting for a human |`);
320
+ if (model.tasks.length) out.push(`| Tasks | ${model.tasks.filter((t) => t.done).length}/${model.tasks.length} committed |`);
321
+ if (model.acs) {
322
+ const tested = model.acs.passing === null ? `${model.acs.withTests}/${model.acs.automated} with tests` : `${model.acs.passing}/${model.acs.automated} with passing tests`;
323
+ out.push(`| Acceptance criteria | ${model.acs.total}: ${tested}${model.acs.manual.length ? ` · manual: ${model.acs.manual.join(', ')}` : ''} |`);
324
+ }
325
+ out.push(`| Reviews | ${s.reviews} · ${s.blocked} blocked · findings ${s.openFindings} open of ${s.totalFindings}, ${s.openBlockers} blocker(s) |`);
326
+ const agents = [model.host ? `writer: ${model.host}` : null, ...model.reviewers.map((r) => `${r.name} (${r.model}${r.isolated ? ', isolated' : ''})`)].filter(Boolean);
327
+ if (agents.length) out.push(`| Agents | ${agents.join(' · ')} |`);
328
+ if (model.humans.length) out.push(`| People | ${model.humans.join(', ')} |`);
329
+ out.push('');
330
+
331
+ const steps = [...new Set(model.reviews.map((r) => r.step))];
332
+ if (steps.length) {
333
+ out.push('## Review loops', '', '| Step | Rounds | Course |', '|---|---|---|');
334
+ for (const step of steps) {
335
+ const rs = model.reviews.filter((r) => r.step === step);
336
+ const course = rs
337
+ .map((r, i) => `${i && r.round === 1 ? '↺ ' : i ? '→ ' : ''}${r.id} ${VERDICT_MD[r.verdict]}${r.findings.length ? ` (${severities(r.findings, model.findings)})` : ''}`)
338
+ .join(' ');
339
+ out.push(`| ${step} | ${rs.length} (limit ${model.roundLimit} per loop) | ${course} |`);
340
+ }
341
+ out.push('');
342
+ }
343
+
344
+ if (model.tasks.length) {
345
+ out.push('## Tasks', '', '| Task | Area | Title | Commits | Reviews |', '|---|---|---|---|---|');
346
+ for (const t of model.tasks) {
347
+ out.push(`| ${t.done ? '✅' : '⬜'} ${t.id} | ${t.area} | ${md(t.title)} | ${t.commits.map((c) => `\`${c}\``).join(' ') || '-'} | ${t.reviews.join(', ') || '-'} |`);
348
+ }
349
+ out.push('');
350
+ }
351
+
352
+ const rows = timelineRows(model);
353
+ out.push('## Timeline (UTC)', '');
354
+ const table = (list) => ['| Time | Who | What |', '|---|---|---|', ...list.map(([at, who, what]) => `| ${hm(at)} | ${who} | ${md(what)} |`)];
355
+ if (rows.length > 30) {
356
+ out.push(...table(rows.slice(-30)), '', `<details><summary>${rows.length - 30} earlier events</summary>`, '', ...table(rows.slice(0, -30)), '', '</details>', '');
357
+ } else {
358
+ out.push(...table(rows), '');
359
+ }
360
+
361
+ const ids = Object.keys(model.findings);
362
+ if (ids.length) {
363
+ out.push('## Findings', '', '| Id | Severity | Status | Issue |', '|---|---|---|---|');
364
+ const order = { open: 0, accepted: 1, resolved: 2 };
365
+ for (const id of ids.sort((a, b) => order[model.findings[a].status] - order[model.findings[b].status])) {
366
+ const f = model.findings[id];
367
+ const status = f.status === 'resolved' ? `resolved (${f.resolvedBy})` : f.status === 'accepted' ? `accepted: ${md(f.acceptReason)}` : 'open';
368
+ out.push(`| ${id} | ${f.severity} | ${status} | ${md(f.issue)}${f.file ? ` (\`${f.file}\`)` : ''} |`);
369
+ }
370
+ out.push('');
371
+ }
372
+ return `${out.join('\n').trimEnd()}\n`;
373
+ }
374
+
375
+ /** .agjan/progress.md */
376
+ export function overviewMarkdown(models, { generatedAt, project }) {
377
+ const out = [`# ${project} · agjan progress`, '', `<!-- Generated by agjan at ${generatedAt}. Local, not committed. Open .agjan/progress.html for the visual view. -->`, ''];
378
+ if (!models.length) return `${[...out, 'No features, fixes or map runs yet.'].join('\n')}\n`;
379
+ out.push('| Unit | Kind | Stage | Now | Last activity |', '|---|---|---|---|---|');
380
+ for (const m of models) {
381
+ const stage = m.stages[Math.min(m.at, m.stages.length - 1)];
382
+ out.push(`| [${m.key} · ${m.slug}](../${FEATURES_DIR}/${m.slug}/${PROGRESS_MD}) | ${m.kind}${m.mode ? ` (${m.mode})` : ''} | ${stage} | ${TURN_MD[m.turn]} · ${m.now.replace(/\|/g, '\\|')} | ${hm(m.last)} |`);
383
+ }
384
+ return `${out.join('\n')}\n`;
385
+ }
386
+
387
+ /** .agjan/progress.html: the template with the models as JSON. */
388
+ export function progressHtml(models, { generatedAt, project, kit }) {
389
+ const data = JSON.stringify({ project, generatedAt, kit, units: models }).replace(/</g, '\\u003c');
390
+ return readFileSync(TEMPLATE, 'utf8').replace('/*AGJAN_PROGRESS_DATA*/null', data);
391
+ }
392
+
393
+ /**
394
+ * Regenerates the progress pages. `only` limits the unit pages written (all units still
395
+ * feed the overview). Never throws: the pages must not break the command that triggered them.
396
+ */
397
+ export function writeProgress(ctx, { only = null, now = Date.now() } = {}) {
398
+ try {
399
+ const models = projectModels(ctx, { now });
400
+ const generatedAt = iso(now);
401
+ const project = ctx.root.split(/[\\/]/).filter(Boolean).at(-1);
402
+ for (const m of models) {
403
+ // Only units worked on this branch: a page for a unit on the base branch would be a
404
+ // change to another unit here (it got its page while it was worked on).
405
+ if (m.onBase || (only && !only.includes(m.slug))) continue;
406
+ const file = join(ctx.root, FEATURES_DIR, m.slug, PROGRESS_MD);
407
+ writeFileSync(file, unitMarkdown(m, { generatedAt }));
408
+ }
409
+ const dir = join(ctx.root, LOCAL_DIR);
410
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
411
+ writeFileSync(join(dir, 'progress.md'), overviewMarkdown(models, { generatedAt, project }));
412
+ writeFileSync(join(dir, 'progress.html'), progressHtml(models, { generatedAt, project, kit: ctx.kit }));
413
+ return { models, html: join(dir, 'progress.html') };
414
+ } catch {
415
+ return null;
416
+ }
417
+ }
418
+
419
+ /** For the log listener: regenerate after an event in `unitDir` (root and config from the path). */
420
+ export function refreshAfterEvent(unitDir, kit) {
421
+ const marker = `${join('/', FEATURES_DIR)}`.replace(/\\/g, '/');
422
+ const normalized = unitDir.replace(/\\/g, '/');
423
+ const index = normalized.lastIndexOf(marker.replace(/^\//, '/'));
424
+ if (index === -1) return;
425
+ const root = unitDir.slice(0, index);
426
+ const slug = normalized.slice(index + marker.length + 1);
427
+ try {
428
+ const ctx = { root, config: loadConfig(root), kit };
429
+ writeProgress(ctx, { only: [slug] });
430
+ } catch {
431
+ // never break the command
432
+ }
433
+ }
434
+
package/src/review.mjs CHANGED
@@ -25,7 +25,7 @@ const VERDICTS = ['pass', 'pass-with-notes', 'blocked'];
25
25
 
26
26
  /** Script-owned files of a feature: they change during a review by design. */
27
27
  function scriptOwned(slug) {
28
- return new Set([APPROVALS_FILE, REVIEWS_FILE, REVIEW_MD, LOG_FILE, 'report.md', 'fix.json', 'fix.md'].map((f) => `${FEATURES_DIR}/${slug}/${f}`));
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
29
  }
30
30
 
31
31
  /**
@@ -138,8 +138,8 @@ function openFindings(feature, steps) {
138
138
 
139
139
  const CHECKLISTS = {
140
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, every AC covered.',
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. Nothing beyond the spec.',
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.',
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). Nothing beyond the spec.',
143
143
  build: 'Each covered AC is met by the diff. Tests exist and carry the AC id in their names. 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. 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
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
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.',
@@ -169,10 +169,20 @@ function scopeText(scope) {
169
169
  ].join('\n');
170
170
  }
171
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
+
172
177
  /** Builds the reviewer's input for a step: the only material the reviewer should read. */
173
178
  export function buildContextText(root, config, feature, parsed) {
174
179
  const base = resolveBase(root, config.git?.base);
175
- const parts = [`# Review context: ${feature.slug} (${feature.key}), step ${parsed.step}`, ''];
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
+ ];
176
186
  parts.push(section('Checklist', CHECKLISTS[parsed.kind]));
177
187
  const baseline = join(root, FEATURES_DIR, 'project.md');
178
188
  const baselineText = existsSync(baseline) ? readFileSync(baseline, 'utf8') : null;
@@ -194,12 +204,12 @@ export function buildContextText(root, config, feature, parsed) {
194
204
  } else if (!feature.spec) {
195
205
  throw new AgjanError('spec.md does not exist');
196
206
  } else if (parsed.kind === 'spec') {
197
- parts.push(section('spec.md', fence(feature.spec.text, 'md')));
207
+ parts.push(section(docPath(feature, 'spec.md'), fence(feature.spec.text, 'md')));
198
208
  } else if (parsed.kind === 'design' || parsed.kind === 'design:light') {
199
209
  if (!feature.design || !feature.tasks) throw new AgjanError('design.md and tasks.md must exist for a design review');
200
- parts.push(section('spec.md', fence(feature.spec.text, 'md')));
201
- parts.push(section('design.md', fence(feature.design.text, 'md')));
202
- parts.push(section('tasks.md', fence(feature.tasks.text, 'md')));
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')));
203
213
  } else if (parsed.kind === 'build') {
204
214
  const ids = new Set(parsed.tasks.flatMap((t) => t.covers));
205
215
  const scope = scopeOf(config, feature, parsed.tasks);
@@ -219,8 +229,8 @@ export function buildContextText(root, config, feature, parsed) {
219
229
  const changed = changedFiles(root, base).filter((f) => !scriptOwned(feature.slug).has(f) && !f.startsWith('.agjan/'));
220
230
  parts.push(section('Acceptance criteria', acsText(feature)));
221
231
  parts.push(section('AC coverage (test files mentioning the AC id, and test results)', `| AC | verification | test files | result |\n|---|---|---|---|\n${coverage}`));
222
- parts.push(section('design.md', fence(feature.design.text, 'md')));
223
- parts.push(section('tasks.md', fence(feature.tasks.text, 'md')));
232
+ parts.push(section(docPath(feature, 'design.md'), fence(feature.design.text, 'md')));
233
+ parts.push(section(docPath(feature, 'tasks.md'), fence(feature.tasks.text, 'md')));
224
234
  parts.push(section('Allowed paths (scope, enforced by agjan check)', scopeText(scopeOf(config, feature, feature.tasks.parsed.tasks))));
225
235
  parts.push(section('Changed files', changed.map((f) => `- ${f}`).join('\n') || '(none)'));
226
236
  parts.push(section('Full diff', fence(diffOf(root, base, changed), 'diff')));
@@ -232,7 +242,8 @@ export function buildContextText(root, config, feature, parsed) {
232
242
  section(
233
243
  'How to record your result',
234
244
  'Call review_record with this context_id, a verdict (pass, pass-with-notes, blocked), your findings ' +
235
- '(severity blocker, major or minor; file and line where possible; issue; suggestion), and in `resolves` the ids ' +
245
+ '(severity blocker, major or minor; file and line where possible, with the repository paths used in this context; ' +
246
+ 'issue; suggestion; evidence for a claim that an API, annotation or syntax is wrong), and in `resolves` the ids ' +
236
247
  'of open findings that this change has fixed. A blocker finding requires the verdict blocked.',
237
248
  ),
238
249
  );
@@ -309,7 +320,8 @@ function validFinding(f, i) {
309
320
  if (f.file !== undefined && (typeof f.file !== 'string' || f.file.includes('\\'))) return `${where}.file must be a POSIX path`;
310
321
  if (f.line !== undefined && !(Number.isInteger(f.line) && f.line > 0)) return `${where}.line must be a positive integer`;
311
322
  if (f.suggestion !== undefined && typeof f.suggestion !== 'string') return `${where}.suggestion must be a string`;
312
- const extra = Object.keys(f).filter((k) => !['severity', 'file', 'line', 'issue', 'suggestion'].includes(k));
323
+ if (f.evidence !== undefined && typeof f.evidence !== 'string') return `${where}.evidence must be a string`;
324
+ const extra = Object.keys(f).filter((k) => !['severity', 'file', 'line', 'issue', 'suggestion', 'evidence'].includes(k));
313
325
  if (extra.length) return `${where} has unknown field(s): ${extra.join(', ')}`;
314
326
  return null;
315
327
  }
@@ -393,6 +405,7 @@ export function renderReviewMd(feature) {
393
405
  out.push(`- **${f.id}** [${f.severity}]${where} (${status.get(f.id)})`);
394
406
  out.push(` - Issue: ${f.issue}`);
395
407
  if (f.suggestion) out.push(` - Suggestion: ${f.suggestion}`);
408
+ if (f.evidence) out.push(` - Evidence: ${f.evidence}`);
396
409
  }
397
410
  if (r.findings?.length) out.push('');
398
411
  }
package/src/ui.mjs CHANGED
@@ -26,10 +26,19 @@ export function colorEnabled(stream, env = process.env) {
26
26
  /** Style functions for one stream: `s.red('text')`; identity functions when colors are off. */
27
27
  export function createStyle(stream, env = process.env) {
28
28
  const enabled = colorEnabled(stream, env);
29
- const style = { enabled, truecolor: enabled && /^(truecolor|24bit)$/i.test(env.COLORTERM ?? '') };
29
+ const style = {
30
+ enabled,
31
+ truecolor: enabled && /^(truecolor|24bit)$/i.test(env.COLORTERM ?? ''),
32
+ // The agjan mark: on a terminal (also with NO_COLOR, then without colors), never for
33
+ // agents, pipes or CI; AGJAN_BANNER=0 turns it off.
34
+ brand: env.AGJAN_BANNER !== '0' && (enabled || Boolean(stream?.isTTY)),
35
+ };
30
36
  for (const [name, [open, close]] of Object.entries(CODES)) {
31
37
  style[name] = enabled ? (text) => `\x1b[${open}m${text}\x1b[${close}m` : (text) => String(text);
32
38
  }
39
+ // Brand teal (#2EC4A0); cyan where the terminal has no true color.
40
+ style.teal = !enabled ? (text) => String(text) : style.truecolor ? (text) => `\x1b[38;2;46;196;160m${text}\x1b[39m` : style.cyan;
41
+ style.violet = !enabled ? (text) => String(text) : style.truecolor ? (text) => `\x1b[38;2;168;145;245m${text}\x1b[39m` : style.magenta;
33
42
  return style;
34
43
  }
35
44
 
@@ -82,29 +91,24 @@ export function highlightMarkdown(style, text) {
82
91
  .join('\n');
83
92
  }
84
93
 
85
- const LOGO = ['▄▀█ █▀▀ █ ▄▀█ █▄ █', '█▀█ █▄█ █▄█ █▀█ █ ▀█'];
86
-
87
- /** Blue to teal, left to right. */
88
- function gradient(style, line) {
89
- if (!style.truecolor) return style.cyan(line);
90
- const from = [0, 112, 242];
91
- const to = [0, 200, 180];
92
- const n = Math.max(line.length - 1, 1);
93
- let out = '';
94
- for (let i = 0; i < line.length; i++) {
95
- const [r, g, b] = from.map((c, k) => Math.round(c + ((to[k] - c) * i) / n));
96
- out += line[i] === ' ' ? ' ' : `\x1b[38;2;${r};${g};${b}m${line[i]}`;
97
- }
98
- return `${out}\x1b[39m`;
99
- }
100
-
101
- /** The agjan logo with the version and a tagline beside it; empty when colors are off. */
102
- export function banner(style, version) {
103
- if (!style.enabled) return [];
94
+ /**
95
+ * The agjan mark (the "ag" of the app icon: the bowl of the a with its teal stem, and the
96
+ * g with its descender) with two lines of text beside it. Empty when the brand is off.
97
+ */
98
+ export function mark(style, version, line2 = 'spec-driven work with AI agents, gated by you', line3 = '') {
99
+ if (!style.brand) return [];
100
+ const stem = style.teal('┃');
104
101
  return [
105
102
  '',
106
- ` ${gradient(style, LOGO[0])} ${style.bold(`agjan ${version}`)}`,
107
- ` ${gradient(style, LOGO[1])} ${style.gray('spec-driven workflow with human gates')}`,
103
+ ` ╭─╮${stem}╭─╮╷ ${style.bold('agjan')} ${version}`,
104
+ ` ╰─╯${stem}╰─╯│ ${line2}`,
105
+ ` ╶─╯ ${line3 ? style.gray(line3) : ''}`.trimEnd(),
108
106
  '',
109
107
  ];
110
108
  }
109
+
110
+ /** The one-line mark for frequent commands: `┃ agjan 0.0.6 · status`. Empty when the brand is off. */
111
+ export function markLine(style, version, what) {
112
+ if (!style.brand) return [];
113
+ return [`${style.teal('┃')} ${style.bold('agjan')} ${style.gray(`${version} · ${what}`)}`];
114
+ }