requirementbot 0.0.0-stage → 0.1.0

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 (82) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +197 -2
  3. package/bin/requirementbot.js +21 -0
  4. package/package.json +53 -4
  5. package/prompts/README.md +18 -0
  6. package/prompts/check.md +15 -0
  7. package/prompts/fix.md +4 -0
  8. package/prompts/from-code.md +12 -0
  9. package/prompts/from-docs.md +11 -0
  10. package/prompts/from-issues.md +14 -0
  11. package/prompts/mdq.md +8 -0
  12. package/prompts/partials/non-interactive.md +1 -0
  13. package/prompts/partials/subagents.md +1 -0
  14. package/prompts/report.md +8 -0
  15. package/prompts/system.md +9 -0
  16. package/skills/SOURCE.md +14 -0
  17. package/skills/catalog-features/SKILL.md +168 -0
  18. package/skills/catalog-features/references/layout.md +87 -0
  19. package/skills/detect-product-mismatches/SKILL.md +147 -0
  20. package/skills/detect-product-mismatches/references/features.md +84 -0
  21. package/skills/detect-product-mismatches/references/layout.md +99 -0
  22. package/skills/pull-request-diff-analyzer/SKILL.md +141 -0
  23. package/skills/qa-explain-behavior/SKILL.md +112 -0
  24. package/skills/qa-explain-behavior/references/answer-shapes.md +116 -0
  25. package/skills/qa-explain-behavior/references/examples.md +157 -0
  26. package/skills/qa-pr-requirements-analyzer/SKILL.md +149 -0
  27. package/skills/qa-pr-requirements-analyzer/references/summary-example.md +54 -0
  28. package/skills/qa-requirement-reviewer/SKILL.md +126 -0
  29. package/skills/qa-requirement-reviewer/references/requirements_reviewer_examples.md +128 -0
  30. package/skills/qa-thinking/SKILL.md +46 -0
  31. package/skills/requirements-from-code/SKILL.md +114 -0
  32. package/skills/requirements-from-code/references/behaviors.md +42 -0
  33. package/skills/requirements-from-code/references/layout.md +100 -0
  34. package/skills/requirements-from-expected/SKILL.md +116 -0
  35. package/skills/requirements-from-expected/references/behaviors.md +49 -0
  36. package/skills/requirements-from-expected/references/layout.md +74 -0
  37. package/skills/requirements-from-expected/references/merge.md +34 -0
  38. package/skills/write-user-story/SKILL.md +42 -0
  39. package/src/agent/agent.js +278 -0
  40. package/src/agent/auth.js +209 -0
  41. package/src/agent/prompt.js +36 -0
  42. package/src/branding.js +27 -0
  43. package/src/cli.js +26 -0
  44. package/src/commands/agent-command.js +61 -0
  45. package/src/commands/check.js +26 -0
  46. package/src/commands/command.js +40 -0
  47. package/src/commands/connect.js +33 -0
  48. package/src/commands/disconnect.js +18 -0
  49. package/src/commands/generate-from-code.js +20 -0
  50. package/src/commands/generate-from-docs.js +38 -0
  51. package/src/commands/generate-from-issues.js +41 -0
  52. package/src/commands/index.js +40 -0
  53. package/src/commands/login.js +44 -0
  54. package/src/commands/logout.js +17 -0
  55. package/src/commands/models.js +11 -0
  56. package/src/commands/pull.js +15 -0
  57. package/src/commands/push.js +29 -0
  58. package/src/commands/query.js +31 -0
  59. package/src/commands/report.js +23 -0
  60. package/src/commands/skills.js +20 -0
  61. package/src/commands/sources.js +16 -0
  62. package/src/commands/update-from-code.js +7 -0
  63. package/src/commands/update-from-docs.js +7 -0
  64. package/src/commands/update-from-issues.js +7 -0
  65. package/src/config.js +90 -0
  66. package/src/files.js +25 -0
  67. package/src/github.js +50 -0
  68. package/src/http.js +19 -0
  69. package/src/requirements.js +139 -0
  70. package/src/sources/adf.js +48 -0
  71. package/src/sources/github.js +81 -0
  72. package/src/sources/index.js +41 -0
  73. package/src/sources/jira.js +135 -0
  74. package/src/sources/pages.js +67 -0
  75. package/src/sources/source.js +60 -0
  76. package/src/transports/confluence.js +114 -0
  77. package/src/transports/git.js +90 -0
  78. package/src/transports/github.js +42 -0
  79. package/src/transports/index.js +36 -0
  80. package/src/transports/notion.js +108 -0
  81. package/src/transports/page-tree.js +119 -0
  82. package/src/transports/transport.js +41 -0
