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,65 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { parseArgs } from 'node:util';
4
+ import { writeJson } from '../json-file.js';
5
+ import { APPROVALS_FILE, FEATURES_DIR, KEY, SLUG, emptyApprovals, featureDir, listFeatures, loadFeature, selectFeature } from '../feature.js';
6
+ import { AgjanError, UsageError } from '../errors.js';
7
+ import { readAutoDefault } from '../auto.js';
8
+ import { appendLog } from '../log.js';
9
+ const TEMPLATES = new URL('../../kit/templates/', import.meta.url);
10
+ export function renderTemplate(name, { slug, key }) {
11
+ return readFileSync(new URL(name, TEMPLATES), 'utf8').replaceAll('{{SLUG}}', slug).replaceAll('{{KEY}}', key);
12
+ }
13
+ /** agjan scaffold design [--feature <slug>]: creates design.md and tasks.md from the templates. */
14
+ export function scaffold(ctx, argv) {
15
+ const { values, positionals } = parseArgs({ args: argv, options: { feature: { type: 'string' } }, allowPositionals: true });
16
+ if (positionals.join(' ') !== 'design')
17
+ throw new UsageError('usage: agjan scaffold design [--feature <slug>]');
18
+ const feature = loadFeature(ctx.root, selectFeature(ctx.root, ctx.config, values.feature));
19
+ for (const name of ['design.md', 'tasks.md']) {
20
+ const file = join(feature.dir, name);
21
+ if (existsSync(file)) {
22
+ ctx.out(`${FEATURES_DIR}/${feature.slug}/${name} exists; not changed`);
23
+ continue;
24
+ }
25
+ writeFileSync(file, renderTemplate(name, { slug: feature.slug, key: feature.key }));
26
+ ctx.out(`created ${FEATURES_DIR}/${feature.slug}/${name}`);
27
+ }
28
+ return 0;
29
+ }
30
+ /** agjan new <slug> --key <KEY>: creates the feature folder, approvals.json and spec.md. */
31
+ export function run(ctx, argv) {
32
+ const { values, positionals } = parseArgs({ args: argv, options: { key: { type: 'string' } }, allowPositionals: true });
33
+ const [slug] = positionals;
34
+ if (!slug || positionals.length > 1 || !values.key)
35
+ throw new UsageError('usage: agjan new <slug> --key <KEY>');
36
+ if (!SLUG.test(slug))
37
+ throw new UsageError(`slug '${slug}' must be lowercase letters, digits and '-', at most 48 characters`);
38
+ if (slug === 'fixes')
39
+ throw new UsageError("'fixes' is reserved");
40
+ const key = values.key;
41
+ if (!KEY.test(key))
42
+ throw new UsageError(`key '${key}' must be 2 to 6 uppercase letters or digits, starting with a letter`);
43
+ const root = ctx.root;
44
+ const dir = featureDir(root, slug);
45
+ if (existsSync(dir))
46
+ throw new AgjanError(`${FEATURES_DIR}/${slug} already exists`);
47
+ for (const other of listFeatures(root)) {
48
+ if (loadFeature(root, other).key === key)
49
+ throw new AgjanError(`key ${key} is already used by feature '${other}'`);
50
+ }
51
+ mkdirSync(dir, { recursive: true });
52
+ const approvals = emptyApprovals(slug, key, ctx.kit, ctx.now());
53
+ // The person's auto mode default for this checkout (decision 79).
54
+ const auto = readAutoDefault(root);
55
+ if (auto)
56
+ approvals.auto = { by: auto.by, at_utc: ctx.now(), from: 'default' };
57
+ writeJson(join(dir, APPROVALS_FILE), approvals);
58
+ writeFileSync(join(dir, 'spec.md'), renderTemplate('spec.md', { slug, key }));
59
+ ctx.out(`created ${FEATURES_DIR}/${slug}/ (key ${key}): ${APPROVALS_FILE}, spec.md`);
60
+ if (auto) {
61
+ appendLog(dir, ctx.now(), 'auto-on', { from: 'default' });
62
+ ctx.out(`auto mode on (the default of ${auto.by} in this checkout): spec and design pass automatically after their reviews; approve verify stays with the user`);
63
+ }
64
+ return 0;
65
+ }
@@ -0,0 +1,168 @@
1
+ import { parseArgs } from 'node:util';
2
+ import { resolveArea } from '../config.js';
3
+ import { FEATURES_DIR } from '../feature.js';
4
+ import { acTestFiles } from '../tests-map.js';
5
+ import { acResults, loadResults, resultLabel } from '../test-results.js';
6
+ import { overrideBase, runChecks } from './check.js';
7
+ import { readFix } from './fix.js';
8
+ import { highlightMarkdown } from '../ui.js';
9
+ import { readLog } from '../log.js';
10
+ import { acceptanceState } from '../progress.js';
11
+ function short(hash) {
12
+ return hash ? hash.slice('sha256:'.length, 'sha256:'.length + 12) : '-';
13
+ }
14
+ /** A fix or a map run in the PR summary. */
15
+ function recordSection(feature) {
16
+ const out = [`### ${feature.kind === 'fix' ? 'Fix' : 'Map run'} ${feature.slug} (${feature.key})`, ''];
17
+ if (feature.kind === 'fix') {
18
+ const fix = readFix(feature);
19
+ out.push(`**What:** ${fix?.what ?? '(not stated)'}`, '');
20
+ if (fix?.files) {
21
+ out.push(`**Size:** ${fix.total} changed lines (limit ${fix.limits?.max_total}, per file ${fix.limits?.max_per_file})`, '');
22
+ out.push(`**Verified with:** ${fix.verify ?? 'not stated'}`, '');
23
+ }
24
+ else {
25
+ out.push('**Not recorded yet** (`npx agjan fix record`).', '');
26
+ }
27
+ }
28
+ else {
29
+ out.push('Writes the baseline `docs/agjan/project.md` and `docs/agjan/baseline.json`.', '');
30
+ }
31
+ for (const r of feature.reviews.records)
32
+ out.push(`- ${r.id} ${r.step} round ${r.round}: ${r.verdict} (${r.findings?.length ?? 0} findings, isolation ${r.reviewer?.isolation ?? 'unknown'})`);
33
+ if (feature.reviews.records.length)
34
+ out.push('');
35
+ return out;
36
+ }
37
+ function featureSection(ctx, feature) {
38
+ if (feature.kind !== 'feature')
39
+ return recordSection(feature);
40
+ const out = [];
41
+ const mode = feature.design?.parsed.mode ?? '-';
42
+ out.push(`### ${feature.slug} (${feature.key})`, '');
43
+ out.push('| Document | State | Hash | Approved |', '|---|---|---|---|');
44
+ const spec = feature.approvals.approvals.spec;
45
+ const design = feature.approvals.approvals.design;
46
+ const approver = (stamp) => (stamp.by === 'auto' ? `**auto mode** (switched on by ${stamp.enabled_by})` : stamp.by);
47
+ out.push(`| spec.md | ${feature.state.spec} | ${short(feature.spec?.hash)} | ${spec ? `${spec.at_utc} by ${approver(spec)}` : '-'} |`);
48
+ out.push(`| design (${mode}) | ${feature.state.design} | ${short(feature.designHash)} | ${design ? `${design.at_utc} by ${approver(design)}` : '-'} |`);
49
+ const acceptance = acceptanceState(ctx.root, ctx.config, feature);
50
+ const acceptedBy = acceptance.state === 'accepted' ? acceptance.approval : null;
51
+ const notes = [];
52
+ const autoGates = [spec, design].filter((s) => s?.by === 'auto').length;
53
+ if (autoGates || feature.approvals.auto) {
54
+ const on = feature.approvals.auto;
55
+ notes.push(`**Auto mode:** ${on ? `on since ${on.at_utc} (switched on by ${on.by})` : 'was on'}. ${autoGates ? 'Gates approved automatically after their reviews passed; no person approved them.' : 'No gate was approved automatically yet.'}`);
56
+ }
57
+ out.push(`| acceptance (verify) | ${acceptance.state === 'none' ? 'not accepted' : acceptance.state} | ${short(acceptance.approval?.tree_hash)} | ${acceptance.approval ? `${acceptance.approval.at_utc} by ${acceptance.approval.by}` : '-'} |`, '');
58
+ if (notes.length)
59
+ out.push(...notes, '');
60
+ const tasks = feature.tasks;
61
+ if (feature.spec && tasks) {
62
+ const areaNames = [...new Set(tasks.parsed.tasks.map((t) => resolveArea(ctx.config, t.area)?.name).filter((name) => Boolean(name)))];
63
+ const tests = acTestFiles(ctx.root, ctx.config, areaNames, feature.key);
64
+ const tasksFor = (id) => tasks.parsed.tasks.filter((t) => t.covers.includes(id)).map((t) => t.id).join(', ') || '-';
65
+ const loaded = loadResults(ctx.root, ctx.config, areaNames);
66
+ const results = loaded.files.length ? acResults(loaded, feature.key) : null;
67
+ out.push('**Acceptance criteria**', '');
68
+ out.push(results ? '| AC | Verification | Tasks | Tests | Result |' : '| AC | Verification | Tasks | Tests |');
69
+ out.push(results ? '|---|---|---|---|---|' : '|---|---|---|---|');
70
+ for (const ac of feature.spec.parsed.acs) {
71
+ const files = [...(tests.get(ac.id) ?? [])].join(', ');
72
+ const manual = ac.verification === 'manual';
73
+ const row = `| ${ac.id} | ${ac.verification} | ${tasksFor(ac.id)} | ${manual ? 'manual' : files || '**missing**'} |`;
74
+ if (!results)
75
+ out.push(row);
76
+ else
77
+ out.push(`${row} ${manual ? '-' : resultLabel(results.get(ac.id)).replace(/^(failed|not run|skipped)$/, '**$1**')} |`);
78
+ }
79
+ out.push('');
80
+ if (results)
81
+ out.push(`Results from ${loaded.files.map((f) => `\`${f.file}\``).join(', ')}.`, '');
82
+ else
83
+ out.push('Test coverage is by AC id in test files (existence only).', '');
84
+ const manual = feature.spec.parsed.acs.filter((ac) => ac.verification === 'manual');
85
+ if (manual.length && acceptedBy) {
86
+ out.push(`**Manual ACs, checked by hand by ${acceptedBy.by} when accepting:**`, '');
87
+ for (const ac of manual)
88
+ out.push(`- [x] ${ac.id}`);
89
+ out.push('');
90
+ }
91
+ else if (manual.length) {
92
+ out.push('**Check by hand before accepting (manual ACs):**', '');
93
+ for (const ac of manual)
94
+ out.push(`- [ ] ${ac.id}`);
95
+ out.push('');
96
+ }
97
+ }
98
+ if (feature.reviews.records.length) {
99
+ out.push('**Reviews**', '', '| Review | Step | Round | Verdict | Findings | Isolation |', '|---|---|---|---|---|---|');
100
+ for (const r of feature.reviews.records) {
101
+ out.push(`| ${r.id} | ${r.step} | ${r.round} | ${r.verdict} | ${r.findings?.length ?? 0} | ${r.reviewer?.isolation ?? 'unknown'} |`);
102
+ }
103
+ out.push('');
104
+ const weak = feature.reviews.records.filter((r) => r.reviewer?.isolation !== 'agent');
105
+ if (weak.length)
106
+ out.push(`Reviews without an isolated reviewer agent: ${weak.map((r) => r.id).join(', ')}.`, '');
107
+ const granted = readLog(feature.dir).filter((e) => e.event === 'round-granted');
108
+ if (granted.length)
109
+ out.push(`Rounds beyond the limit, allowed by the user: ${granted.map((e) => `${e.step} round ${e.round}`).join(', ')}.`, '');
110
+ }
111
+ const open = feature.findings.filter((f) => f.status === 'open');
112
+ const accepted = feature.findings.filter((f) => f.status === 'accepted');
113
+ if (open.length) {
114
+ out.push('**Open findings**', '');
115
+ for (const f of open)
116
+ out.push(`- ${f.id} [${f.severity}] ${f.issue}`);
117
+ out.push('');
118
+ }
119
+ if (accepted.length) {
120
+ out.push('**Accepted findings**', '');
121
+ for (const f of accepted) {
122
+ const a = feature.approvals.accepted.find((x) => x.finding === f.id);
123
+ out.push(`- ${f.id} [${f.severity}] ${f.issue} (accepted by ${a?.by}: ${a?.reason})`);
124
+ }
125
+ out.push('');
126
+ }
127
+ const amendments = feature.amendments.filter((a) => a.status !== 'lapsed');
128
+ if (amendments.length) {
129
+ out.push('**Scope amendments**', '');
130
+ for (const a of amendments)
131
+ out.push(`- ${a.id} (${a.task}, ${a.status}): ${a.paths.join(', ')}: ${a.reason}`);
132
+ out.push('');
133
+ }
134
+ return out;
135
+ }
136
+ /** agjan pr-summary [--feature <slug>]: prints the PR description in Markdown (design 6.6). */
137
+ export function run(ctx, argv) {
138
+ const { values } = parseArgs({ args: argv, options: { feature: { type: 'string' }, base: { type: 'string' } } });
139
+ overrideBase(ctx, values.base);
140
+ const { report, features, files, policy } = runChecks(ctx, 'ci', values.feature);
141
+ const out = ['## agjan summary', ''];
142
+ if (features.length === 0)
143
+ out.push('No agjan feature in this change.', '');
144
+ for (const feature of features)
145
+ out.push(...featureSection(ctx, feature));
146
+ const code = files.filter((f) => !f.startsWith(`${FEATURES_DIR}/`) && !f.startsWith('.agjan/'));
147
+ out.push(`**Changed files** (${code.length} outside ${FEATURES_DIR}/)`, '');
148
+ for (const f of code)
149
+ out.push(`- ${f}`);
150
+ if (code.length)
151
+ out.push('');
152
+ if (files.includes(`${FEATURES_DIR}/project.md`))
153
+ out.push('The baseline `docs/agjan/project.md` is updated in this change.', '');
154
+ if (policy.length) {
155
+ out.push('**Policy changes** (these change the rules that check this PR)', '');
156
+ for (const p of policy)
157
+ out.push(`- ${p}`);
158
+ out.push('');
159
+ }
160
+ const state = report.errors > 0 ? `**failing**: ${report.errors} error(s)` : 'passing';
161
+ out.push(`**agjan check --ci**: ${state}, ${report.warnings} warning(s)`, '');
162
+ for (const item of report.items.filter((i) => i.level === 'error'))
163
+ out.push(`- ${item.scope}: ${item.message}`);
164
+ if (report.errors)
165
+ out.push('');
166
+ ctx.out(highlightMarkdown(ctx.style, out.join('\n').trimEnd()));
167
+ return 0;
168
+ }
@@ -0,0 +1,42 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { relative } from 'node:path';
3
+ import { parseArgs } from 'node:util';
4
+ import { writeProgress } from '../progress-view.js';
5
+ import { markLine, tone } from '../ui.js';
6
+ /** Opens a file with the system's default application; failures are reported, not thrown. */
7
+ function openFile(file) {
8
+ const [cmd, args] = process.platform === 'win32' ? ['cmd', ['/c', 'start', '""', file]] : [process.platform === 'darwin' ? 'open' : 'xdg-open', [file]];
9
+ try {
10
+ const child = spawn(cmd, args, { stdio: 'ignore', detached: true });
11
+ child.on('error', () => { });
12
+ child.unref();
13
+ return true;
14
+ }
15
+ catch {
16
+ return false;
17
+ }
18
+ }
19
+ /** agjan progress [--open]: regenerates the progress pages and prints the overview. */
20
+ export function run(ctx, argv) {
21
+ const { values } = parseArgs({ args: argv, options: { open: { type: 'boolean' } } });
22
+ const s = ctx.style;
23
+ const result = writeProgress(ctx, { now: Date.parse(ctx.now()) });
24
+ for (const line of markLine(s, ctx.kit, 'progress'))
25
+ ctx.out(line);
26
+ if (!result) {
27
+ ctx.err('agjan progress: the pages could not be generated; run npx agjan check for details');
28
+ return 1;
29
+ }
30
+ if (!result.models.length)
31
+ ctx.out('no features, fixes or map runs yet');
32
+ for (const m of result.models) {
33
+ const turn = m.turn === 'you' ? s.violet('your turn') : m.turn === 'merged' ? tone(s, 'merged') : s.cyan('agent working');
34
+ const stage = m.stages[Math.min(m.at, m.stages.length - 1)];
35
+ ctx.out(`${s.bold(m.key.padEnd(6))} ${m.slug.padEnd(34)} ${stage.padEnd(15)} ${turn}${m.turn === 'merged' ? '' : s.gray(` · ${m.now}`)}`);
36
+ }
37
+ const html = relative(ctx.root, result.html).split('\\').join('/');
38
+ ctx.out('', `${s.gray('overview')} ${html} ${s.gray('· per unit: docs/agjan/<unit>/progress.md')}`);
39
+ if (values.open && !openFile(result.html))
40
+ ctx.out(`open ${html} in a browser`);
41
+ return 0;
42
+ }
@@ -0,0 +1,105 @@
1
+ import { writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { parseArgs } from 'node:util';
4
+ import { FEATURES_DIR, loadFeature, selectFeature } from '../feature.js';
5
+ import { readLog } from '../log.js';
6
+ import { usageBetween } from '../usage.js';
7
+ export const REPORT_FILE = 'report.md';
8
+ function minutes(ms) {
9
+ if (ms < 60_000)
10
+ return `${Math.round(ms / 1000)}s`;
11
+ const m = Math.round(ms / 60_000);
12
+ return m < 60 ? `${m}m` : `${Math.floor(m / 60)}h ${m % 60}m`;
13
+ }
14
+ function tokens(n) {
15
+ return n >= 10_000 ? `${(n / 1000).toFixed(0)}k` : String(n);
16
+ }
17
+ function sum(records) {
18
+ const total = { input: 0, cacheRead: 0, cacheWrite: 0, output: 0 };
19
+ for (const r of records)
20
+ for (const k of Object.keys(total))
21
+ total[k] += r[k];
22
+ return total;
23
+ }
24
+ function models(records) {
25
+ return [...new Set(records.map((r) => r.model))].join(', ') || '-';
26
+ }
27
+ /**
28
+ * Spans of the feature's life from its log (design 12.1): each step runs from its
29
+ * `step` event to the next `step` or `gate-requested` event; each gate wait runs from
30
+ * `gate-requested` to the matching approval or rejection.
31
+ */
32
+ export function spans(events, end) {
33
+ const out = [];
34
+ const times = events.map((e) => Date.parse(e.at_utc));
35
+ events.forEach((event, i) => {
36
+ const at = times[i];
37
+ if (event.event === 'step') {
38
+ const next = events.findIndex((e, j) => j > i && ['step', 'gate-requested', 'waiting'].includes(e.event));
39
+ const label = [event.stage, event.task, event.role].filter(Boolean).join(' ');
40
+ out.push({ kind: 'step', label, from: at, to: next === -1 ? end : times[next] });
41
+ }
42
+ if (event.event === 'gate-requested') {
43
+ const done = events.findIndex((e, j) => j > i && (e.event === 'approved' || e.event === 'rejected'));
44
+ out.push({ kind: 'gate', label: `gate ${event.gate}`, from: at, to: done === -1 ? end : times[done], open: done === -1 });
45
+ }
46
+ // The agent stopped for the user: waiting until its next step.
47
+ if (event.event === 'waiting') {
48
+ const next = events.findIndex((e, j) => j > i && e.event === 'step');
49
+ out.push({ kind: 'gate', label: 'waiting for you', from: at, to: next === -1 ? end : times[next], open: next === -1 });
50
+ }
51
+ });
52
+ return out;
53
+ }
54
+ /** report.md for a feature (design 12.2). */
55
+ export function buildReport(root, feature, { now = Date.now(), homes = {} } = {}) {
56
+ const events = readLog(feature.dir);
57
+ const lines = [`# Report: ${feature.slug} (${feature.key})`, '', `<!-- Generated by agjan report at ${new Date(now).toISOString().replace(/\.\d{3}Z$/, 'Z')}. Do not edit. -->`, ''];
58
+ if (events.length === 0)
59
+ return [...lines, 'No log events yet.', ''].join('\n');
60
+ const start = Date.parse(events[0].at_utc);
61
+ const list = spans(events, now);
62
+ const usage = usageBetween(root, start, now, homes);
63
+ const inSpan = (span) => usage.filter((r) => r.at >= span.from && r.at < span.to);
64
+ const steps = list.filter((s) => s.kind === 'step');
65
+ const gates = list.filter((s) => s.kind === 'gate');
66
+ const active = steps.reduce((t, s) => t + (s.to - s.from), 0);
67
+ const waiting = gates.reduce((t, s) => t + (s.to - s.from), 0);
68
+ const total = sum(usage);
69
+ const reviewer = usage.filter((r) => r.agent === 'subagent');
70
+ lines.push('## Summary', '');
71
+ lines.push(`| | |`, `|---|---|`);
72
+ lines.push(`| Time window | ${events[0].at_utc} to ${new Date(now).toISOString().replace(/\.\d{3}Z$/, 'Z')} |`);
73
+ lines.push(`| Active work (steps) | ${minutes(active)} |`);
74
+ lines.push(`| Waiting at gates | ${minutes(waiting)}${gates.some((g) => g.open) ? ' (a gate is still open)' : ''} |`);
75
+ lines.push(`| Reviews | ${feature.reviews.records.length} (${feature.reviews.records.filter((r) => r.verdict === 'blocked').length} blocked) |`);
76
+ if (usage.length) {
77
+ lines.push(`| Tokens: input / cache read / cache write / output | ${tokens(total.input)} / ${tokens(total.cacheRead)} / ${tokens(total.cacheWrite)} / ${tokens(total.output)} |`);
78
+ lines.push(`| Share of output by reviewer agents | ${total.output ? Math.round((sum(reviewer).output / total.output) * 100) : 0}% |`);
79
+ lines.push(`| Models | ${models(usage)} |`);
80
+ }
81
+ else {
82
+ lines.push('| Tokens and models | unknown: no host session records found for this folder and time window |');
83
+ }
84
+ lines.push('');
85
+ lines.push('## Steps and gates', '', '| Step | Start | Duration | Input | Output | Models |', '|---|---|---|---|---|---|');
86
+ for (const s of list) {
87
+ const r = inSpan(s);
88
+ const t = sum(r);
89
+ const when = new Date(s.from).toISOString().slice(11, 16);
90
+ lines.push(`| ${s.label}${s.open ? ' (open)' : ''} | ${when} | ${minutes(s.to - s.from)} | ${r.length ? tokens(t.input + t.cacheRead + t.cacheWrite) : '-'} | ${r.length ? tokens(t.output) : '-'} | ${models(r)} |`);
91
+ }
92
+ lines.push('');
93
+ lines.push('Durations come from `log.jsonl`. Tokens and models come from the hosts\' session records (Claude Code, GitHub Copilot CLI) for this ' +
94
+ 'folder within each time span; other work in the same folder at the same time is included.', '');
95
+ return lines.join('\n');
96
+ }
97
+ /** agjan report [--feature <slug>]: writes docs/agjan/<slug>/report.md. */
98
+ export function run(ctx, argv) {
99
+ const { values } = parseArgs({ args: argv, options: { feature: { type: 'string' } } });
100
+ const feature = loadFeature(ctx.root, selectFeature(ctx.root, ctx.config, values.feature));
101
+ const text = buildReport(ctx.root, feature, { now: Date.parse(ctx.now()) });
102
+ writeFileSync(join(feature.dir, REPORT_FILE), text);
103
+ ctx.out(`wrote ${FEATURES_DIR}/${feature.slug}/${REPORT_FILE}`);
104
+ return 0;
105
+ }
@@ -0,0 +1,146 @@
1
+ import { parseArgs } from 'node:util';
2
+ import { serve } from '../mcp.js';
3
+ import { buildContextText, parseStep } from '../review.js';
4
+ import { loadFeature, selectFeature } from '../feature.js';
5
+ import { appendLog } from '../log.js';
6
+ import { reviewerFor, roundState } from '../review-policy.js';
7
+ import { highlightMarkdown, tone } from '../ui.js';
8
+ import { AgjanError, UsageError } from '../errors.js';
9
+ /** agjan mcp [--host <name>] [--isolation agent|fork|none]: the agjan MCP server on stdio. */
10
+ export function mcp(ctx, argv) {
11
+ const { values } = parseArgs({ args: argv, options: { host: { type: 'string' }, isolation: { type: 'string' } } });
12
+ const isolation = values.isolation ?? 'unknown';
13
+ if (!['agent', 'shared', 'fork', 'none', 'unknown'].includes(isolation)) {
14
+ throw new UsageError('--isolation must be agent, shared, fork or none');
15
+ }
16
+ // Resolve the repository now so a misconfigured server fails at start, not on first call.
17
+ void ctx.root;
18
+ return serve(ctx, { host: values.host ?? 'unknown', isolation: isolation });
19
+ }
20
+ /** agjan review show | report | extend: dispatches to the subcommand. */
21
+ export function run(ctx, argv) {
22
+ if (argv[0] === 'extend')
23
+ return extend(ctx, argv.slice(1));
24
+ if (argv[0] === 'report')
25
+ return report(ctx, argv.slice(1));
26
+ return show(ctx, argv);
27
+ }
28
+ const VERDICT = { pass: '✅ pass', 'pass-with-notes': '✅ pass with notes', blocked: '⛔ blocked' };
29
+ const MARK = { pass: '✅', 'pass-with-notes': '✅', blocked: '⛔' };
30
+ const SEVERITY = { blocker: '🔴', major: '🟠', minor: '🟡' };
31
+ /** One line of an issue, at most `max` characters. */
32
+ function oneLine(text, max = 140) {
33
+ const line = String(text ?? '').replace(/\s+/g, ' ').trim();
34
+ return line.length > max ? `${line.slice(0, max - 1)}…` : line;
35
+ }
36
+ /** What the writer does after this review (design 7.4), in the user's words. */
37
+ function nextAfter(feature, config, record) {
38
+ const state = roundState(feature, config, record.step);
39
+ const status = new Map(feature.findings.map((f) => [f.id, f.status]));
40
+ const open = (severity) => record.findings.filter((f) => f.severity === severity && status.get(f.id) === 'open').length;
41
+ if (record.verdict === 'blocked') {
42
+ if (state.exhausted)
43
+ return `round limit reached (${state.round} of ${state.limit}): the agent asks you whether to run another round`;
44
+ return `the agent fixes ${open('blocker')} blocker(s), then review round ${state.next} of ${state.limit}`;
45
+ }
46
+ const majors = open('major');
47
+ if (majors)
48
+ return `the agent fixes the ${majors} major finding(s) it agrees with (another round), or goes on; minor notes stay open for the PR`;
49
+ return record.verdict === 'pass' ? 'the agent goes on with the next step' : 'minor notes stay open (the PR summary lists them); the agent goes on';
50
+ }
51
+ /**
52
+ * agjan review report [--step <step>] [--feature <slug>]: the latest review round as a
53
+ * short Markdown report for the user (verdict, findings by severity, the rounds of this
54
+ * loop, what happens next). Agents put it into their message after every review, so the
55
+ * user sees what the reviewer found; the markers are emoji, which every host shows.
56
+ */
57
+ export function report(ctx, argv) {
58
+ const { values, positionals } = parseArgs({ args: argv, options: { step: { type: 'string' }, feature: { type: 'string' } }, allowPositionals: true });
59
+ if (positionals.length)
60
+ throw new UsageError('usage: agjan review report [--step <step>] [--feature <slug>]');
61
+ const feature = loadFeature(ctx.root, selectFeature(ctx.root, ctx.config, values.feature));
62
+ const records = feature.reviews.records.filter((r) => !values.step || r.step === values.step);
63
+ const record = records.at(-1);
64
+ if (!record)
65
+ throw new AgjanError(`no review recorded for ${feature.slug}${values.step ? ` (step ${values.step})` : ''}`);
66
+ const { limit } = roundState(feature, ctx.config, record.step);
67
+ const status = new Map(feature.findings.map((f) => [f.id, f.status]));
68
+ const out = [`**🔍 Review ${record.id} · ${record.step} · round ${record.round} of ${limit} · ${VERDICT[record.verdict]}**`];
69
+ const isolation = record.reviewer?.isolation === 'agent' ? 'isolated' : `isolation ${record.reviewer?.isolation ?? 'unknown'}`;
70
+ out.push(`- reviewer: ${reviewerFor(ctx.config, record.step)} on ${record.reviewer?.host ?? 'unknown host'}, ${isolation}`);
71
+ const order = { blocker: 0, major: 1, minor: 2 };
72
+ for (const f of [...record.findings].sort((a, b) => order[a.severity] - order[b.severity])) {
73
+ const where = f.file ? ` · \`${f.file}${f.line ? `:${f.line}` : ''}\`` : '';
74
+ const state = status.get(f.id) === 'open' ? '' : ` (${status.get(f.id)})`;
75
+ out.push(`- ${SEVERITY[f.severity]} **${f.id}** ${f.severity}${state}${where} · ${oneLine(f.issue)}`);
76
+ }
77
+ if (!record.findings.length)
78
+ out.push('- no findings');
79
+ if (record.resolves?.length)
80
+ out.push(`- ✅ resolved: ${record.resolves.join(', ')}`);
81
+ const mine = new Set(record.findings.map((f) => f.id));
82
+ const earlier = feature.findings.filter((f) => f.step === record.step && f.status === 'open' && !mine.has(f.id));
83
+ if (earlier.length)
84
+ out.push(`- still open from earlier rounds: ${earlier.map((f) => `${SEVERITY[f.severity]} ${f.id}`).join(', ')}`);
85
+ // The rounds of this correction loop, oldest first: shows the cycles between the agents.
86
+ const step = feature.reviews.records.filter((r) => r.step === record.step && r.at_utc <= record.at_utc);
87
+ const start = step.findLastIndex((r) => r.round === 1);
88
+ const loop = step.slice(Math.max(start, 0));
89
+ if (loop.length > 1)
90
+ out.push(`- rounds: ${loop.map((r) => `${r.id} ${MARK[r.verdict]}`).join(' → ')}`);
91
+ out.push(`- ➜ next: ${nextAfter(feature, ctx.config, record)}`);
92
+ ctx.out(highlightMarkdown(ctx.style, out.join('\n')));
93
+ return 0;
94
+ }
95
+ /**
96
+ * agjan review extend <step> [--feature <slug>]: one more correction round for a step
97
+ * that is still blocked at its round limit (design 7.4). The agent runs it only after
98
+ * the user said yes to another round; status, the report and the PR summary show it.
99
+ */
100
+ export function extend(ctx, argv) {
101
+ const { values, positionals } = parseArgs({ args: argv, options: { feature: { type: 'string' } }, allowPositionals: true });
102
+ if (positionals.length !== 1)
103
+ throw new UsageError('usage: agjan review extend <step> [--feature <slug>]');
104
+ const step = positionals[0];
105
+ const feature = loadFeature(ctx.root, selectFeature(ctx.root, ctx.config, values.feature));
106
+ const state = roundState(feature, ctx.config, step);
107
+ if (!state.exhausted) {
108
+ const why = state.last ? `round ${state.round} of ${state.limit}, ${state.last.verdict}` : 'no review yet';
109
+ throw new AgjanError(`the ${step} review has not used up its rounds (${why}); another round needs no extension`);
110
+ }
111
+ appendLog(feature.dir, ctx.now(), 'round-granted', { step, round: state.limit + 1 });
112
+ ctx.out(`${ctx.style.green('granted')} round ${state.limit + 1} for ${ctx.style.bold(step)}: fix the blockers, then ask for the review again`);
113
+ return 0;
114
+ }
115
+ /**
116
+ * agjan review show [--step <step>] [--feature <slug>]: read-only. Without --step it lists
117
+ * the review records; with --step it prints the context a reviewer would get.
118
+ * There is deliberately no CLI command that records a review.
119
+ */
120
+ export function show(ctx, argv) {
121
+ const { values, positionals } = parseArgs({
122
+ args: argv,
123
+ options: { step: { type: 'string' }, feature: { type: 'string' } },
124
+ allowPositionals: true,
125
+ });
126
+ if (positionals[0] !== 'show' || positionals.length !== 1)
127
+ throw new UsageError('usage: agjan review show [--step <step>] [--feature <slug>] | agjan review extend <step>');
128
+ const feature = loadFeature(ctx.root, selectFeature(ctx.root, ctx.config, values.feature));
129
+ if (values.step) {
130
+ ctx.out(buildContextText(ctx.root, ctx.config, feature, parseStep(values.step, feature, ctx.config)));
131
+ return 0;
132
+ }
133
+ if (feature.reviews.records.length === 0) {
134
+ ctx.out(`no reviews recorded for ${feature.slug}`);
135
+ return 0;
136
+ }
137
+ const status = new Map(feature.findings.map((f) => [f.id, f.status]));
138
+ for (const r of feature.reviews.records) {
139
+ const st = ctx.style;
140
+ const meta = st.gray(`(${r.at_utc}, ${r.reviewer?.host ?? '?'}, isolation ${r.reviewer?.isolation ?? '?'})`);
141
+ ctx.out(`${st.bold(r.id)} ${r.step} round ${r.round}: ${tone(st, r.verdict)} ${meta}`);
142
+ for (const f of r.findings ?? [])
143
+ ctx.out(` ${st.cyan(f.id)} [${tone(st, f.severity)}] ${tone(st, status.get(f.id))}: ${f.issue}`);
144
+ }
145
+ return 0;
146
+ }