agjan 0.0.10 → 0.0.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/README.md +2 -2
  2. package/bin/agjan.mjs +9 -2
  3. package/dist/adapters/claude-code.js +105 -0
  4. package/dist/adapters/copilot.js +80 -0
  5. package/dist/auto.js +24 -0
  6. package/dist/baseline.js +66 -0
  7. package/dist/browser.js +46 -0
  8. package/dist/cli.js +164 -0
  9. package/dist/commands/branch.js +71 -0
  10. package/dist/commands/check.js +420 -0
  11. package/dist/commands/fix.js +122 -0
  12. package/dist/commands/gates.js +462 -0
  13. package/dist/commands/lint.js +76 -0
  14. package/dist/commands/log.js +72 -0
  15. package/dist/commands/map.js +47 -0
  16. package/dist/commands/new.js +65 -0
  17. package/dist/commands/pr-summary.js +168 -0
  18. package/dist/commands/progress.js +42 -0
  19. package/dist/commands/report.js +105 -0
  20. package/dist/commands/review.js +146 -0
  21. package/dist/commands/setup.js +393 -0
  22. package/dist/commands/status.js +303 -0
  23. package/dist/commands/ui-test.js +39 -0
  24. package/dist/config.js +110 -0
  25. package/dist/context.js +56 -0
  26. package/dist/copilot-mcp.js +56 -0
  27. package/dist/documents.js +207 -0
  28. package/dist/errors.js +15 -0
  29. package/dist/feature.js +221 -0
  30. package/dist/fix.js +117 -0
  31. package/dist/git.js +88 -0
  32. package/{src/hash.mjs → dist/hash.js} +11 -14
  33. package/dist/hook.js +47 -0
  34. package/dist/json-file.js +26 -0
  35. package/dist/log.js +50 -0
  36. package/dist/managed.js +182 -0
  37. package/dist/mcp-config.js +76 -0
  38. package/dist/mcp.js +142 -0
  39. package/dist/plan.js +40 -0
  40. package/dist/progress-view.js +494 -0
  41. package/dist/progress.js +106 -0
  42. package/{src/review-policy.mjs → dist/review-policy.js} +39 -47
  43. package/dist/review.js +435 -0
  44. package/dist/scope.js +30 -0
  45. package/dist/terminal.js +127 -0
  46. package/dist/test-results.js +101 -0
  47. package/dist/tests-map.js +29 -0
  48. package/dist/types.js +5 -0
  49. package/dist/ui.js +136 -0
  50. package/dist/usage.js +116 -0
  51. package/dist/validate.js +46 -0
  52. package/docs/guide.md +98 -37
  53. package/kit/domains/btp/domain.json +4 -4
  54. package/kit/hooks/guard.mjs +48 -119
  55. package/kit/skills/agjan-build/SKILL.md +14 -8
  56. package/kit/skills/agjan-design/SKILL.md +42 -6
  57. package/kit/skills/agjan-fix/SKILL.md +9 -10
  58. package/kit/skills/agjan-map/SKILL.md +9 -10
  59. package/kit/skills/agjan-spec/SKILL.md +22 -11
  60. package/kit/skills/agjan-verify/SKILL.md +46 -19
  61. package/kit/skills/cap-developer/SKILL.md +10 -2
  62. package/kit/skills/cap-developer/references/handlers.md +11 -9
  63. package/kit/skills/cap-developer/references/project-setup.md +21 -8
  64. package/kit/skills/cap-developer/references/testing.md +38 -14
  65. package/kit/skills/cap-developer/references/typescript.md +143 -0
  66. package/kit/skills/cap-developer/references/validation-security.md +26 -8
  67. package/kit/skills/fiori-developer/SKILL.md +20 -5
  68. package/kit/skills/fiori-developer/references/app-setup.md +91 -16
  69. package/kit/skills/fiori-developer/references/elements.md +19 -5
  70. package/kit/skills/fiori-developer/references/freestyle-ts.md +5 -1
  71. package/kit/skills/fiori-developer/references/testing.md +109 -15
  72. package/kit/templates/agents-block.md +7 -3
  73. package/package.json +11 -3
  74. package/schemas/approvals.schema.json +23 -2
  75. package/schemas/config.schema.json +0 -5
  76. package/schemas/log.schema.json +1 -1
  77. package/src/adapters/claude-code.mjs +0 -121
  78. package/src/adapters/copilot.mjs +0 -89
  79. package/src/baseline.mjs +0 -66
  80. package/src/cli.mjs +0 -155
  81. package/src/commands/branch.mjs +0 -60
  82. package/src/commands/check.mjs +0 -365
  83. package/src/commands/fix.mjs +0 -116
  84. package/src/commands/gates.mjs +0 -264
  85. package/src/commands/lint.mjs +0 -74
  86. package/src/commands/log.mjs +0 -60
  87. package/src/commands/map.mjs +0 -47
  88. package/src/commands/new.mjs +0 -53
  89. package/src/commands/pr-summary.mjs +0 -137
  90. package/src/commands/progress.mjs +0 -40
  91. package/src/commands/report.mjs +0 -115
  92. package/src/commands/review.mjs +0 -76
  93. package/src/commands/setup.mjs +0 -383
  94. package/src/commands/status.mjs +0 -248
  95. package/src/config.mjs +0 -122
  96. package/src/context.mjs +0 -67
  97. package/src/copilot-mcp.mjs +0 -56
  98. package/src/documents.mjs +0 -188
  99. package/src/errors.mjs +0 -16
  100. package/src/feature.mjs +0 -225
  101. package/src/fix.mjs +0 -108
  102. package/src/git.mjs +0 -83
  103. package/src/hook.mjs +0 -48
  104. package/src/json-file.mjs +0 -24
  105. package/src/log.mjs +0 -51
  106. package/src/managed.mjs +0 -178
  107. package/src/mcp-config.mjs +0 -83
  108. package/src/mcp.mjs +0 -147
  109. package/src/plan.mjs +0 -45
  110. package/src/progress-view.mjs +0 -466
  111. package/src/progress.mjs +0 -85
  112. package/src/review.mjs +0 -413
  113. package/src/scope.mjs +0 -30
  114. package/src/terminal.mjs +0 -118
  115. package/src/test-results.mjs +0 -111
  116. package/src/tests-map.mjs +0 -29
  117. package/src/ui.mjs +0 -136
  118. package/src/usage.mjs +0 -118
  119. package/src/validate.mjs +0 -41