@@ -0,0 +1,17 @@
1
+ import { Auth } from '../agent/auth.js';
2
+ import { log } from '../branding.js';
3
+ import { Command } from './command.js';
4
+
5
+ export class Logout extends Command {
6
+ static command = 'logout';
7
+ static description = 'remove a stored provider credential';
8
+
9
+ static configure(cmd) {
10
+ return cmd.argument('<provider>', 'provider id, e.g. anthropic, codex');
11
+ }
12
+
13
+ async run(providerId) {
14
+ await (await Auth.create()).logout(providerId);
15
+ log(`Signed out of ${providerId}`);
16
+ }
17
+ }
@@ -0,0 +1,11 @@
1
+ import { Agent } from '../agent/agent.js';
2
+ import { Command } from './command.js';
3
+
4
+ export class Models extends Command {
5
+ static command = 'models';
6
+ static description = 'list models with configured API keys';
7
+
8
+ async run() {
9
+ for (const model of await Agent.models()) process.stdout.write(`${model}\n`);
10
+ }
11
+ }
@@ -0,0 +1,15 @@
1
+ import { Transports } from '../transports/index.js';
2
+ import { Push } from './push.js';
3
+
4
+ export class Pull extends Push {
5
+ static command = 'pull';
6
+ static description = 'pull requirements from a destination into the requirements folder';
7
+ direction = 'pull';
8
+
9
+ static configure(cmd) {
10
+ return cmd
11
+ .argument('[destination]', `${Transports.usage}; the last one when omitted`)
12
+ .option('-p, --path <dir>', 'git/github: folder inside the repository', 'requirements')
13
+ .option('--dry-run', 'show what would change without writing');
14
+ }
15
+ }
@@ -0,0 +1,29 @@
1
+ import { log, muted } from '../branding.js';
2
+ import { Transports } from '../transports/index.js';
3
+ import { Command } from './command.js';
4
+
5
+ export class Push extends Command {
6
+ static command = 'push';
7
+ static description = 'push the requirements folder to a destination';
8
+ direction = 'push';
9
+
10
+ static configure(cmd) {
11
+ return cmd
12
+ .argument('[destination]', `${Transports.usage}; the last one when omitted`)
13
+ .option('-p, --path <dir>', 'git/github: folder inside the repository', 'requirements')
14
+ .option('--message <text>', 'git/github: commit message and PR title', 'Update requirements')
15
+ .option('--title-prefix <text>', 'confluence: prefix for page titles (titles are unique per space)', '')
16
+ .option('--dry-run', 'show what would change without writing');
17
+ }
18
+
19
+ async run(destination, options) {
20
+ const transport = Transports.create(destination, this.config);
21
+ if (this.direction === 'push' && !this.requirements.exists) throw new Error(`Nothing to push: ${this.requirements.root} does not exist`);
22
+ const arrow = this.direction === 'push' ? '→' : '←';
23
+ log(`${this.direction === 'push' ? 'Pushing' : 'Pulling'} ${muted(this.requirements.root)} ${arrow} ${transport}`);
24
+ await transport[this.direction](this.requirements.root, options);
25
+ if (options.dryRun) return;
26
+ this.config.rememberDestination(transport.kind, transport.target);
27
+ this.config.save();
28
+ }
29
+ }
@@ -0,0 +1,31 @@
1
+ import { resolve } from 'node:path';
2
+ import { brand } from '../branding.js';
3
+ import { Command } from './command.js';
4
+
5
+ export class Query extends Command {
6
+ static command = 'query';
7
+ static description = 'query requirements markdown with mdq selectors (no AI)';
8
+
9
+ static configure(cmd) {
10
+ return cmd
11
+ .argument('<selector>', 'mdq selector, e.g. \'section("Impact") paragraph[0]\'')
12
+ .argument('[files...]', 'markdown files or folders (default: requirements folder)')
13
+ .option('-j, --json', 'tables as JSON rows')
14
+ .option('-c, --count', 'print match counts only');
15
+ }
16
+
17
+ run(selector, files, options) {
18
+ const paths = files.length ? files.map((f) => resolve(this.cwd, f)) : [this.requirements.root];
19
+ const matches = this.requirements.query(selector, paths, { json: options.json });
20
+ if (!matches.length) process.exitCode = 1;
21
+ if (options.count) {
22
+ for (const m of matches) process.stdout.write(`${m.count}\t${m.file}\n`);
23
+ process.stdout.write(`${matches.reduce((n, m) => n + m.count, 0)}\ttotal\n`);
24
+ } else if (options.json) {
25
+ const rows = matches.map(({ file, rows: tableRows, text }) => ({ file, rows: tableRows?.length ? tableRows : undefined, text }));
26
+ process.stdout.write(`${JSON.stringify(rows, null, 2)}\n`);
27
+ } else {
28
+ for (const m of matches) process.stdout.write(`${brand(`── ${m.file}`)}\n${m.text.trim()}\n\n`);
29
+ }
30
+ }
31
+ }
@@ -0,0 +1,23 @@
1
+ import { writeFileSync } from 'node:fs';
2
+ import { resolve } from 'node:path';
3
+ import { Prompt } from '../agent/prompt.js';
4
+ import { AgentCommand } from './agent-command.js';
5
+
6
+ export class Report extends AgentCommand {
7
+ static command = 'report';
8
+ static description = 'answer a question about the requirements with a brief markdown report';
9
+
10
+ static configure(cmd) {
11
+ return super.configure(cmd)
12
+ .argument('<question...>', 'what to report, e.g. "all High priority mismatches"')
13
+ .option('-f, --file <path>', 'also save the report to a file');
14
+ }
15
+
16
+ async run(words, options) {
17
+ if (!this.requirements.exists) throw new Error(`No requirements in ${this.rel(this.requirements.root)}. Generate them first.`);
18
+ const prompt = new Prompt('report', { question: words.join(' '), output: this.rel(this.requirements.root) });
19
+ const answer = (await (await this.agent(options, { quiet: !options.verbose })).run(prompt)).trim();
20
+ process.stdout.write(`${answer}\n`);
21
+ if (options.file) writeFileSync(resolve(this.cwd, options.file), `${answer}\n`);
22
+ }
23
+ }
@@ -0,0 +1,20 @@
1
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import matter from 'gray-matter';
4
+ import { brand, muted } from '../branding.js';
5
+ import { SKILLS_DIR } from '../config.js';
6
+ import { Command } from './command.js';
7
+
8
+ export class Skills extends Command {
9
+ static command = 'skills';
10
+ static description = 'list bundled skills';
11
+
12
+ run() {
13
+ for (const name of readdirSync(SKILLS_DIR).sort()) {
14
+ const file = join(SKILLS_DIR, name, 'SKILL.md');
15
+ if (!existsSync(file)) continue;
16
+ const { data } = matter(readFileSync(file, 'utf8'));
17
+ process.stdout.write(`${brand(data.name || name)}\n ${muted(String(data.description || '').split('\n')[0].trim())}\n`);
18
+ }
19
+ }
20
+ }
@@ -0,0 +1,16 @@
1
+ import { brand, log, muted } from '../branding.js';
2
+ import { Command } from './command.js';
3
+
4
+ export class ListSources extends Command {
5
+ static command = 'sources';
6
+ static description = 'list connected sources';
7
+
8
+ run() {
9
+ const entries = Object.entries(this.config.sources);
10
+ if (!entries.length) return log('No sources connected. Try: requirementbot connect github:<repo url>');
11
+ for (const [name, s] of entries) {
12
+ const fetched = s.lastFetch ? muted(` fetched ${s.lastFetch}`) : '';
13
+ process.stdout.write(`${brand(name)} ${s.kind}:${s.target} ${muted(JSON.stringify(s.scope || {}))}${fetched}\n`);
14
+ }
15
+ }
16
+ }
@@ -0,0 +1,7 @@
1
+ import { GenerateFromCode } from './generate-from-code.js';
2
+
3
+ export class UpdateFromCode extends GenerateFromCode {
4
+ static command = 'update:from-code';
5
+ static description = 'update requirements after code changes since the last baseline commit';
6
+ mode = 'update';
7
+ }
@@ -0,0 +1,7 @@
1
+ import { GenerateFromDocs } from './generate-from-docs.js';
2
+
3
+ export class UpdateFromDocs extends GenerateFromDocs {
4
+ static command = 'update:from-docs';
5
+ static description = 'update requirements from changed user documentation';
6
+ mode = 'update';
7
+ }
@@ -0,0 +1,7 @@
1
+ import { GenerateFromIssues } from './generate-from-issues.js';
2
+
3
+ export class UpdateFromIssues extends GenerateFromIssues {
4
+ static command = 'update:from-issues';
5
+ static description = 'update requirements with issues changed since the last fetch';
6
+ mode = 'update';
7
+ }
package/src/config.js ADDED
@@ -0,0 +1,90 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { dirname, join, resolve } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+
6
+ export const PACKAGE_DIR = resolve(dirname(fileURLToPath(import.meta.url)), '..');
7
+ export const SKILLS_DIR = join(PACKAGE_DIR, 'skills');
8
+ export const PROMPTS_DIR = join(PACKAGE_DIR, 'prompts');
9
+
10
+ /**
11
+ * Project settings in `.requirementbot/config.json`: output folder, model, connected sources, last destinations.
12
+ */
13
+ export class Config {
14
+ static DIR_NAME = '.requirementbot';
15
+ static DEFAULT_OUTPUT = 'requirements';
16
+
17
+ /** Agent home shared by all projects: auth, models, user MCP servers. */
18
+ static homeDir() {
19
+ return process.env.REQUIREMENTBOT_HOME ? resolve(process.env.REQUIREMENTBOT_HOME) : join(homedir(), '.requirementbot');
20
+ }
21
+
22
+ static agentDir() {
23
+ return join(Config.homeDir(), 'agent');
24
+ }
25
+
26
+ static load(cwd = process.cwd()) {
27
+ const config = new Config(cwd);
28
+ if (existsSync(config.file)) Object.assign(config.data, JSON.parse(readFileSync(config.file, 'utf8')));
29
+ return config;
30
+ }
31
+
32
+ constructor(cwd) {
33
+ this.cwd = cwd;
34
+ /** @type {{ output: string, model?: string, sources: Record<string, { kind: string, target: string, scope?: object, lastFetch?: string }>, destination?: string, destinations?: Record<string, string> }} */
35
+ this.data = { output: Config.DEFAULT_OUTPUT, sources: {} };
36
+ }
37
+
38
+ get dir() {
39
+ return join(this.cwd, Config.DIR_NAME);
40
+ }
41
+
42
+ get cacheDir() {
43
+ return join(this.dir, 'cache');
44
+ }
45
+
46
+ get file() {
47
+ return join(this.dir, 'config.json');
48
+ }
49
+
50
+ get outputDir() {
51
+ return resolve(this.cwd, this.data.output || Config.DEFAULT_OUTPUT);
52
+ }
53
+
54
+ set output(value) {
55
+ if (value) this.data.output = value;
56
+ }
57
+
58
+ get model() {
59
+ return process.env.REQUIREMENTBOT_MODEL || this.data.model;
60
+ }
61
+
62
+ get sources() {
63
+ return this.data.sources;
64
+ }
65
+
66
+ /** Remember a push/pull destination so `push notion:` or a bare `push` can reuse it. */
67
+ rememberDestination(kind, target) {
68
+ this.data.destination = `${kind}:${target}`;
69
+ this.data.destinations = { ...this.data.destinations, [kind]: target };
70
+ }
71
+
72
+ destinationFor(kind) {
73
+ return this.data.destinations?.[kind];
74
+ }
75
+
76
+ get lastDestination() {
77
+ return this.data.destination;
78
+ }
79
+
80
+ save() {
81
+ mkdirSync(dirname(this.file), { recursive: true });
82
+ writeFileSync(this.file, `${JSON.stringify(this.data, null, 2)}\n`);
83
+ }
84
+ }
85
+
86
+ export function requireEnv(...names) {
87
+ const missing = names.filter((name) => !process.env[name]);
88
+ if (missing.length) throw new Error(`Missing environment variable(s): ${missing.join(', ')}`);
89
+ return names.map((name) => process.env[name]);
90
+ }
package/src/files.js ADDED
@@ -0,0 +1,25 @@
1
+ import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { dirname } from 'node:path';
3
+ import matter from 'gray-matter';
4
+
5
+ export function slugify(text, max = 60) {
6
+ return String(text)
7
+ .toLowerCase()
8
+ .normalize('NFKD')
9
+ .replace(/[^\w\s-]/g, '')
10
+ .trim()
11
+ .replace(/[\s_-]+/g, '-')
12
+ .slice(0, max)
13
+ .replace(/-+$/, '') || 'untitled';
14
+ }
15
+
16
+ export function writeMarkdown(path, data, body) {
17
+ mkdirSync(dirname(path), { recursive: true });
18
+ const clean = Object.fromEntries(Object.entries(data).filter(([, v]) => v !== undefined && v !== null && !(Array.isArray(v) && !v.length)));
19
+ writeFileSync(path, matter.stringify(`${body.trim()}\n`, clean));
20
+ }
21
+
22
+ export function resetDir(dir) {
23
+ rmSync(dir, { recursive: true, force: true });
24
+ mkdirSync(dir, { recursive: true });
25
+ }
package/src/github.js ADDED
@@ -0,0 +1,50 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { request } from './http.js';
3
+
4
+ /** GitHub REST access with `GITHUB_TOKEN`, `GH_TOKEN` or the logged-in `gh` CLI. */
5
+ export class GitHub {
6
+ /** Parse `https://github.com/org/repo`, `git@github.com:org/repo.git` or `org/repo`. */
7
+ static parseRepo(target) {
8
+ const match = String(target).trim().match(/(?:github\.com[/:])?([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?(?:[#?].*)?$/);
9
+ if (!match) throw new Error(`Not a GitHub repository: "${target}"`);
10
+ return { owner: match[1], repo: match[2] };
11
+ }
12
+
13
+ static token() {
14
+ if (process.env.GITHUB_TOKEN) return process.env.GITHUB_TOKEN;
15
+ if (process.env.GH_TOKEN) return process.env.GH_TOKEN;
16
+ try {
17
+ return execFileSync('gh', ['auth', 'token'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
18
+ } catch {
19
+ return undefined;
20
+ }
21
+ }
22
+
23
+ constructor(target) {
24
+ Object.assign(this, GitHub.parseRepo(target));
25
+ }
26
+
27
+ get fullName() {
28
+ return `${this.owner}/${this.repo}`;
29
+ }
30
+
31
+ /** @param {string} path relative to `/repos/{owner}/{repo}` */
32
+ api(path, options = {}) {
33
+ const token = GitHub.token();
34
+ return request(`https://api.github.com/repos/${this.fullName}${path}`, {
35
+ ...options,
36
+ headers: { Accept: 'application/vnd.github+json', ...(token ? { Authorization: `Bearer ${token}` } : {}), ...options.headers },
37
+ });
38
+ }
39
+
40
+ /** Open a pull request with `gh`, falling back to the REST API. */
41
+ async openPullRequest({ head, base, title, body }) {
42
+ try {
43
+ return execFileSync('gh', ['pr', 'create', '--repo', this.fullName, '--head', head, '--base', base, '--title', title, '--body', body], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
44
+ } catch (err) {
45
+ if (!GitHub.token()) throw new Error(`Branch ${head} pushed, but no PR opened: install gh or set GITHUB_TOKEN (${err.message})`);
46
+ const pr = await this.api('/pulls', { method: 'POST', json: { head, base, title, body } });
47
+ return pr.html_url;
48
+ }
49
+ }
50
+ }
package/src/http.js ADDED
@@ -0,0 +1,19 @@
1
+ /**
2
+ * fetch JSON with a readable error.
3
+ * @param {string} url
4
+ * @param {RequestInit & { json?: any }} options
5
+ */
6
+ export async function request(url, { json, headers = {}, ...options } = {}) {
7
+ const res = await fetch(url, {
8
+ ...options,
9
+ headers: { Accept: 'application/json', ...(json !== undefined ? { 'Content-Type': 'application/json' } : {}), ...headers },
10
+ body: json !== undefined ? JSON.stringify(json) : options.body,
11
+ });
12
+ if (!res.ok) {
13
+ const body = await res.text().catch(() => '');
14
+ throw new Error(`${options.method || 'GET'} ${url} → ${res.status} ${res.statusText}${body ? `: ${body.slice(0, 500)}` : ''}`);
15
+ }
16
+ if (res.status === 204) return undefined;
17
+ const text = await res.text();
18
+ return text ? JSON.parse(text) : undefined;
19
+ }
@@ -0,0 +1,139 @@
1
+ import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
2
+ import { basename, join, relative } from 'node:path';
3
+ import { mdq } from 'mdq-cli';
4
+ import { PageTree } from './transports/page-tree.js';
5
+
6
+ /**
7
+ * The requirements folder: where each generator writes, mdq queries over its pages,
8
+ * structure checks, and the root index.
9
+ *
10
+ * actual/<repo>/ generate:from-code (its mismatches/: code vs claims in the repo)
11
+ * expected/<source>/ generate:from-issues, generate:from-docs (its mismatches/: contradictions inside the source)
12
+ * mismatches/ check: mismatches between sources
13
+ *
14
+ * `actual` and `expected` are strict names (docs/structure.md): every source folder is inside one of them.
15
+ */
16
+ export class Requirements {
17
+ static ACTUAL = 'actual';
18
+ static EXPECTED = 'expected';
19
+ static FEATURE_SECTIONS = ['Behaviors'];
20
+ static SOURCE_MISMATCH_SECTIONS = ['Difference', 'Impact', 'Solution', 'Sources'];
21
+ static PRODUCT_MISMATCH_SECTIONS = ['Difference', 'Impact', 'Likely cause', 'Solution', 'Sources'];
22
+
23
+ constructor(root, cwd = process.cwd()) {
24
+ this.root = root;
25
+ this.cwd = cwd;
26
+ }
27
+
28
+ get exists() {
29
+ return existsSync(this.root);
30
+ }
31
+
32
+ /** How it works now: one folder per code repository. */
33
+ actualDir(repo) {
34
+ return join(this.root, Requirements.ACTUAL, repo);
35
+ }
36
+
37
+ /** What was intended to be built: one folder per issue tracker or docs source. */
38
+ expectedDir(source) {
39
+ return join(this.root, Requirements.EXPECTED, source);
40
+ }
41
+
42
+ get mismatchesDir() {
43
+ return join(this.root, 'mismatches');
44
+ }
45
+
46
+ /** Cataloged sources, for `check`. */
47
+ catalogs() {
48
+ const catalogs = [];
49
+ const add = (name, dir) => existsSync(join(dir, 'features', '.catalog')) && catalogs.push({ name, path: join(dir, 'features', '.catalog') });
50
+ for (const name of this.subdirs(Requirements.ACTUAL)) add(name, this.actualDir(name));
51
+ for (const name of this.subdirs(Requirements.EXPECTED)) add(name, this.expectedDir(name));
52
+ return catalogs;
53
+ }
54
+
55
+ /** Markdown files under `path`, skipping hidden folders such as `.catalog`. */
56
+ files(path = this.root) {
57
+ if (!existsSync(path)) return [];
58
+ if (statSync(path).isFile()) return path.endsWith('.md') ? [path] : [];
59
+ return readdirSync(path, { withFileTypes: true })
60
+ .filter((entry) => !entry.name.startsWith('.'))
61
+ .sort((a, b) => a.name.localeCompare(b.name))
62
+ .flatMap((entry) => {
63
+ const child = join(path, entry.name);
64
+ if (entry.isDirectory()) return this.files(child);
65
+ return entry.name.endsWith('.md') ? [child] : [];
66
+ });
67
+ }
68
+
69
+ /**
70
+ * Run an mdq selector over markdown files.
71
+ * @returns {{ file: string, count: number, text: string, rows?: object[] }[]}
72
+ */
73
+ query(selector, paths = [this.root], { json = false } = {}) {
74
+ return paths.flatMap((path) => this.files(path)).flatMap((file) => {
75
+ const result = mdq(readFileSync(file, 'utf8')).query(selector);
76
+ const count = result.count();
77
+ if (!count) return [];
78
+ const match = { file: relative(this.cwd, file), count, text: result.text() };
79
+ if (json) match.rows = result.rows();
80
+ return [match];
81
+ });
82
+ }
83
+
84
+ /**
85
+ * Check generated pages for the sections their skill layout requires.
86
+ * @param {string} dir a generated tree: a source folder in `actual/` or `expected/`, or product mismatches
87
+ * @param {'source'|'product-mismatches'} kind
88
+ * @returns {string[]} problems
89
+ */
90
+ validate(dir, kind = 'source') {
91
+ const problems = [];
92
+ if (!existsSync(join(dir, 'README.md'))) problems.push(`${relative(this.cwd, dir)}/README.md is missing`);
93
+ for (const file of this.files(dir).filter((f) => basename(f) !== 'README.md')) {
94
+ const rel = relative(this.cwd, file);
95
+ const inMismatches = rel.split(/[\\/]/).includes('mismatches');
96
+ if (kind === 'product-mismatches' && !inMismatches) continue;
97
+ const doc = mdq(readFileSync(file, 'utf8'));
98
+ if (!doc.query('h1').exists()) problems.push(`${rel}: no "# Title" heading`);
99
+ for (const section of this.requiredSections(kind, inMismatches)) {
100
+ if (!doc.section(section).exists()) problems.push(`${rel}: missing "## ${section}" section`);
101
+ }
102
+ if (!inMismatches && doc.section('Behaviors').exists() && !doc.query('section("Behaviors") item').exists() && !doc.query('section("Behaviors") h3').exists()) {
103
+ problems.push(`${rel}: "## Behaviors" lists no behaviors`);
104
+ }
105
+ }
106
+ return problems;
107
+ }
108
+
109
+ requiredSections(kind, inMismatches) {
110
+ if (!inMismatches) return Requirements.FEATURE_SECTIONS;
111
+ return kind === 'product-mismatches' ? Requirements.PRODUCT_MISMATCH_SECTIONS : Requirements.SOURCE_MISMATCH_SECTIONS;
112
+ }
113
+
114
+ /** Write the root README.md: one link per generated tree. */
115
+ writeIndex() {
116
+ const lines = ['# Requirements', '', 'Generated by [requirementbot](https://github.com/testomatio/requirementbot).', ''];
117
+ const section = (heading, entries) => entries.length && lines.push(`## ${heading}`, '', ...entries, '');
118
+ const sources = (role) => this.subdirs(role).map((name) => this.link(`${role}/${name}`, name));
119
+ section('Actual: how it works now', sources(Requirements.ACTUAL));
120
+ section('Expected: what was intended to be built', sources(Requirements.EXPECTED));
121
+ section('Mismatches inside sources', [Requirements.ACTUAL, Requirements.EXPECTED].flatMap((role) => this.subdirs(role)
122
+ .filter((name) => existsSync(join(this.root, role, name, 'mismatches', 'README.md')))
123
+ .map((name) => `- [${name}](${role}/${name}/mismatches/README.md)`)));
124
+ section('Mismatches between sources', existsSync(this.mismatchesDir) ? [this.link('mismatches', 'Mismatches')] : []);
125
+ if (lines.length > 4) writeFileSync(join(this.root, 'README.md'), `${lines.join('\n').trim()}\n`);
126
+ }
127
+
128
+ link(rel, fallback) {
129
+ const readme = join(this.root, rel, 'README.md');
130
+ const title = existsSync(readme) ? PageTree.splitTitle(readFileSync(readme, 'utf8')).title : undefined;
131
+ return `- [${title || fallback}](${rel}/README.md)`;
132
+ }
133
+
134
+ subdirs(group) {
135
+ const dir = join(this.root, group);
136
+ if (!existsSync(dir)) return [];
137
+ return readdirSync(dir, { withFileTypes: true }).filter((e) => e.isDirectory() && !e.name.startsWith('.')).map((e) => e.name).sort();
138
+ }
139
+ }
@@ -0,0 +1,48 @@
1
+ /** Atlassian Document Format (Jira Cloud rich text) to markdown. */
2
+ export class Adf {
3
+ static toMarkdown(value) {
4
+ if (!value) return '';
5
+ if (typeof value === 'string') return value;
6
+ return new Adf().node(value).replace(/\n{3,}/g, '\n\n').trim();
7
+ }
8
+
9
+ node(node) {
10
+ const inner = (sep = '') => (node.content || []).map((child) => this.node(child)).join(sep);
11
+ switch (node.type) {
12
+ case 'doc': return inner('\n\n');
13
+ case 'paragraph': return inner();
14
+ case 'text': return this.marks(node.text, node.marks);
15
+ case 'hardBreak': return '\n';
16
+ case 'heading': return `${'#'.repeat(Math.min((node.attrs?.level || 1) + 1, 6))} ${inner()}`;
17
+ case 'bulletList': return (node.content || []).map((li) => `- ${this.node(li).replace(/\n/g, '\n ')}`).join('\n');
18
+ case 'orderedList': return (node.content || []).map((li, i) => `${i + 1}. ${this.node(li).replace(/\n/g, '\n ')}`).join('\n');
19
+ case 'listItem': return inner('\n');
20
+ case 'codeBlock': return `\`\`\`${node.attrs?.language || ''}\n${inner()}\n\`\`\``;
21
+ case 'blockquote': return inner('\n\n').split('\n').map((l) => `> ${l}`).join('\n');
22
+ case 'rule': return '---';
23
+ case 'mention': return node.attrs?.text || '@user';
24
+ case 'emoji': return node.attrs?.text || '';
25
+ case 'inlineCard': return node.attrs?.url || '';
26
+ case 'table': return this.table(node);
27
+ default: return inner(node.content?.some((c) => c.type === 'paragraph') ? '\n\n' : '');
28
+ }
29
+ }
30
+
31
+ marks(text, list = []) {
32
+ return list.reduce((t, m) => {
33
+ if (m.type === 'strong') return `**${t}**`;
34
+ if (m.type === 'em') return `*${t}*`;
35
+ if (m.type === 'code') return `\`${t}\``;
36
+ if (m.type === 'strike') return `~~${t}~~`;
37
+ if (m.type === 'link') return `[${t}](${m.attrs?.href})`;
38
+ return t;
39
+ }, text);
40
+ }
41
+
42
+ table(node) {
43
+ const rows = (node.content || []).map((row) => (row.content || []).map((cell) => this.node(cell).replace(/\n+/g, ' ').replace(/\|/g, '\\|')));
44
+ if (!rows.length) return '';
45
+ const [head, ...rest] = rows;
46
+ return [`| ${head.join(' | ')} |`, `| ${head.map(() => '---').join(' | ')} |`, ...rest.map((r) => `| ${r.join(' | ')} |`)].join('\n');
47
+ }
48
+ }
@@ -0,0 +1,81 @@
1
+ import { join } from 'node:path';
2
+ import { slugify, writeMarkdown } from '../files.js';
3
+ import { GitHub } from '../github.js';
4
+ import { Source } from './source.js';
5
+
6
+ /** `github:<repo url or owner/repo>` — closed repository issues that built something (pull requests, open, not planned and duplicate issues excluded). */
7
+ export class GitHubSource extends Source {
8
+ static NOT_BUILT = ['not_planned', 'duplicate'];
9
+ static kind = 'github';
10
+ static type = 'issues';
11
+ static usage = 'github:<repo url>';
12
+ static defaultScope = { labels: '', limit: 200, comments: true };
13
+
14
+ constructor(target, scope) {
15
+ super(target, scope);
16
+ this.github = new GitHub(target);
17
+ }
18
+
19
+ get defaultName() {
20
+ return slugify(`github-${this.github.owner}-${this.github.repo}`);
21
+ }
22
+
23
+ async validate() {
24
+ const info = await this.github.api('');
25
+ return `${info.full_name} (${info.open_issues_count} open issues and PRs)`;
26
+ }
27
+
28
+ async fetch(dir, { since } = {}) {
29
+ const limit = Number(this.scope.limit) || 200;
30
+ const params = new URLSearchParams({ state: 'closed', per_page: '100', sort: 'updated', direction: 'desc' });
31
+ if (this.scope.labels) params.set('labels', this.scope.labels);
32
+ if (since) params.set('since', since);
33
+ let written = 0;
34
+ for (let page = 1; written < limit; page++) {
35
+ params.set('page', String(page));
36
+ const issues = await this.github.api(`/issues?${params}`);
37
+ if (!issues.length) break;
38
+ for (const issue of issues) {
39
+ if (issue.pull_request || written >= limit) continue;
40
+ if (GitHubSource.NOT_BUILT.includes(issue.state_reason)) continue;
41
+ if (this.scope.stateReason && issue.state_reason !== this.scope.stateReason) continue;
42
+ const comments = this.scope.comments !== false && issue.comments ? await this.github.api(`/issues/${issue.number}/comments?per_page=100`) : [];
43
+ this.write(dir, issue, comments);
44
+ written++;
45
+ }
46
+ }
47
+ return written;
48
+ }
49
+
50
+ /** Other issues this one mentions in its body or comments: `#12`, `owner/repo#12`, or an issue URL. */
51
+ references(issue, comments = []) {
52
+ const own = `${this.github.owner}/${this.github.repo}`.toLowerCase();
53
+ const text = [issue.body, ...comments.map((c) => c.body)].filter(Boolean).join('\n');
54
+ const pattern = /(?:https:\/\/github\.com\/([\w.-]+\/[\w.-]+)\/issues\/|(?<![\w./-])([\w.-]+\/[\w.-]+)?#)(\d+)\b/g;
55
+ const keys = new Set();
56
+ for (const [, urlRepo, refRepo, number] of text.matchAll(pattern)) {
57
+ const repo = (urlRepo || refRepo || own).toLowerCase();
58
+ const key = repo === own ? `#${number}` : `${repo}#${number}`;
59
+ if (key !== `#${issue.number}`) keys.add(key);
60
+ }
61
+ return [...keys].map((key) => ({ relation: 'mentions', key }));
62
+ }
63
+
64
+ write(dir, issue, comments) {
65
+ const body = [`# #${issue.number} ${issue.title}`, '', issue.body || '_No description._'];
66
+ for (const c of comments) body.push('', `## Comment by ${c.user?.login} on ${c.created_at.slice(0, 10)}`, '', c.body || '');
67
+ writeMarkdown(join(dir, `${issue.number}-${slugify(issue.title)}.md`), {
68
+ key: `#${issue.number}`,
69
+ title: issue.title,
70
+ status: issue.state,
71
+ resolution: issue.state_reason,
72
+ labels: issue.labels.map((l) => (typeof l === 'string' ? l : l.name)),
73
+ milestone: issue.milestone?.title,
74
+ links: this.references(issue, comments),
75
+ created: issue.created_at,
76
+ updated: issue.updated_at,
77
+ resolved: issue.closed_at,
78
+ url: issue.html_url,
79
+ }, body.join('\n'));
80
+ }
81
+ }