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
@@ -1,466 +0,0 @@
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' : 'Done'];
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
- // A step runs once the skill logged its start after the approval it builds on; until then
80
- // the agent has stopped and the human starts the next skill (design decision 70).
81
- const startedSince = (stage, at) => events.some((e) => e.event === 'step' && e.stage === stage && (!at || e.at_utc >= at));
82
- const lastStep = events.filter((e) => e.event === 'step').at(-1);
83
- if (unit.stage === 'spec') {
84
- 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' };
85
- }
86
- if (unit.stage === 'design') {
87
- if (waiting) 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)) return { names, at: 1, turn: 'you', now: 'start the design: /agjan-design' };
89
- return { names, at: 1, turn: 'agent', now: 'writing and reviewing the design' };
90
- }
91
- const pending = unit.amendments.filter((a) => a.status === 'pending');
92
- const verified = progress.complete && progress.due.length === 0 && verify.state === 'current';
93
- if (onBase && progress.complete && verify.record && !stillBlocked(unit, verify.record)) return { names, at: 5, turn: 'merged', now: 'merged' };
94
- if (verified) return { names, at: 5, turn: 'done', now: 'development finished and verified' };
95
- if (pending.length) return { names, at: 2, turn: 'you', now: `approve amendment ${pending[0].id} (npx agjan approve amendment ${pending[0].id})` };
96
- const building = startedSince('build', unit.approvals.approvals.design?.at_utc);
97
- if (!progress.complete || progress.due.length) {
98
- if (!building) return { names, at: 2, turn: 'you', now: 'start the build: /agjan-build' };
99
- return { names, at: 2, turn: 'agent', now: progress.next ? `task ${progress.next.id}: ${progress.next.title}` : `review ${progress.due[0].step}` };
100
- }
101
- if (lastStep?.stage !== 'verify') return { names, at: 3, turn: 'you', now: 'start the verification: /agjan-verify' };
102
- return { names, at: 3, turn: 'agent', now: verify.state === 'none' ? 'verify' : `verify (${verify.state})` };
103
- }
104
-
105
- /**
106
- * While the agent would be working, a `waiting` event after its last step means it stopped
107
- * for the user (an error it cannot resolve, a decision): their turn, with the reason.
108
- */
109
- function waitingFor(events, stage) {
110
- if (stage.turn !== 'agent') return stage;
111
- const last = events.filter((e) => ['step', 'waiting', 'gate-requested', 'approved', 'rejected'].includes(e.event)).at(-1);
112
- return last?.event === 'waiting' ? { ...stage, turn: 'you', now: last.reason } : stage;
113
- }
114
-
115
- /** What the human may do after "done" (design decision 70): all of it optional. */
116
- export function optionalSteps(root, unit, acs) {
117
- const steps = [];
118
- const project = readFileSyncSafe(join(root, FEATURES_DIR, 'project.md'));
119
- steps.push(/^## Run locally\s*$/m.test(project) ? 'try it locally: docs/agjan/project.md, section "Run locally" (start command, URL, users)' : 'try it locally');
120
- if (acs?.manual.length) steps.push(`check by hand: ${acs.manual.join(', ')}`);
121
- steps.push('open a pull request (ask the agent: "open the PR"), review it, merge it');
122
- return steps;
123
- }
124
-
125
- /** The data of one unit for the progress pages. */
126
- export function unitModel(ctx, slug, { onBase = false, now = Date.now() } = {}) {
127
- const unit = loadFeature(ctx.root, slug);
128
- const config = ctx.config;
129
- const events = readLog(unit.dir);
130
- const isFeature = unit.kind === 'feature';
131
- const progress = isFeature && unit.tasks ? buildProgress(ctx.root, config, unit, { history: onBase }) : null;
132
- const verify = isFeature ? verifyState(ctx.root, config, unit) : null;
133
- const review = !isFeature ? freshReview(ctx.root, config, unit, unit.kind) : null;
134
- const stage = waitingFor(events, stageOf(ctx, unit, onBase, { progress, verify, review }));
135
- const commits = unitCommits(ctx.root, unit.key);
136
-
137
- const times = [...events.map((e) => Date.parse(e.at_utc)), ...commits.map((c) => Date.parse(c.at))].filter(Number.isFinite);
138
- const start = times.length ? Math.min(...times) : now;
139
- const last = times.length ? Math.max(...times) : now;
140
- // An open step runs until now only while the agent works; when it is a human's turn,
141
- // the agent's work ended with the last activity and the rest is waiting.
142
- const end = stage.turn === 'merged' || stage.turn === 'done' ? last : Math.max(last, now);
143
- const list = spans(events, stage.turn === 'agent' ? end : last).map((s) => (s.kind === 'gate' && s.open ? { ...s, to: end } : s));
144
- const steps = list.filter((s) => s.kind === 'step');
145
- const gates = list.filter((s) => s.kind === 'gate');
146
-
147
- const host = unit.reviews.records.find((r) => r.reviewer?.host)?.reviewer.host ?? events.find((e) => e.host)?.host ?? null;
148
- const reviews = unit.reviews.records.map((r) => ({
149
- id: r.id,
150
- step: r.step,
151
- round: r.round,
152
- verdict: r.verdict,
153
- at: r.at_utc,
154
- tier: reviewerFor(config, r.step) === 'agjan-reviewer-deep' ? 'deep' : 'balanced',
155
- host: r.reviewer?.host ?? null,
156
- isolation: r.reviewer?.isolation ?? null,
157
- findings: (r.findings ?? []).map((f) => f.id),
158
- resolves: r.resolves ?? [],
159
- }));
160
- const resolvedBy = {};
161
- for (const r of reviews) for (const id of r.resolves) resolvedBy[id] = r.id;
162
- const accepted = new Map(unit.approvals.accepted.map((a) => [a.finding, a]));
163
- const findings = {};
164
- for (const f of unit.findings) {
165
- findings[f.id] = {
166
- severity: f.severity,
167
- file: f.file ?? null,
168
- issue: f.issue,
169
- evidence: f.evidence ?? null,
170
- status: f.status,
171
- raisedBy: f.record,
172
- resolvedBy: resolvedBy[f.id] ?? null,
173
- acceptReason: accepted.get(f.id)?.reason ?? null,
174
- };
175
- }
176
-
177
- const tasks = (progress?.tasks ?? []).map((t) => ({
178
- id: t.id,
179
- area: t.areaName,
180
- title: t.title,
181
- covers: t.covers,
182
- done: Boolean(t.commit),
183
- commits: commits.filter((c) => c.subject.startsWith(`${unit.key}-${t.id}:`)).map((c) => c.sha),
184
- reviews: reviews.filter((r) => r.step === `build:${t.areaName}` || r.step === `build:${t.id}`).map((r) => r.id),
185
- }));
186
-
187
- let acs = null;
188
- if (isFeature && unit.spec) {
189
- const areaNames = [...new Set(tasks.map((t) => t.area))];
190
- const automated = unit.spec.parsed.acs.filter((ac) => ac.verification !== 'manual');
191
- const loaded = loadResults(ctx.root, config, areaNames);
192
- const results = loaded.files.length ? acResults(loaded, unit.key) : null;
193
- const tests = acTestFiles(ctx.root, config, areaNames, unit.key);
194
- acs = {
195
- total: unit.spec.parsed.acs.length,
196
- automated: automated.length,
197
- manual: unit.spec.parsed.acs.filter((ac) => ac.verification === 'manual').map((ac) => ac.id),
198
- withTests: automated.filter((ac) => tests.has(ac.id)).length,
199
- passing: results ? automated.filter((ac) => results.get(ac.id)?.passed && !results.get(ac.id)?.failed).length : null,
200
- };
201
- }
202
-
203
- const decisions = [];
204
- for (const [gate, a] of Object.entries(unit.approvals.approvals)) decisions.push({ at: a.at_utc, by: a.by, what: `approved ${gate}` });
205
- for (const a of unit.approvals.accepted) decisions.push({ at: a.at_utc, by: a.by, what: `accepted ${a.finding}`, detail: a.reason });
206
- for (const r of unit.approvals.rejections ?? []) decisions.push({ at: r.at_utc, by: r.by, what: `rejected ${r.gate}`, detail: r.reason });
207
- 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(', ') });
208
- decisions.sort((a, b) => a.at.localeCompare(b.at));
209
- // A light-mode approval stamps spec and design at the same time: one decision.
210
- const shown = [];
211
- for (const d of decisions) {
212
- const prev = shown.at(-1);
213
- if (prev && prev.at === d.at && /^approved (spec|design)$/.test(prev.what) && /^approved (spec|design)$/.test(d.what)) prev.what = 'approved spec and design';
214
- else shown.push({ ...d });
215
- }
216
-
217
- const tierModel = (tier) => {
218
- const value = config.models?.[host]?.[tier];
219
- return !value || value === 'session' ? 'session model' : value;
220
- };
221
- const reviewers = ['balanced', 'deep']
222
- .map((tier) => {
223
- const own = reviews.filter((r) => r.tier === tier);
224
- return {
225
- name: tier === 'deep' ? 'agjan-reviewer-deep' : 'agjan-reviewer',
226
- tier,
227
- model: tierModel(tier),
228
- count: own.length,
229
- steps: [...new Set(own.map((r) => r.step))],
230
- isolated: own.every((r) => r.isolation === 'agent'),
231
- };
232
- })
233
- .filter((r) => r.count);
234
- const humans = [...new Set(decisions.map((d) => d.by))];
235
-
236
- const open = Object.values(findings).filter((f) => f.status === 'open');
237
- return {
238
- key: unit.key,
239
- slug: unit.slug,
240
- kind: unit.kind,
241
- title: titleOf(unit),
242
- mode: unit.design?.parsed.mode ?? null,
243
- areas: unit.design?.parsed.areas ?? [],
244
- onBase,
245
- stages: stage.names,
246
- at: stage.at,
247
- turn: stage.turn,
248
- now: stage.now,
249
- optional: stage.turn === 'done' ? optionalSteps(ctx.root, unit, acs) : [],
250
- start: iso(start),
251
- end: iso(end),
252
- last: iso(last),
253
- host,
254
- writer: steps.map((s) => ({ from: iso(s.from), to: iso(s.to), label: s.label })),
255
- gates: gates.map((g) => ({ from: iso(g.from), to: iso(g.to), label: g.label.replace(/^gate /, ''), open: Boolean(g.open) })),
256
- events: events.map((e) => ({ at: e.at_utc, event: e.event, ...Object.fromEntries(Object.entries(e).filter(([k]) => !['at_utc', 'event'].includes(k))) })),
257
- commits,
258
- reviews,
259
- findings,
260
- tasks,
261
- acs,
262
- decisions: shown,
263
- reviewers,
264
- humans,
265
- roundLimit: roundLimit(config),
266
- stats: {
267
- activeMs: steps.reduce((t, s) => t + (s.to - s.from), 0),
268
- waitingMs: gates.reduce((t, s) => t + (s.to - s.from), 0),
269
- reviews: reviews.length,
270
- blocked: reviews.filter((r) => r.verdict === 'blocked').length,
271
- openFindings: open.length,
272
- openBlockers: open.filter((f) => f.severity === 'blocker').length,
273
- totalFindings: Object.keys(findings).length,
274
- },
275
- };
276
- }
277
-
278
- /** Every unit of the project, the units changed on this branch first. */
279
- export function projectModels(ctx, { now = Date.now() } = {}) {
280
- const changed = new Set(changedFeatures(ctx.root, ctx.config));
281
- const all = listFeatures(ctx.root);
282
- const models = [];
283
- for (const slug of all) {
284
- try {
285
- models.push(unitModel(ctx, slug, { onBase: !changed.has(slug), now }));
286
- } catch {
287
- // A damaged unit must not stop the pages; check reports it.
288
- }
289
- }
290
- const order = { you: 0, agent: 1, done: 2, idle: 3, merged: 4 };
291
- return models.sort((a, b) => order[a.turn] - order[b.turn] || b.last.localeCompare(a.last));
292
- }
293
-
294
- // ---------------------------------------------------------------- Markdown
295
-
296
- const VERDICT_MD = { pass: '✅ pass', 'pass-with-notes': '🟡 notes', blocked: '⛔ blocked' };
297
- const TURN_MD = { you: '👤 your turn', agent: '🤖 agent working', done: '✅ done', merged: '✅ merged', idle: '⏸ idle' };
298
-
299
- function duration(ms) {
300
- if (ms < 60_000) return `${Math.max(Math.round(ms / 1000), 0)} s`;
301
- const m = Math.round(ms / 60_000);
302
- if (m < 60) return `${m} min`;
303
- const h = Math.floor(m / 60);
304
- return h < 48 ? `${h} h ${m % 60} min` : `${Math.floor(h / 24)} d ${h % 24} h`;
305
- }
306
-
307
- const hm = (at) => `${at.slice(5, 10)} ${at.slice(11, 16)}`;
308
-
309
- function track(model) {
310
- return model.stages
311
- .map((name, i) => (i < model.at || model.turn === 'done' || model.turn === 'merged' ? `✅ ${name}` : i === model.at ? (model.turn === 'you' ? `⏳ **${name}**` : `🔄 **${name}**`) : `⬜ ${name}`))
312
- .join(' ── ');
313
- }
314
-
315
- function severities(ids, findings) {
316
- const count = {};
317
- for (const id of ids) count[findings[id].severity] = (count[findings[id].severity] ?? 0) + 1;
318
- return ['blocker', 'major', 'minor'].filter((k) => count[k]).map((k) => `${count[k]} ${k}`).join(', ');
319
- }
320
-
321
- /** The timeline rows of a unit: steps, reviews, gates, decisions and commits, in order. */
322
- export function timelineRows(model) {
323
- const rows = [];
324
- for (const e of model.events) {
325
- if (e.event === 'step') rows.push([e.at, '🤖 writer', `${[e.stage, e.task, e.role].filter(Boolean).join(' ')} started`]);
326
- if (e.event === 'gate-requested') rows.push([e.at, '🤖 writer', `asks you to approve ${e.gate}`]);
327
- if (e.event === 'amendment-proposed') rows.push([e.at, '🤖 writer', `proposes amendment ${e.amendment ?? ''}`.trim()]);
328
- if (e.event === 'round-granted') rows.push([e.at, '👤 human', `allows round ${e.round} for ${e.step}`]);
329
- }
330
- for (const r of model.reviews) {
331
- const what = r.findings.length ? ` (${severities(r.findings, model.findings)})` : '';
332
- rows.push([r.at, `🔍 reviewer${r.tier === 'deep' ? ' (deep)' : ''}`, `${r.step} · round ${r.round} → ${VERDICT_MD[r.verdict]}${what}`]);
333
- }
334
- for (const d of model.decisions) rows.push([d.at, '👤 human', `${d.what}${d.detail ? `: ${d.detail}` : ''}`]);
335
- for (const c of model.commits) rows.push([c.at, '🤖 writer', `commit \`${c.sha}\` ${c.subject}`]);
336
- return rows.sort((a, b) => a[0].localeCompare(b[0]));
337
- }
338
-
339
- /** docs/agjan/<unit>/progress.md */
340
- export function unitMarkdown(model, { generatedAt }) {
341
- const out = [];
342
- const md = (s) => String(s).replace(/\|/g, '\\|');
343
- out.push(`# ${model.key} · ${model.slug}`, '');
344
- out.push(`<!-- Generated by agjan at ${generatedAt}. Do not edit: every agjan command regenerates it. Overview: .agjan/progress.html (npx agjan progress --open). -->`, '');
345
- out.push(`> ${md(model.title)}`, '');
346
- out.push(track(model), '');
347
- out.push(`**Now:** ${TURN_MD[model.turn]} · ${md(model.now)}`, '');
348
- if (model.optional.length) out.push('Optional next steps:', '', ...model.optional.map((step) => `- ${md(step)}`), '');
349
- const s = model.stats;
350
- out.push('| | |', '|---|---|');
351
- out.push(`| Time | ${duration(s.activeMs)} agent work · ${duration(s.waitingMs)} waiting for a human |`);
352
- if (model.tasks.length) out.push(`| Tasks | ${model.tasks.filter((t) => t.done).length}/${model.tasks.length} committed |`);
353
- if (model.acs) {
354
- const tested = model.acs.passing === null ? `${model.acs.withTests}/${model.acs.automated} with tests` : `${model.acs.passing}/${model.acs.automated} with passing tests`;
355
- out.push(`| Acceptance criteria | ${model.acs.total}: ${tested}${model.acs.manual.length ? ` · manual: ${model.acs.manual.join(', ')}` : ''} |`);
356
- }
357
- out.push(`| Reviews | ${s.reviews} · ${s.blocked} blocked · findings ${s.openFindings} open of ${s.totalFindings}, ${s.openBlockers} blocker(s) |`);
358
- const agents = [model.host ? `writer: ${model.host}` : null, ...model.reviewers.map((r) => `${r.name} (${r.model}${r.isolated ? ', isolated' : ''})`)].filter(Boolean);
359
- if (agents.length) out.push(`| Agents | ${agents.join(' · ')} |`);
360
- if (model.humans.length) out.push(`| People | ${model.humans.join(', ')} |`);
361
- out.push('');
362
-
363
- const steps = [...new Set(model.reviews.map((r) => r.step))];
364
- if (steps.length) {
365
- out.push('## Review loops', '', '| Step | Rounds | Course |', '|---|---|---|');
366
- for (const step of steps) {
367
- const rs = model.reviews.filter((r) => r.step === step);
368
- const course = rs
369
- .map((r, i) => `${i && r.round === 1 ? '↺ ' : i ? '→ ' : ''}${r.id} ${VERDICT_MD[r.verdict]}${r.findings.length ? ` (${severities(r.findings, model.findings)})` : ''}`)
370
- .join(' ');
371
- out.push(`| ${step} | ${rs.length} (limit ${model.roundLimit} per loop) | ${course} |`);
372
- }
373
- out.push('');
374
- }
375
-
376
- if (model.tasks.length) {
377
- out.push('## Tasks', '', '| Task | Area | Title | Commits | Reviews |', '|---|---|---|---|---|');
378
- for (const t of model.tasks) {
379
- out.push(`| ${t.done ? '✅' : '⬜'} ${t.id} | ${t.area} | ${md(t.title)} | ${t.commits.map((c) => `\`${c}\``).join(' ') || '-'} | ${t.reviews.join(', ') || '-'} |`);
380
- }
381
- out.push('');
382
- }
383
-
384
- const rows = timelineRows(model);
385
- out.push('## Timeline (UTC)', '');
386
- const table = (list) => ['| Time | Who | What |', '|---|---|---|', ...list.map(([at, who, what]) => `| ${hm(at)} | ${who} | ${md(what)} |`)];
387
- if (rows.length > 30) {
388
- out.push(...table(rows.slice(-30)), '', `<details><summary>${rows.length - 30} earlier events</summary>`, '', ...table(rows.slice(0, -30)), '', '</details>', '');
389
- } else {
390
- out.push(...table(rows), '');
391
- }
392
-
393
- const ids = Object.keys(model.findings);
394
- if (ids.length) {
395
- out.push('## Findings', '', '| Id | Severity | Status | Issue |', '|---|---|---|---|');
396
- const order = { open: 0, accepted: 1, resolved: 2 };
397
- for (const id of ids.sort((a, b) => order[model.findings[a].status] - order[model.findings[b].status])) {
398
- const f = model.findings[id];
399
- const status = f.status === 'resolved' ? `resolved (${f.resolvedBy})` : f.status === 'accepted' ? `accepted: ${md(f.acceptReason)}` : 'open';
400
- out.push(`| ${id} | ${f.severity} | ${status} | ${md(f.issue)}${f.file ? ` (\`${f.file}\`)` : ''} |`);
401
- }
402
- out.push('');
403
- }
404
- return `${out.join('\n').trimEnd()}\n`;
405
- }
406
-
407
- /** .agjan/progress.md */
408
- export function overviewMarkdown(models, { generatedAt, project }) {
409
- const out = [`# ${project} · agjan progress`, '', `<!-- Generated by agjan at ${generatedAt}. Local, not committed. Open .agjan/progress.html for the visual view. -->`, ''];
410
- if (!models.length) return `${[...out, 'No features, fixes or map runs yet.'].join('\n')}\n`;
411
- out.push('| Unit | Kind | Stage | Now | Last activity |', '|---|---|---|---|---|');
412
- for (const m of models) {
413
- const stage = m.stages[Math.min(m.at, m.stages.length - 1)];
414
- 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)} |`);
415
- }
416
- return `${out.join('\n')}\n`;
417
- }
418
-
419
- /** .agjan/progress.html: the template with the models as JSON. */
420
- export function progressHtml(models, { generatedAt, project, kit }) {
421
- const data = JSON.stringify({ project, generatedAt, kit, units: models }).replace(/</g, '\\u003c');
422
- return readFileSync(TEMPLATE, 'utf8').replace('/*AGJAN_PROGRESS_DATA*/null', data);
423
- }
424
-
425
- /**
426
- * Regenerates the progress pages. `only` limits the unit pages written (all units still
427
- * feed the overview). Never throws: the pages must not break the command that triggered them.
428
- */
429
- export function writeProgress(ctx, { only = null, now = Date.now() } = {}) {
430
- try {
431
- const models = projectModels(ctx, { now });
432
- const generatedAt = iso(now);
433
- const project = ctx.root.split(/[\\/]/).filter(Boolean).at(-1);
434
- for (const m of models) {
435
- // Only units worked on this branch: a page for a unit on the base branch would be a
436
- // change to another unit here (it got its page while it was worked on).
437
- if (m.onBase || (only && !only.includes(m.slug))) continue;
438
- const file = join(ctx.root, FEATURES_DIR, m.slug, PROGRESS_MD);
439
- writeFileSync(file, unitMarkdown(m, { generatedAt }));
440
- }
441
- const dir = join(ctx.root, LOCAL_DIR);
442
- if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
443
- writeFileSync(join(dir, 'progress.md'), overviewMarkdown(models, { generatedAt, project }));
444
- writeFileSync(join(dir, 'progress.html'), progressHtml(models, { generatedAt, project, kit: ctx.kit }));
445
- return { models, html: join(dir, 'progress.html') };
446
- } catch {
447
- return null;
448
- }
449
- }
450
-
451
- /** For the log listener: regenerate after an event in `unitDir` (root and config from the path). */
452
- export function refreshAfterEvent(unitDir, kit) {
453
- const marker = `${join('/', FEATURES_DIR)}`.replace(/\\/g, '/');
454
- const normalized = unitDir.replace(/\\/g, '/');
455
- const index = normalized.lastIndexOf(marker.replace(/^\//, '/'));
456
- if (index === -1) return;
457
- const root = unitDir.slice(0, index);
458
- const slug = normalized.slice(index + marker.length + 1);
459
- try {
460
- const ctx = { root, config: loadConfig(root), kit };
461
- writeProgress(ctx, { only: [slug] });
462
- } catch {
463
- // never break the command
464
- }
465
- }
466
-
package/src/progress.mjs DELETED
@@ -1,85 +0,0 @@
1
- import { git, mergeBase, resolveBase } from './git.mjs';
2
- import { resolveArea } from './config.mjs';
3
- import { matcher } from './scope.mjs';
4
- import { latestReview, stillBlocked } 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 && !stillBlocked(feature, r) && 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 (stillBlocked(feature, record)) return { state: 'blocked', record };
83
- if (record.tree_hash !== treeHash(root, config, feature.slug)) return { state: 'stale', record };
84
- return { state: 'current', record };
85
- }