@@ -0,0 +1,494 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { git } from './git.js';
4
+ import { loadConfig } from './config.js';
5
+ import { FEATURES_DIR, changedFeatures, listFeatures, loadFeature, stillBlocked } from './feature.js';
6
+ import { readLog } from './log.js';
7
+ import { acceptanceState, buildProgress, verifyState } from './progress.js';
8
+ import { reviewerFor, roundLimit } from './review-policy.js';
9
+ import { acTestFiles } from './tests-map.js';
10
+ import { acResults, loadResults } from './test-results.js';
11
+ import { freshReview } from './fix.js';
12
+ import { spans } from './commands/report.js';
13
+ /**
14
+ * Progress pages (design decision 66): what happened in each unit (feature, fix, map run),
15
+ * who worked on it, how the review loops went, and whose turn it is. agjan regenerates them
16
+ * after every event it records:
17
+ * - docs/agjan/<unit>/progress.md: committed with the unit, visible in the pull request;
18
+ * - .agjan/progress.md and .agjan/progress.html: the project overview, local (not
19
+ * committed, so parallel branches do not conflict). The HTML is self-contained.
20
+ */
21
+ export const PROGRESS_MD = 'progress.md';
22
+ const LOCAL_DIR = '.agjan';
23
+ const TEMPLATE = new URL('../kit/templates/progress.html', import.meta.url);
24
+ const iso = (ms) => new Date(ms).toISOString().replace(/\.\d{3}Z$/, 'Z');
25
+ /** The unit's title: the first sentence of the spec's Summary, the fix's description, or the map run. */
26
+ function titleOf(unit) {
27
+ if (unit.kind === 'fix') {
28
+ const fix = JSON.parse(readFileSyncSafe(join(unit.dir, 'fix.json')) || '{}');
29
+ return fix.what ?? unit.slug;
30
+ }
31
+ if (unit.kind === 'map')
32
+ return 'Map of the application (docs/agjan/project.md)';
33
+ const lines = (unit.spec?.text ?? '').split('\n');
34
+ const start = lines.findIndex((l) => l.trim() === '## Summary');
35
+ const text = start === -1 ? '' : lines.slice(start + 1).find((l) => l.trim() && !l.startsWith('#')) ?? '';
36
+ const sentence = text.split(/(?<=\.)\s/)[0].trim();
37
+ return sentence.length > 110 ? `${sentence.slice(0, 107)}…` : sentence || unit.slug;
38
+ }
39
+ function readFileSyncSafe(file) {
40
+ try {
41
+ return readFileSync(file, 'utf8');
42
+ }
43
+ catch {
44
+ return '';
45
+ }
46
+ }
47
+ /** Commits of the unit anywhere in the history: subjects starting with `<KEY>:` or `<KEY>-T<n>:`. */
48
+ function unitCommits(root, key) {
49
+ const log = git(root, ['log', '--format=%h%x09%cI%x09%s', 'HEAD'], { allowFail: true }) ?? '';
50
+ const pattern = new RegExp(`^${key}(-T[1-9][0-9]*)?:`);
51
+ return log
52
+ .split('\n')
53
+ .filter(Boolean)
54
+ .map((line) => line.split('\t'))
55
+ .filter(([, , subject]) => pattern.test(subject ?? ''))
56
+ .map(([sha, at, subject]) => ({ sha, at: iso(Date.parse(at)), subject }))
57
+ .reverse();
58
+ }
59
+ /** Stage track and whose turn it is. */
60
+ function stageOf(ctx, unit, onBase, extra) {
61
+ const { review } = extra;
62
+ if (unit.kind !== 'feature') {
63
+ const names = unit.kind === 'fix' ? ['Fix', 'Review', 'Merged'] : ['Map', 'Review', 'Merged'];
64
+ const last = unit.reviews.records.at(-1);
65
+ if (onBase && last && !stillBlocked(unit, last))
66
+ return { names, at: 3, turn: 'merged', now: 'merged' };
67
+ if (review && !review.problem)
68
+ return { names, at: 2, turn: 'you', now: 'review and merge the pull request' };
69
+ if (last)
70
+ return { names, at: 1, turn: 'agent', now: review?.problem ?? 'review' };
71
+ return { names, at: 0, turn: 'agent', now: unit.kind === 'fix' ? 'making the change' : 'writing docs/agjan/project.md' };
72
+ }
73
+ const mode = unit.design?.parsed.mode;
74
+ const names = ['Spec', mode === 'light' ? 'Design (light)' : 'Design', 'Build', 'Verify', onBase ? 'Merged' : 'Done'];
75
+ const events = readLog(unit.dir);
76
+ const lastGate = events.filter((e) => ['gate-requested', 'approved', 'rejected'].includes(e.event)).at(-1);
77
+ const waiting = lastGate?.event === 'gate-requested';
78
+ // A step runs once the skill logged its start after the approval it builds on; until then
79
+ // the agent has stopped and the human starts the next skill (design decision 70).
80
+ const startedSince = (stage, at) => events.some((e) => e.event === 'step' && e.stage === stage && (!at || e.at_utc >= at));
81
+ const lastStep = events.filter((e) => e.event === 'step').at(-1);
82
+ if (unit.stage === 'spec') {
83
+ 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' };
84
+ }
85
+ if (unit.stage === 'design') {
86
+ if (waiting)
87
+ return { names, at: 1, turn: 'you', now: 'approve the design in a terminal (npx agjan approve design)' };
88
+ if (!startedSince('design', unit.approvals.approvals.spec?.at_utc))
89
+ return unit.approvals.auto ? { names, at: 1, turn: 'agent', now: 'auto mode: the design is next' } : { names, at: 1, turn: 'you', now: 'start the design: /agjan-design' };
90
+ return { names, at: 1, turn: 'agent', now: 'writing and reviewing the design' };
91
+ }
92
+ // In Build a feature always has its tasks and a verify state.
93
+ const progress = extra.progress;
94
+ const verify = extra.verify;
95
+ const pending = unit.amendments.filter((a) => a.status === 'pending');
96
+ const verified = progress.complete && progress.due.length === 0 && verify.state === 'current';
97
+ if (onBase && progress.complete && verify.record && !stillBlocked(unit, verify.record))
98
+ return { names, at: 5, turn: 'merged', now: 'merged' };
99
+ if (verified) {
100
+ if (acceptanceState(ctx.root, ctx.config, unit, verify).state === 'accepted')
101
+ return { names, at: 5, turn: 'done', now: 'implemented, verified and accepted' };
102
+ const manual = unit.spec.parsed.acs.filter((ac) => ac.verification === 'manual').map((ac) => ac.id);
103
+ return { names, at: 4, turn: 'you', now: `verified: ${manual.length ? `check ${manual.join(', ')} by hand, then ` : ''}accept it in a terminal (npx agjan approve verify)` };
104
+ }
105
+ if (pending.length)
106
+ return { names, at: 2, turn: 'you', now: `approve amendment ${pending[0].id} (npx agjan approve amendment ${pending[0].id})` };
107
+ const building = startedSince('build', unit.approvals.approvals.design?.at_utc);
108
+ if (!progress.complete || progress.due.length) {
109
+ if (!building)
110
+ return unit.approvals.auto ? { names, at: 2, turn: 'agent', now: 'auto mode: the build is next' } : { names, at: 2, turn: 'you', now: 'start the build: /agjan-build' };
111
+ return { names, at: 2, turn: 'agent', now: progress.next ? `task ${progress.next.id}: ${progress.next.title}` : `review ${progress.due[0].step}` };
112
+ }
113
+ if (lastStep?.stage !== 'verify')
114
+ return unit.approvals.auto ? { names, at: 3, turn: 'agent', now: 'auto mode: the verification is next' } : { names, at: 3, turn: 'you', now: 'start the verification: /agjan-verify' };
115
+ return { names, at: 3, turn: 'agent', now: verify.state === 'none' ? 'verify' : `verify (${verify.state})` };
116
+ }
117
+ /**
118
+ * While the agent would be working, a `waiting` event after its last step means it stopped
119
+ * for the user (an error it cannot resolve, a decision): their turn, with the reason.
120
+ */
121
+ function waitingFor(events, stage) {
122
+ if (stage.turn !== 'agent')
123
+ return stage;
124
+ const last = events.filter((e) => ['step', 'waiting', 'gate-requested', 'approved', 'rejected'].includes(e.event)).at(-1);
125
+ return last?.event === 'waiting' ? { ...stage, turn: 'you', now: last.reason ?? '' } : stage;
126
+ }
127
+ /**
128
+ * What the human does after Verify: before the acceptance, try it, check the manual ACs
129
+ * and accept it (Gate 3, decision 77); the pull request is optional (decision 70).
130
+ */
131
+ export function finalSteps(root, unit, { manual = [], accepted = false } = {}) {
132
+ const project = readFileSyncSafe(join(root, FEATURES_DIR, 'project.md'));
133
+ const tryIt = /^## Run locally\s*$/m.test(project) ? 'try it locally: docs/agjan/project.md, section "Run locally" (start command, URL, users)' : 'try it locally';
134
+ const pr = 'open a pull request (ask the agent: "open the PR"), review it, merge it';
135
+ if (accepted)
136
+ return { yours: [], optional: [tryIt, pr] };
137
+ return {
138
+ yours: [tryIt, ...(manual.length ? [`check by hand: ${manual.join(', ')}`] : []), 'accept it: npx agjan approve verify'],
139
+ optional: [pr],
140
+ };
141
+ }
142
+ /** The data of one unit for the progress pages. */
143
+ export function unitModel(ctx, slug, { onBase = false, now = Date.now() } = {}) {
144
+ const unit = loadFeature(ctx.root, slug);
145
+ const config = ctx.config;
146
+ const events = readLog(unit.dir);
147
+ const isFeature = unit.kind === 'feature';
148
+ const progress = isFeature && unit.tasks ? buildProgress(ctx.root, config, unit, { history: onBase }) : null;
149
+ const verify = isFeature ? verifyState(ctx.root, config, unit) : null;
150
+ const review = !isFeature ? freshReview(ctx.root, config, unit, unit.kind) : null;
151
+ const stage = waitingFor(events, stageOf(ctx, unit, onBase, { progress, verify, review }));
152
+ const commits = unitCommits(ctx.root, unit.key);
153
+ const times = [...events.map((e) => Date.parse(e.at_utc)), ...commits.map((c) => Date.parse(c.at))].filter(Number.isFinite);
154
+ const start = times.length ? Math.min(...times) : now;
155
+ const last = times.length ? Math.max(...times) : now;
156
+ // An open step runs until now only while the agent works; when it is a human's turn,
157
+ // the agent's work ended with the last activity and the rest is waiting.
158
+ const end = stage.turn === 'merged' || stage.turn === 'done' ? last : Math.max(last, now);
159
+ const list = spans(events, stage.turn === 'agent' ? end : last).map((s) => (s.kind === 'gate' && s.open ? { ...s, to: end } : s));
160
+ const steps = list.filter((s) => s.kind === 'step');
161
+ const gates = list.filter((s) => s.kind === 'gate');
162
+ const host = unit.reviews.records.find((r) => r.reviewer?.host)?.reviewer.host ?? events.find((e) => e.host)?.host ?? null;
163
+ const reviews = unit.reviews.records.map((r) => ({
164
+ id: r.id,
165
+ step: r.step,
166
+ round: r.round,
167
+ verdict: r.verdict,
168
+ at: r.at_utc,
169
+ tier: reviewerFor(config, r.step) === 'agjan-reviewer-deep' ? 'deep' : 'balanced',
170
+ host: r.reviewer?.host ?? null,
171
+ isolation: r.reviewer?.isolation ?? null,
172
+ findings: (r.findings ?? []).map((f) => f.id),
173
+ resolves: r.resolves ?? [],
174
+ }));
175
+ const resolvedBy = {};
176
+ for (const r of reviews)
177
+ for (const id of r.resolves)
178
+ resolvedBy[id] = r.id;
179
+ const accepted = new Map(unit.approvals.accepted.map((a) => [a.finding, a]));
180
+ const findings = {};
181
+ for (const f of unit.findings) {
182
+ findings[f.id] = {
183
+ severity: f.severity,
184
+ file: f.file ?? null,
185
+ issue: f.issue,
186
+ evidence: f.evidence ?? null,
187
+ status: f.status,
188
+ raisedBy: f.record,
189
+ resolvedBy: resolvedBy[f.id] ?? null,
190
+ acceptReason: accepted.get(f.id)?.reason ?? null,
191
+ };
192
+ }
193
+ const tasks = (progress?.tasks ?? []).map((t) => ({
194
+ id: t.id,
195
+ area: t.areaName,
196
+ title: t.title,
197
+ covers: t.covers,
198
+ done: Boolean(t.commit),
199
+ commits: commits.filter((c) => c.subject.startsWith(`${unit.key}-${t.id}:`)).map((c) => c.sha),
200
+ reviews: reviews.filter((r) => r.step === `build:${t.areaName}` || r.step === `build:${t.id}`).map((r) => r.id),
201
+ }));
202
+ let acs = null;
203
+ if (isFeature && unit.spec) {
204
+ const areaNames = [...new Set(tasks.map((t) => t.area))];
205
+ const automated = unit.spec.parsed.acs.filter((ac) => ac.verification !== 'manual');
206
+ const loaded = loadResults(ctx.root, config, areaNames);
207
+ const results = loaded.files.length ? acResults(loaded, unit.key) : null;
208
+ const tests = acTestFiles(ctx.root, config, areaNames, unit.key);
209
+ acs = {
210
+ total: unit.spec.parsed.acs.length,
211
+ automated: automated.length,
212
+ manual: unit.spec.parsed.acs.filter((ac) => ac.verification === 'manual').map((ac) => ac.id),
213
+ withTests: automated.filter((ac) => tests.has(ac.id)).length,
214
+ passing: results ? automated.filter((ac) => results.get(ac.id)?.passed && !results.get(ac.id)?.failed).length : null,
215
+ };
216
+ }
217
+ const decisions = [];
218
+ for (const [gate, a] of Object.entries(unit.approvals.approvals)) {
219
+ const by = 'enabled_by' in a && a.by === 'auto' ? `auto mode (switched on by ${a.enabled_by})` : a.by;
220
+ decisions.push({ at: a.at_utc, by, what: gate === 'verify' ? 'accepted the feature' : `approved ${gate}` });
221
+ }
222
+ for (const a of unit.approvals.accepted)
223
+ decisions.push({ at: a.at_utc, by: a.by, what: `accepted ${a.finding}`, detail: a.reason });
224
+ for (const r of unit.approvals.rejections ?? [])
225
+ decisions.push({ at: r.at_utc, by: r.by, what: `rejected ${r.gate}`, detail: r.reason });
226
+ for (const a of unit.amendments)
227
+ if (a.approved_at_utc)
228
+ decisions.push({ at: a.approved_at_utc, by: a.by ?? 'unknown', what: `approved amendment ${a.id}`, detail: a.paths.join(', ') });
229
+ decisions.sort((a, b) => a.at.localeCompare(b.at));
230
+ // A light-mode approval stamps spec and design at the same time: one decision.
231
+ const shown = [];
232
+ for (const d of decisions) {
233
+ const prev = shown.at(-1);
234
+ if (prev && prev.at === d.at && /^approved (spec|design)$/.test(prev.what) && /^approved (spec|design)$/.test(d.what))
235
+ prev.what = 'approved spec and design';
236
+ else
237
+ shown.push({ ...d });
238
+ }
239
+ const tierModel = (tier) => {
240
+ const value = host ? config.models?.[host]?.[tier] : undefined;
241
+ return !value || value === 'session' ? 'session model' : value;
242
+ };
243
+ const reviewers = ['balanced', 'deep']
244
+ .map((tier) => {
245
+ const own = reviews.filter((r) => r.tier === tier);
246
+ return {
247
+ name: tier === 'deep' ? 'agjan-reviewer-deep' : 'agjan-reviewer',
248
+ tier,
249
+ model: tierModel(tier),
250
+ count: own.length,
251
+ steps: [...new Set(own.map((r) => r.step))],
252
+ isolated: own.every((r) => r.isolation === 'agent'),
253
+ };
254
+ })
255
+ .filter((r) => r.count);
256
+ const humans = [...new Set(decisions.map((d) => d.by).filter((by) => !by.startsWith('auto mode')))];
257
+ const open = Object.values(findings).filter((f) => f.status === 'open');
258
+ return {
259
+ key: unit.key,
260
+ slug: unit.slug,
261
+ kind: unit.kind,
262
+ title: titleOf(unit),
263
+ mode: unit.design?.parsed.mode ?? null,
264
+ areas: unit.design?.parsed.areas ?? [],
265
+ onBase,
266
+ stages: stage.names,
267
+ at: stage.at,
268
+ turn: stage.turn,
269
+ now: stage.now,
270
+ optional: stage.turn === 'done' ? finalSteps(ctx.root, unit, { accepted: true }).optional : [],
271
+ start: iso(start),
272
+ end: iso(end),
273
+ last: iso(last),
274
+ host,
275
+ writer: steps.map((s) => ({ from: iso(s.from), to: iso(s.to), label: s.label })),
276
+ gates: gates.map((g) => ({ from: iso(g.from), to: iso(g.to), label: g.label.replace(/^gate /, ''), open: Boolean(g.open) })),
277
+ events: events.map((e) => ({ at: e.at_utc, event: e.event, ...Object.fromEntries(Object.entries(e).filter(([k]) => !['at_utc', 'event'].includes(k))) })),
278
+ commits,
279
+ reviews,
280
+ findings,
281
+ tasks,
282
+ acs,
283
+ decisions: shown,
284
+ reviewers,
285
+ humans,
286
+ roundLimit: roundLimit(config),
287
+ stats: {
288
+ activeMs: steps.reduce((t, s) => t + (s.to - s.from), 0),
289
+ waitingMs: gates.reduce((t, s) => t + (s.to - s.from), 0),
290
+ reviews: reviews.length,
291
+ blocked: reviews.filter((r) => r.verdict === 'blocked').length,
292
+ openFindings: open.length,
293
+ openBlockers: open.filter((f) => f.severity === 'blocker').length,
294
+ totalFindings: Object.keys(findings).length,
295
+ },
296
+ };
297
+ }
298
+ /** Every unit of the project, the units changed on this branch first. */
299
+ export function projectModels(ctx, { now = Date.now() } = {}) {
300
+ const changed = new Set(changedFeatures(ctx.root, ctx.config));
301
+ const all = listFeatures(ctx.root);
302
+ const models = [];
303
+ for (const slug of all) {
304
+ try {
305
+ models.push(unitModel(ctx, slug, { onBase: !changed.has(slug), now }));
306
+ }
307
+ catch {
308
+ // A damaged unit must not stop the pages; check reports it.
309
+ }
310
+ }
311
+ const order = { you: 0, agent: 1, done: 2, idle: 3, merged: 4 };
312
+ return models.sort((a, b) => order[a.turn] - order[b.turn] || b.last.localeCompare(a.last));
313
+ }
314
+ // ---------------------------------------------------------------- Markdown
315
+ const VERDICT_MD = { pass: '✅ pass', 'pass-with-notes': '🟡 notes', blocked: '⛔ blocked' };
316
+ const TURN_MD = { you: '👤 your turn', agent: '🤖 agent working', done: '✅ done', merged: '✅ merged', idle: '⏸ idle' };
317
+ function duration(ms) {
318
+ if (ms < 60_000)
319
+ return `${Math.max(Math.round(ms / 1000), 0)} s`;
320
+ const m = Math.round(ms / 60_000);
321
+ if (m < 60)
322
+ return `${m} min`;
323
+ const h = Math.floor(m / 60);
324
+ return h < 48 ? `${h} h ${m % 60} min` : `${Math.floor(h / 24)} d ${h % 24} h`;
325
+ }
326
+ const hm = (at) => `${at.slice(5, 10)} ${at.slice(11, 16)}`;
327
+ function track(model) {
328
+ return model.stages
329
+ .map((name, i) => (i < model.at || model.turn === 'done' || model.turn === 'merged' ? `✅ ${name}` : i === model.at ? (model.turn === 'you' ? `⏳ **${name}**` : `🔄 **${name}**`) : `⬜ ${name}`))
330
+ .join(' ── ');
331
+ }
332
+ function severities(ids, findings) {
333
+ const count = {};
334
+ for (const id of ids)
335
+ count[findings[id].severity] = (count[findings[id].severity] ?? 0) + 1;
336
+ return ['blocker', 'major', 'minor'].filter((k) => count[k]).map((k) => `${count[k]} ${k}`).join(', ');
337
+ }
338
+ /** The timeline rows of a unit: steps, reviews, gates, decisions and commits, in order. */
339
+ export function timelineRows(model) {
340
+ const rows = [];
341
+ for (const e of model.events) {
342
+ if (e.event === 'step')
343
+ rows.push([e.at, '🤖 writer', `${[e.stage, e.task, e.role].filter(Boolean).join(' ')} started`]);
344
+ if (e.event === 'gate-requested')
345
+ rows.push([e.at, '🤖 writer', e.gate === 'verify' ? 'asks you to accept the feature' : `asks you to approve ${e.gate}`]);
346
+ if (e.event === 'amendment-proposed')
347
+ rows.push([e.at, '🤖 writer', `proposes amendment ${e.amendment ?? ''}`.trim()]);
348
+ if (e.event === 'round-granted')
349
+ rows.push([e.at, '👤 human', `allows round ${e.round} for ${e.step}`]);
350
+ if (e.event === 'auto-on')
351
+ rows.push([e.at, '👤 human', 'switches auto mode on: spec and design pass automatically after their reviews']);
352
+ if (e.event === 'auto-off')
353
+ rows.push([e.at, '👤 human', 'switches auto mode off']);
354
+ }
355
+ for (const r of model.reviews) {
356
+ const what = r.findings.length ? ` (${severities(r.findings, model.findings)})` : '';
357
+ rows.push([r.at, `🔍 reviewer${r.tier === 'deep' ? ' (deep)' : ''}`, `${r.step} · round ${r.round} → ${VERDICT_MD[r.verdict]}${what}`]);
358
+ }
359
+ for (const d of model.decisions)
360
+ rows.push([d.at, '👤 human', `${d.what}${d.detail ? `: ${d.detail}` : ''}`]);
361
+ for (const c of model.commits)
362
+ rows.push([c.at, '🤖 writer', `commit \`${c.sha}\` ${c.subject}`]);
363
+ return rows.sort((a, b) => a[0].localeCompare(b[0]));
364
+ }
365
+ /** docs/agjan/<unit>/progress.md */
366
+ export function unitMarkdown(model, { generatedAt }) {
367
+ const out = [];
368
+ const md = (s) => String(s).replace(/\|/g, '\\|');
369
+ out.push(`# ${model.key} · ${model.slug}`, '');
370
+ out.push(`<!-- Generated by agjan at ${generatedAt}. Do not edit: every agjan command regenerates it. Overview: .agjan/progress.html (npx agjan progress --open). -->`, '');
371
+ out.push(`> ${md(model.title)}`, '');
372
+ out.push(track(model), '');
373
+ out.push(`**Now:** ${TURN_MD[model.turn]} · ${md(model.now)}`, '');
374
+ if (model.optional.length)
375
+ out.push('Optional next steps:', '', ...model.optional.map((step) => `- ${md(step)}`), '');
376
+ const s = model.stats;
377
+ out.push('| | |', '|---|---|');
378
+ out.push(`| Time | ${duration(s.activeMs)} agent work · ${duration(s.waitingMs)} waiting for a human |`);
379
+ if (model.tasks.length)
380
+ out.push(`| Tasks | ${model.tasks.filter((t) => t.done).length}/${model.tasks.length} committed |`);
381
+ if (model.acs) {
382
+ const tested = model.acs.passing === null ? `${model.acs.withTests}/${model.acs.automated} with tests` : `${model.acs.passing}/${model.acs.automated} with passing tests`;
383
+ out.push(`| Acceptance criteria | ${model.acs.total}: ${tested}${model.acs.manual.length ? ` · manual: ${model.acs.manual.join(', ')}` : ''} |`);
384
+ }
385
+ out.push(`| Reviews | ${s.reviews} · ${s.blocked} blocked · findings ${s.openFindings} open of ${s.totalFindings}, ${s.openBlockers} blocker(s) |`);
386
+ const agents = [model.host ? `writer: ${model.host}` : null, ...model.reviewers.map((r) => `${r.name} (${r.model}${r.isolated ? ', isolated' : ''})`)].filter(Boolean);
387
+ if (agents.length)
388
+ out.push(`| Agents | ${agents.join(' · ')} |`);
389
+ if (model.humans.length)
390
+ out.push(`| People | ${model.humans.join(', ')} |`);
391
+ out.push('');
392
+ const steps = [...new Set(model.reviews.map((r) => r.step))];
393
+ if (steps.length) {
394
+ out.push('## Review loops', '', '| Step | Rounds | Course |', '|---|---|---|');
395
+ for (const step of steps) {
396
+ const rs = model.reviews.filter((r) => r.step === step);
397
+ const course = rs
398
+ .map((r, i) => `${i && r.round === 1 ? '↺ ' : i ? '→ ' : ''}${r.id} ${VERDICT_MD[r.verdict]}${r.findings.length ? ` (${severities(r.findings, model.findings)})` : ''}`)
399
+ .join(' ');
400
+ out.push(`| ${step} | ${rs.length} (limit ${model.roundLimit} per loop) | ${course} |`);
401
+ }
402
+ out.push('');
403
+ }
404
+ if (model.tasks.length) {
405
+ out.push('## Tasks', '', '| Task | Area | Title | Commits | Reviews |', '|---|---|---|---|---|');
406
+ for (const t of model.tasks) {
407
+ out.push(`| ${t.done ? '✅' : '⬜'} ${t.id} | ${t.area} | ${md(t.title)} | ${t.commits.map((c) => `\`${c}\``).join(' ') || '-'} | ${t.reviews.join(', ') || '-'} |`);
408
+ }
409
+ out.push('');
410
+ }
411
+ const rows = timelineRows(model);
412
+ out.push('## Timeline (UTC)', '');
413
+ const table = (list) => ['| Time | Who | What |', '|---|---|---|', ...list.map(([at, who, what]) => `| ${hm(at)} | ${who} | ${md(what)} |`)];
414
+ if (rows.length > 30) {
415
+ out.push(...table(rows.slice(-30)), '', `<details><summary>${rows.length - 30} earlier events</summary>`, '', ...table(rows.slice(0, -30)), '', '</details>', '');
416
+ }
417
+ else {
418
+ out.push(...table(rows), '');
419
+ }
420
+ const ids = Object.keys(model.findings);
421
+ if (ids.length) {
422
+ out.push('## Findings', '', '| Id | Severity | Status | Issue |', '|---|---|---|---|');
423
+ const order = { open: 0, accepted: 1, resolved: 2 };
424
+ for (const id of ids.sort((a, b) => order[model.findings[a].status] - order[model.findings[b].status])) {
425
+ const f = model.findings[id];
426
+ const status = f.status === 'resolved' ? `resolved (${f.resolvedBy})` : f.status === 'accepted' ? `accepted: ${md(f.acceptReason)}` : 'open';
427
+ out.push(`| ${id} | ${f.severity} | ${status} | ${md(f.issue)}${f.file ? ` (\`${f.file}\`)` : ''} |`);
428
+ }
429
+ out.push('');
430
+ }
431
+ return `${out.join('\n').trimEnd()}\n`;
432
+ }
433
+ /** .agjan/progress.md */
434
+ export function overviewMarkdown(models, { generatedAt, project }) {
435
+ const out = [`# ${project} · agjan progress`, '', `<!-- Generated by agjan at ${generatedAt}. Local, not committed. Open .agjan/progress.html for the visual view. -->`, ''];
436
+ if (!models.length)
437
+ return `${[...out, 'No features, fixes or map runs yet.'].join('\n')}\n`;
438
+ out.push('| Unit | Kind | Stage | Now | Last activity |', '|---|---|---|---|---|');
439
+ for (const m of models) {
440
+ const stage = m.stages[Math.min(m.at, m.stages.length - 1)];
441
+ 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)} |`);
442
+ }
443
+ return `${out.join('\n')}\n`;
444
+ }
445
+ /** .agjan/progress.html: the template with the models as JSON. */
446
+ export function progressHtml(models, { generatedAt, project, kit }) {
447
+ const data = JSON.stringify({ project, generatedAt, kit, units: models }).replace(/</g, '\\u003c');
448
+ return readFileSync(TEMPLATE, 'utf8').replace('/*AGJAN_PROGRESS_DATA*/null', data);
449
+ }
450
+ /**
451
+ * Regenerates the progress pages. `only` limits the unit pages written (all units still
452
+ * feed the overview). Never throws: the pages must not break the command that triggered them.
453
+ */
454
+ export function writeProgress(ctx, { only = null, now = Date.now() } = {}) {
455
+ try {
456
+ const models = projectModels(ctx, { now });
457
+ const generatedAt = iso(now);
458
+ const project = ctx.root.split(/[\\/]/).filter(Boolean).at(-1) ?? '';
459
+ for (const m of models) {
460
+ // Only units worked on this branch: a page for a unit on the base branch would be a
461
+ // change to another unit here (it got its page while it was worked on).
462
+ if (m.onBase || (only && !only.includes(m.slug)))
463
+ continue;
464
+ const file = join(ctx.root, FEATURES_DIR, m.slug, PROGRESS_MD);
465
+ writeFileSync(file, unitMarkdown(m, { generatedAt }));
466
+ }
467
+ const dir = join(ctx.root, LOCAL_DIR);
468
+ if (!existsSync(dir))
469
+ mkdirSync(dir, { recursive: true });
470
+ writeFileSync(join(dir, 'progress.md'), overviewMarkdown(models, { generatedAt, project }));
471
+ writeFileSync(join(dir, 'progress.html'), progressHtml(models, { generatedAt, project, kit: ctx.kit }));
472
+ return { models, html: join(dir, 'progress.html') };
473
+ }
474
+ catch {
475
+ return null;
476
+ }
477
+ }
478
+ /** For the log listener: regenerate after an event in `unitDir` (root and config from the path). */
479
+ export function refreshAfterEvent(unitDir, kit) {
480
+ const marker = `${join('/', FEATURES_DIR)}`.replace(/\\/g, '/');
481
+ const normalized = unitDir.replace(/\\/g, '/');
482
+ const index = normalized.lastIndexOf(marker.replace(/^\//, '/'));
483
+ if (index === -1)
484
+ return;
485
+ const root = unitDir.slice(0, index);
486
+ const slug = normalized.slice(index + marker.length + 1);
487
+ try {
488
+ const ctx = { root, config: loadConfig(root), kit };
489
+ writeProgress(ctx, { only: [slug] });
490
+ }
491
+ catch {
492
+ // never break the command
493
+ }
494
+ }
@@ -0,0 +1,106 @@
1
+ import { git, mergeBase, resolveBase } from './git.js';
2
+ import { resolveArea } from './config.js';
3
+ import { matcher } from './scope.js';
4
+ import { latestReview, stillBlocked } from './feature.js';
5
+ import { scriptOwned, treeHash } from './review.js';
6
+ /**
7
+ * Build progress, derived from commits (design 8.3): a task is done when a commit on
8
+ * the branch has a subject starting with `<KEY>-<task id>:`, for example `ORDF-T1: …`.
9
+ * `history` searches the whole history instead, for a feature already on the base branch.
10
+ * A commit that changes only agjan's records (reviews, log, progress) is not task work:
11
+ * it never makes a review due, as the reviews' tree hash does not see it either.
12
+ */
13
+ export function taskCommits(root, config, feature, { history = false } = {}) {
14
+ const from = history ? null : mergeBase(root, resolveBase(root, config.git?.base));
15
+ const range = from ? `${from}..HEAD` : 'HEAD';
16
+ const log = git(root, ['log', '--format=%H%x09%s', range], { allowFail: true }) ?? '';
17
+ const done = new Map();
18
+ const prefix = new RegExp(`^${feature.key}-(T[1-9][0-9]*):`);
19
+ const records = scriptOwned(feature.slug);
20
+ // git log lists newest first; keep the newest commit of each task.
21
+ for (const line of log.split('\n').filter(Boolean)) {
22
+ const [sha, subject] = line.split('\t');
23
+ const match = prefix.exec(subject ?? '');
24
+ if (!match || done.has(match[1]))
25
+ continue;
26
+ const files = filesOf(root, sha);
27
+ if (files.length && files.every((f) => records.has(f) || f.startsWith('.agjan/')))
28
+ continue;
29
+ done.set(match[1], sha);
30
+ }
31
+ return done;
32
+ }
33
+ function filesOf(root, sha) {
34
+ return (git(root, ['show', '--name-only', '--format=', sha]) ?? '').split('\n').filter(Boolean);
35
+ }
36
+ function isAncestor(root, ancestor, descendant) {
37
+ if (!ancestor || !descendant)
38
+ return false;
39
+ return git(root, ['merge-base', '--is-ancestor', ancestor, descendant], { allowFail: true }) !== null;
40
+ }
41
+ /** A passing review of `step` that saw the given commit (its head contains the commit). */
42
+ function reviewedSince(root, feature, step, sha) {
43
+ return feature.reviews.records.some((r) => r.step === step && !stillBlocked(feature, r) && isAncestor(root, sha, r.head_commit));
44
+ }
45
+ /**
46
+ * Tasks with their state, the next task, and the build reviews that are due
47
+ * (design 7.3): per completed area by default, per task with `review.build: task`, and
48
+ * always per task for tasks whose commit touched a risk path.
49
+ */
50
+ export function buildProgress(root, config, feature, options = {}) {
51
+ const tasks = feature.tasks?.parsed.tasks ?? [];
52
+ const done = taskCommits(root, config, feature, options);
53
+ const isRisk = matcher(config.risk_paths ?? []);
54
+ const list = tasks.map((t) => ({
55
+ ...t,
56
+ areaName: resolveArea(config, t.area ?? '')?.name ?? t.area,
57
+ commit: done.get(t.id) ?? null,
58
+ }));
59
+ const due = [];
60
+ const perTask = config.review?.build === 'task';
61
+ for (const task of list.filter((t) => t.commit)) {
62
+ const risky = filesOf(root, task.commit).some(isRisk);
63
+ if ((perTask || risky) && !reviewedSince(root, feature, `build:${task.id}`, task.commit)) {
64
+ due.push({ step: `build:${task.id}`, reason: risky ? 'touches a risk path' : 'review per task' });
65
+ }
66
+ }
67
+ if (!perTask) {
68
+ for (const area of [...new Set(list.map((t) => t.areaName))]) {
69
+ const areaTasks = list.filter((t) => t.areaName === area);
70
+ if (areaTasks.some((t) => !t.commit))
71
+ continue;
72
+ const last = areaTasks.map((t) => t.commit).find((sha) => areaTasks.every((o) => isAncestor(root, o.commit, sha)));
73
+ if (!reviewedSince(root, feature, `build:${area}`, last))
74
+ due.push({ step: `build:${area}`, reason: 'all tasks of the area are done' });
75
+ }
76
+ }
77
+ const next = list.find((t) => !t.commit) ?? null;
78
+ return { tasks: list, next, due, complete: list.length > 0 && !next };
79
+ }
80
+ /**
81
+ * The final verify review (design 8.4): `none`, `blocked`, `stale` (files changed after
82
+ * it) or `current`. Shared by `check --ci` and `status`.
83
+ */
84
+ export function verifyState(root, config, feature) {
85
+ const record = latestReview(feature.reviews, ['verify']);
86
+ if (!record)
87
+ return { state: 'none', record: null };
88
+ if (stillBlocked(feature, record))
89
+ return { state: 'blocked', record };
90
+ if (record.tree_hash !== treeHash(root, config, feature.slug))
91
+ return { state: 'stale', record };
92
+ return { state: 'current', record };
93
+ }
94
+ /**
95
+ * The human's acceptance of the verified feature (`agjan approve verify`, decision 77):
96
+ * `none`, `accepted` (it names the current verify review and its tree hash) or `stale`
97
+ * (an earlier verify review was accepted). Only meaningful while the verify review is
98
+ * current; agjan learns of the acceptance from this record, not from a pull request.
99
+ */
100
+ export function acceptanceState(root, config, feature, verify = verifyState(root, config, feature)) {
101
+ const approval = feature.approvals.approvals.verify;
102
+ if (!approval)
103
+ return { state: 'none', approval: null };
104
+ const current = verify.state === 'current' && approval.review === verify.record.id && approval.tree_hash === verify.record.tree_hash;
105
+ return { state: current ? 'accepted' : 'stale', approval };
106
+ }