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,209 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { mkdirSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { createInterface } from 'node:readline';
5
+ import { getAgentDir, ModelRuntime, SettingsManager } from '@earendil-works/pi-coding-agent';
6
+ import { brand, log, muted } from '../branding.js';
7
+ import { Config } from '../config.js';
8
+
9
+ /**
10
+ * Credentials for model providers, shared with pi: they live in pi's `~/.pi/agent/auth.json`, so a
11
+ * sign-in made here works in pi and the other way round. Login flows (Claude Pro/Max, ChatGPT,
12
+ * GitHub Copilot, API keys) are pi's own.
13
+ */
14
+ export class Auth {
15
+ /** Names people use for a subscription, mapped to pi provider ids. */
16
+ static ALIASES = { claude: 'anthropic', codex: 'openai-codex', chatgpt: 'openai', copilot: 'github-copilot', grok: 'xai' };
17
+
18
+ /** @param {ModelRuntime} runtime */
19
+ constructor(runtime) {
20
+ this.runtime = runtime;
21
+ }
22
+
23
+ /** pi's credential file, `~/.pi/agent/auth.json` (`PI_CODING_AGENT_DIR` moves it). */
24
+ static path() {
25
+ return join(getAgentDir(), 'auth.json');
26
+ }
27
+
28
+ /** The pi model runtime: pi's credentials, requirementbot's `models.json`. */
29
+ static runtime() {
30
+ const dir = Config.agentDir();
31
+ mkdirSync(dir, { recursive: true });
32
+ return ModelRuntime.create({ authPath: Auth.path(), modelsPath: join(dir, 'models.json') });
33
+ }
34
+
35
+ /** @param {ModelRuntime} runtime */
36
+ static async available(runtime) {
37
+ return runtime.getAvailable();
38
+ }
39
+
40
+ static async create() {
41
+ return new Auth(await Auth.runtime());
42
+ }
43
+
44
+ /** Providers that can log in with `type`, subscriptions first. */
45
+ providers(type = 'oauth') {
46
+ return this.runtime
47
+ .getProviders()
48
+ .filter((p) => (type === 'oauth' ? p.auth?.oauth : p.auth?.apiKey?.login))
49
+ .map((p) => {
50
+ const method = type === 'oauth' ? p.auth.oauth : p.auth.apiKey;
51
+ return { id: p.id, label: method.name, subscription: Boolean(type === 'oauth' && method.isSubscription) };
52
+ })
53
+ .sort((a, b) => Number(b.subscription) - Number(a.subscription) || a.id.localeCompare(b.id));
54
+ }
55
+
56
+ /**
57
+ * Run a provider's login flow and store the credential.
58
+ * @param {string|undefined} providerId asked through `interaction` when missing
59
+ * @param {'oauth'|'api_key'} type
60
+ * @param {import('@earendil-works/pi-ai').AuthInteraction} interaction
61
+ */
62
+ async login(providerId, type, interaction) {
63
+ const providers = this.providers(type);
64
+ if (!providers.length) throw new Error(`No providers support ${type} login`);
65
+ const id = providerId || (await interaction.prompt({
66
+ type: 'select',
67
+ message: 'Select a provider:',
68
+ options: providers.map((p) => ({ id: p.id, label: p.label, description: p.subscription ? 'subscription' : undefined })),
69
+ }));
70
+ const provider = providers.find((p) => p.id === (Auth.ALIASES[id] || id));
71
+ if (!provider) {
72
+ const kind = type === 'oauth' ? 'OAuth or subscription' : 'API key';
73
+ throw new Error(`"${id}" does not support ${kind} login. Choose one of: ${providers.map((p) => p.id).join(', ')}`);
74
+ }
75
+ const deviceId = await Auth.deviceId();
76
+ await this.runtime.login(provider.id, type, interaction, { agentName: 'requirementbot', getDeviceId: () => deviceId });
77
+ return provider;
78
+ }
79
+
80
+ /** pi's installation id. Sign in with ChatGPT registers the app under it, so pi and requirementbot share it. */
81
+ static async deviceId() {
82
+ const settings = SettingsManager.create(process.cwd(), getAgentDir());
83
+ const id = settings.getOrCreateDeviceId();
84
+ await settings.flush();
85
+ return id;
86
+ }
87
+
88
+ async logout(name) {
89
+ const providerId = Auth.ALIASES[name] || name;
90
+ const stored = await this.credentials();
91
+ if (!stored.some((c) => c.providerId === providerId)) {
92
+ const names = stored.map((c) => c.providerId);
93
+ throw new Error(`No stored credential for "${providerId}"${names.length ? `. Stored: ${names.join(', ')}` : ''}`);
94
+ }
95
+ await this.runtime.logout(providerId);
96
+ }
97
+
98
+ /** Credentials stored in auth.json (not environment variables). */
99
+ async credentials() {
100
+ return (await this.runtime.listCredentials()).map(({ providerId, type }) => ({
101
+ providerId,
102
+ type,
103
+ subscription: type === 'oauth' && this.runtime.isUsingSubscription(providerId),
104
+ }));
105
+ }
106
+ }
107
+
108
+ /**
109
+ * Answers pi's login prompts in a terminal. Messages go to stderr so stdout stays clean;
110
+ * answers are read from `input`.
111
+ */
112
+ export class TerminalInteraction {
113
+ /**
114
+ * @param {{ input?: NodeJS.ReadableStream, output?: NodeJS.WritableStream, browser?: boolean, signal?: AbortSignal }} [options]
115
+ */
116
+ constructor({ input = process.stdin, output = process.stderr, browser = true, signal } = {}) {
117
+ this.input = input;
118
+ this.output = output;
119
+ this.browser = browser;
120
+ this.signal = signal;
121
+ // pi copies the interaction with a spread, which keeps own properties only.
122
+ this.prompt = this.prompt.bind(this);
123
+ this.notify = this.notify.bind(this);
124
+ }
125
+
126
+ notify(event) {
127
+ if (event.type === 'auth_url') {
128
+ this.write(`\n${event.instructions || 'Open this URL to sign in:'}\n${brand(event.url)}\n\n`);
129
+ if (this.browser) openBrowser(event.url);
130
+ } else if (event.type === 'device_code') {
131
+ this.write(`\nOpen ${brand(event.verificationUri)} and enter the code ${brand.bold(event.userCode)}\n\n`);
132
+ if (this.browser) openBrowser(event.verificationUri);
133
+ } else if (event.type === 'info') {
134
+ log(event.message);
135
+ for (const link of event.links || []) this.write(` ${link.label ? `${link.label}: ` : ''}${brand(link.url)}\n`);
136
+ } else if (event.type === 'progress') {
137
+ log(muted(event.message));
138
+ }
139
+ }
140
+
141
+ async prompt(prompt) {
142
+ if (prompt.type === 'select') return this.select(prompt);
143
+ // A URL placeholder (e.g. the bare callback address) reads like a link to open; show only plain hints.
144
+ const hint = prompt.placeholder && !/^https?:\/\//.test(prompt.placeholder) ? muted(` (${prompt.placeholder})`) : '';
145
+ const answer = await this.ask(`${prompt.message}${hint} `, {
146
+ secret: prompt.type === 'secret',
147
+ signal: prompt.signal,
148
+ });
149
+ if (!answer && prompt.type !== 'manual_code') throw new Error('Login cancelled: no value entered');
150
+ return answer;
151
+ }
152
+
153
+ async select({ message, options, signal }) {
154
+ this.write(`${message}\n`);
155
+ options.forEach((o, i) => this.write(` ${brand(String(i + 1))}. ${o.label}${o.description ? muted(` (${o.description})`) : ''}\n`));
156
+ const answer = await this.ask(`Choice ${muted('[1]')}: `, { signal });
157
+ if (!answer) return options[0].id;
158
+ const index = Number(answer) - 1;
159
+ const option = options[index] || options.find((o) => o.id === answer);
160
+ if (!option) throw new Error(`Invalid choice "${answer}"`);
161
+ return option.id;
162
+ }
163
+
164
+ /** Read one line. Rejects when `signal` (or the whole login's signal) aborts. */
165
+ ask(question, { secret = false, signal } = {}) {
166
+ if (this.input === process.stdin && !process.stdin.isTTY) {
167
+ return Promise.reject(new Error('Login needs an interactive terminal. In CI, set the provider API key or ANTHROPIC_OAUTH_TOKEN instead.'));
168
+ }
169
+ const rl = createInterface({ input: this.input, output: this.output, terminal: Boolean(this.input.isTTY) });
170
+ if (secret) {
171
+ const write = rl._writeToOutput?.bind(rl);
172
+ rl._writeToOutput = (text) => write?.(text.startsWith(question) ? question : '');
173
+ }
174
+ const signals = [signal, this.signal].filter(Boolean);
175
+ return new Promise((resolve, reject) => {
176
+ const abort = (shown = true) => {
177
+ rl.close();
178
+ if (shown) this.write('\n'); // e.g. the browser callback answered, so end the unanswered prompt line
179
+ reject(new Error('Login prompt aborted'));
180
+ };
181
+ if (signals.some((s) => s.aborted)) return abort(false);
182
+ for (const s of signals) s.addEventListener('abort', abort, { once: true });
183
+ rl.question(question, (answer) => {
184
+ for (const s of signals) s.removeEventListener('abort', abort);
185
+ rl.close();
186
+ if (secret) this.write('\n');
187
+ resolve(answer.trim());
188
+ });
189
+ });
190
+ }
191
+
192
+ write(text) {
193
+ this.output.write(text);
194
+ }
195
+ }
196
+
197
+ /** Best-effort: open a URL in the default browser. The URL is also printed, so failures are ignored. */
198
+ function openBrowser(url) {
199
+ const [command, args] = process.platform === 'darwin' ? ['open', [url]]
200
+ : process.platform === 'win32' ? ['cmd', ['/c', 'start', '', url]]
201
+ : ['xdg-open', [url]];
202
+ try {
203
+ const child = spawn(command, args, { stdio: 'ignore', detached: true });
204
+ child.on('error', () => {});
205
+ child.unref();
206
+ } catch {
207
+ // printed URL is the fallback
208
+ }
209
+ }
@@ -0,0 +1,36 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { PROMPTS_DIR, SKILLS_DIR } from '../config.js';
4
+
5
+ /**
6
+ * A prompt read from `prompts/<name>.md`. `{{value}}` is replaced by a value, `{{> partial}}` by
7
+ * `prompts/partials/<partial>.md`, and HTML comments are dropped. `{{skills}}` is always available.
8
+ */
9
+ export class Prompt {
10
+ constructor(name, values = {}) {
11
+ this.name = name;
12
+ this.values = { skills: SKILLS_DIR, ...values };
13
+ }
14
+
15
+ toString() {
16
+ return this.render(Prompt.read(this.name)).replace(/<!--[\s\S]*?-->\n?/g, '').trim();
17
+ }
18
+
19
+ render(template) {
20
+ return template
21
+ .replace(/\{\{>\s*([\w-]+)\s*\}\}/g, (_, partial) => this.render(Prompt.read(join('partials', partial)).trim()))
22
+ .replace(/\{\{\s*([\w-]+)\s*\}\}/g, (match, key) => {
23
+ if (!(key in this.values)) throw new Error(`Prompt ${this.name}: no value for {{${key}}}`);
24
+ return String(this.values[key]);
25
+ });
26
+ }
27
+
28
+ static read(name) {
29
+ return readFileSync(join(PROMPTS_DIR, `${name}.md`), 'utf8');
30
+ }
31
+
32
+ /** Markdown bullet list, for values that hold several lines. */
33
+ static list(items) {
34
+ return items.map((item) => `- ${item}`).join('\n');
35
+ }
36
+ }
@@ -0,0 +1,27 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import chalk from 'chalk';
3
+
4
+ const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
5
+
6
+ export const NAME = 'requirementbot';
7
+ export const VERSION = pkg.version;
8
+ export const TAGLINE = 'AI requirements from code, issues and docs · by Testomat.io';
9
+
10
+ export const brand = chalk.hex('#7c5cff');
11
+ export const muted = chalk.gray;
12
+
13
+ export function banner() {
14
+ return `${brand.bold('▣ requirementbot')} ${muted(`v${VERSION}`)}\n${muted(TAGLINE)}`;
15
+ }
16
+
17
+ export function log(message) {
18
+ process.stderr.write(`${brand('▣')} ${message}\n`);
19
+ }
20
+
21
+ export function warn(message) {
22
+ process.stderr.write(`${chalk.yellow('!')} ${message}\n`);
23
+ }
24
+
25
+ export function fail(message) {
26
+ process.stderr.write(`${chalk.red('✗')} ${message}\n`);
27
+ }
package/src/cli.js ADDED
@@ -0,0 +1,26 @@
1
+ import { Command as Program } from 'commander';
2
+ import { banner, fail, VERSION } from './branding.js';
3
+ import { commands } from './commands/index.js';
4
+
5
+ export async function main(argv) {
6
+ const program = new Program('requirementbot')
7
+ .description(`${banner()}\n\nGenerate requirements as markdown from code, issues and docs, and sync them to Git, GitHub, Confluence and Notion.`)
8
+ .version(VERSION, '-V, --version')
9
+ .option('-o, --output <dir>', 'requirements folder (default: "requirements" or config)')
10
+ .showHelpAfterError();
11
+
12
+ for (const command of commands) command.register(program);
13
+
14
+ if (argv.length <= 2) {
15
+ program.outputHelp();
16
+ return;
17
+ }
18
+
19
+ try {
20
+ await program.parseAsync(argv);
21
+ } catch (err) {
22
+ fail(err.message);
23
+ if (process.env.DEBUG) console.error(err);
24
+ process.exitCode = 1;
25
+ }
26
+ }
@@ -0,0 +1,61 @@
1
+ import { relative } from 'node:path';
2
+ import { Agent } from '../agent/agent.js';
3
+ import { Prompt } from '../agent/prompt.js';
4
+ import { banner, brand, log, muted, warn } from '../branding.js';
5
+ import { Command } from './command.js';
6
+
7
+ /** A command that runs the agent. Adds the model options and the generate → check → fix loop. */
8
+ export class AgentCommand extends Command {
9
+ static configure(cmd) {
10
+ return cmd
11
+ .option('-m, --model <provider/id>', 'model to use, e.g. anthropic/claude-sonnet-5-5')
12
+ .option('--thinking <level>', 'thinking level: off, minimal, low, medium, high')
13
+ .option('--no-mcp', 'do not connect MCP servers')
14
+ .option('--session', 'keep the agent session in .requirementbot/sessions')
15
+ .option('-v, --verbose', 'stream the agent output');
16
+ }
17
+
18
+ /** The agent for the selected model. */
19
+ async agent(options, extra = {}) {
20
+ return new Agent({
21
+ cwd: this.cwd,
22
+ model: options.model || this.config.model,
23
+ thinking: options.thinking,
24
+ mcp: options.mcp,
25
+ session: options.session,
26
+ verbose: options.verbose,
27
+ ...extra,
28
+ });
29
+ }
30
+
31
+ /** Path as the agent should see it: relative to the working directory. */
32
+ rel(path) {
33
+ return relative(this.cwd, path) || '.';
34
+ }
35
+
36
+ /**
37
+ * Run a generating prompt, check the produced tree once, and send the agent back to fix
38
+ * missing sections. Prints the agent's report to stdout.
39
+ * @param {Prompt} prompt
40
+ * @param {{ tree: string, kind?: 'source'|'product-mismatches' }} target
41
+ */
42
+ async generate(prompt, options, { tree, kind = 'source' }) {
43
+ process.stderr.write(`${banner()}\n\n`);
44
+ const answer = await (await this.agent(options)).run(prompt, {
45
+ followUps: [async () => {
46
+ const problems = this.requirements.validate(tree, kind);
47
+ if (!problems.length) return undefined;
48
+ warn(`${problems.length} structure problem(s) found, asking the agent to fix them`);
49
+ return new Prompt('fix', { problems: Prompt.list(problems.slice(0, 80)) });
50
+ }],
51
+ });
52
+ this.requirements.writeIndex();
53
+ process.stdout.write(`${answer.trim()}\n`);
54
+ const remaining = this.requirements.validate(tree, kind);
55
+ if (remaining.length) {
56
+ warn(`${remaining.length} structure problem(s) remain:`);
57
+ for (const problem of remaining.slice(0, 20)) process.stderr.write(` ${muted(problem)}\n`);
58
+ }
59
+ log(`Requirements in ${brand(this.rel(tree))}`);
60
+ }
61
+ }
@@ -0,0 +1,26 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { Prompt } from '../agent/prompt.js';
3
+ import { AgentCommand } from './agent-command.js';
4
+
5
+ export class Check extends AgentCommand {
6
+ static command = 'check';
7
+ static description = 'compare code, issues and docs requirements and record mismatches (detect-product-mismatches skill)';
8
+
9
+ static configure(cmd) {
10
+ return super.configure(cmd).option('--update', 'only re-check what changed since the last check');
11
+ }
12
+
13
+ async run(options) {
14
+ const catalogs = this.requirements.catalogs();
15
+ if (catalogs.length < 2) {
16
+ throw new Error(`Need at least two cataloged sources in ${this.rel(this.requirements.root)} (found ${catalogs.length}). Run generate:from-code and generate:from-issues or generate:from-docs first.`);
17
+ }
18
+ const tree = this.requirements.mismatchesDir;
19
+ const prompt = new Prompt('check', {
20
+ mode: options.update && existsSync(tree) ? 'update' : 'build',
21
+ catalogs: Prompt.list(catalogs.map((c) => `${c.name}: \`${this.rel(c.path)}\``)),
22
+ output: this.rel(tree),
23
+ });
24
+ await this.generate(prompt, options, { tree, kind: 'product-mismatches' });
25
+ }
26
+ }
@@ -0,0 +1,40 @@
1
+ import { Config } from '../config.js';
2
+ import { Requirements } from '../requirements.js';
3
+
4
+ /**
5
+ * A CLI command. Subclasses set `command` and `description`, add arguments and options in
6
+ * `configure`, and implement `run(...arguments, options)`.
7
+ */
8
+ export class Command {
9
+ /** @type {string} */
10
+ static command;
11
+ /** @type {string} */
12
+ static description;
13
+
14
+ /** @param {import('commander').Command} cmd */
15
+ static configure(cmd) {
16
+ return cmd;
17
+ }
18
+
19
+ /** @param {import('commander').Command} program */
20
+ static register(program) {
21
+ const cmd = this.configure(program.command(this.command).description(this.description));
22
+ cmd.action((...args) => {
23
+ args.pop();
24
+ const options = args.pop();
25
+ return new this(program.opts()).run(...args, options);
26
+ });
27
+ }
28
+
29
+ /** @param {{ output?: string }} globalOptions */
30
+ constructor(globalOptions = {}) {
31
+ this.cwd = process.cwd();
32
+ this.config = Config.load(this.cwd);
33
+ this.config.output = globalOptions.output;
34
+ this.requirements = new Requirements(this.config.outputDir, this.cwd);
35
+ }
36
+
37
+ async run() {
38
+ throw new Error(`${this.constructor.command} is not implemented`);
39
+ }
40
+ }
@@ -0,0 +1,33 @@
1
+ import { brand, log, muted } from '../branding.js';
2
+ import { Sources } from '../sources/index.js';
3
+ import { Command } from './command.js';
4
+
5
+ export class Connect extends Command {
6
+ static command = 'connect';
7
+ static description = 'connect an issue tracker or docs space as a requirements source';
8
+
9
+ static configure(cmd) {
10
+ return cmd
11
+ .argument('<source>', Sources.usage)
12
+ .option('--name <name>', 'source name (default derived from the target)')
13
+ .option('--labels <labels>', 'GitHub: comma-separated labels')
14
+ .option('--state-reason <reason>', 'GitHub: only closed issues with this reason, e.g. completed')
15
+ .option('--jql <jql>', 'Jira: JQL query (default: project issues); always narrowed to resolved issues')
16
+ .option('--limit <n>', 'maximum issues to fetch', Number)
17
+ .option('--no-comments', 'leave issue comments out');
18
+ }
19
+
20
+ async run(value, options) {
21
+ const { name: customName, ...flags } = options;
22
+ if (flags.comments !== false) delete flags.comments;
23
+ const scope = Object.fromEntries(Object.entries(flags).filter(([, v]) => v !== undefined));
24
+ const source = Sources.parse(value, scope);
25
+ const name = customName || source.defaultName;
26
+ const info = await source.validate();
27
+ this.config.sources[name] = { kind: source.kind, target: source.target, scope: source.scope };
28
+ this.config.save();
29
+ log(`Connected ${brand(name)} → ${info}`);
30
+ if (Object.keys(source.scope).length) log(`Scope ${muted(JSON.stringify(source.scope))}`);
31
+ log(`Next: requirementbot ${source.type === 'issues' ? 'generate:from-issues' : 'generate:from-docs'}`);
32
+ }
33
+ }
@@ -0,0 +1,18 @@
1
+ import { log } from '../branding.js';
2
+ import { Command } from './command.js';
3
+
4
+ export class Disconnect extends Command {
5
+ static command = 'disconnect';
6
+ static description = 'remove a connected source';
7
+
8
+ static configure(cmd) {
9
+ return cmd.argument('<name>', 'source name');
10
+ }
11
+
12
+ run(name) {
13
+ if (!this.config.sources[name]) throw new Error(`No source named "${name}"`);
14
+ delete this.config.sources[name];
15
+ this.config.save();
16
+ log(`Disconnected ${name}`);
17
+ }
18
+ }
@@ -0,0 +1,20 @@
1
+ import { basename, resolve } from 'node:path';
2
+ import { Prompt } from '../agent/prompt.js';
3
+ import { AgentCommand } from './agent-command.js';
4
+
5
+ export class GenerateFromCode extends AgentCommand {
6
+ static command = 'generate:from-code';
7
+ static description = 'build requirements from source code (requirements-from-code skill)';
8
+ mode = 'build';
9
+
10
+ static configure(cmd) {
11
+ return super.configure(cmd).argument('[path]', 'repository to read', '.');
12
+ }
13
+
14
+ async run(path, options) {
15
+ const repo = resolve(this.cwd, path);
16
+ const tree = this.requirements.actualDir(basename(repo) || 'repo');
17
+ const prompt = new Prompt('from-code', { mode: this.mode, repo, output: this.rel(tree) });
18
+ await this.generate(prompt, options, { tree });
19
+ }
20
+ }
@@ -0,0 +1,38 @@
1
+ import { basename, join, resolve } from 'node:path';
2
+ import { Prompt } from '../agent/prompt.js';
3
+ import { log, muted } from '../branding.js';
4
+ import { resetDir, slugify } from '../files.js';
5
+ import { Sources } from '../sources/index.js';
6
+ import { AgentCommand } from './agent-command.js';
7
+
8
+ export class GenerateFromDocs extends AgentCommand {
9
+ static command = 'generate:from-docs';
10
+ static description = 'build requirements from user documentation';
11
+ mode = 'build';
12
+
13
+ static configure(cmd) {
14
+ return super.configure(cmd).argument('[path]', 'local docs folder; connected Confluence/Notion sources when omitted');
15
+ }
16
+
17
+ async run(path, options) {
18
+ for (const { name, docs } of await this.docs(path)) {
19
+ const tree = this.requirements.expectedDir(name);
20
+ const prompt = new Prompt('from-docs', { mode: this.mode, name, docs: this.rel(docs), output: this.rel(tree) });
21
+ await this.generate(prompt, options, { tree });
22
+ }
23
+ }
24
+
25
+ /** A local folder, or every connected docs source downloaded into the cache. */
26
+ async docs(path) {
27
+ if (path) return [{ name: slugify(basename(resolve(this.cwd, path))), docs: resolve(this.cwd, path) }];
28
+ const docs = [];
29
+ for (const [name, , source] of Sources.connected(this.config, 'docs')) {
30
+ const dir = join(this.config.cacheDir, name);
31
+ log(`Fetching ${name} ${muted(String(source))}`);
32
+ resetDir(dir);
33
+ await source.fetch(dir);
34
+ docs.push({ name, docs: dir });
35
+ }
36
+ return docs;
37
+ }
38
+ }
@@ -0,0 +1,41 @@
1
+ import { join } from 'node:path';
2
+ import { Prompt } from '../agent/prompt.js';
3
+ import { log, muted } from '../branding.js';
4
+ import { resetDir } from '../files.js';
5
+ import { Sources } from '../sources/index.js';
6
+ import { AgentCommand } from './agent-command.js';
7
+
8
+ export class GenerateFromIssues extends AgentCommand {
9
+ static command = 'generate:from-issues';
10
+ static description = 'build requirements from connected issue trackers (GitHub, Jira)';
11
+ mode = 'build';
12
+
13
+ static configure(cmd) {
14
+ return super.configure(cmd).option('-s, --source <name>', 'only this connected source');
15
+ }
16
+
17
+ async run(options) {
18
+ for (const [name, entry, source] of Sources.connected(this.config, 'issues', options.source)) {
19
+ const dump = join(this.config.cacheDir, name);
20
+ const since = this.mode === 'update' ? entry.lastFetch : undefined;
21
+ if (!since) resetDir(dump);
22
+ const startedAt = new Date().toISOString();
23
+ log(`Fetching ${name} ${muted(String(source))}`);
24
+ const count = await source.fetch(dump, { since });
25
+ log(`${count} issue(s) ${since ? `changed since ${since}` : 'in scope'}`);
26
+ entry.lastFetch = startedAt;
27
+ this.config.save();
28
+
29
+ const tree = this.requirements.expectedDir(name);
30
+ const prompt = new Prompt('from-issues', {
31
+ mode: this.mode,
32
+ name,
33
+ kind: source.kind,
34
+ dump: this.rel(dump),
35
+ scope: JSON.stringify(source.scope),
36
+ output: this.rel(tree),
37
+ });
38
+ await this.generate(prompt, options, { tree });
39
+ }
40
+ }
41
+ }
@@ -0,0 +1,40 @@
1
+ import { Check } from './check.js';
2
+ import { Connect } from './connect.js';
3
+ import { Disconnect } from './disconnect.js';
4
+ import { GenerateFromCode } from './generate-from-code.js';
5
+ import { GenerateFromDocs } from './generate-from-docs.js';
6
+ import { GenerateFromIssues } from './generate-from-issues.js';
7
+ import { Login } from './login.js';
8
+ import { Logout } from './logout.js';
9
+ import { Models } from './models.js';
10
+ import { Pull } from './pull.js';
11
+ import { Push } from './push.js';
12
+ import { Query } from './query.js';
13
+ import { Report } from './report.js';
14
+ import { Skills } from './skills.js';
15
+ import { ListSources } from './sources.js';
16
+ import { UpdateFromCode } from './update-from-code.js';
17
+ import { UpdateFromDocs } from './update-from-docs.js';
18
+ import { UpdateFromIssues } from './update-from-issues.js';
19
+
20
+ /** Commands in help order. */
21
+ export const commands = [
22
+ GenerateFromCode,
23
+ UpdateFromCode,
24
+ GenerateFromIssues,
25
+ UpdateFromIssues,
26
+ GenerateFromDocs,
27
+ UpdateFromDocs,
28
+ Check,
29
+ Report,
30
+ Query,
31
+ Connect,
32
+ Disconnect,
33
+ ListSources,
34
+ Push,
35
+ Pull,
36
+ Skills,
37
+ Models,
38
+ Login,
39
+ Logout,
40
+ ];
@@ -0,0 +1,44 @@
1
+ import { Auth, TerminalInteraction } from '../agent/auth.js';
2
+ import { brand, log, muted } from '../branding.js';
3
+ import { Command } from './command.js';
4
+
5
+ export class Login extends Command {
6
+ static command = 'login';
7
+ static description = 'sign in to a model provider: a subscription (Claude Pro/Max, ChatGPT/Codex, Copilot) or an API key, using pi\'s login';
8
+
9
+ static configure(cmd) {
10
+ return cmd
11
+ .argument('[provider]', 'provider id, e.g. anthropic, codex, github-copilot (asked when omitted)')
12
+ .option('--api-key', 'store an API key instead of signing in with a subscription')
13
+ .option('--no-browser', 'print the sign-in URL without opening a browser')
14
+ .option('--list', 'list providers you can sign in to and stored credentials');
15
+ }
16
+
17
+ async run(providerId, options) {
18
+ const auth = await Auth.create();
19
+ const type = options.apiKey ? 'api_key' : 'oauth';
20
+ if (options.list) return this.list(auth, type);
21
+
22
+ const controller = new AbortController();
23
+ const cancel = () => controller.abort();
24
+ process.once('SIGINT', cancel);
25
+ try {
26
+ const interaction = new TerminalInteraction({ browser: options.browser, signal: controller.signal });
27
+ const provider = await auth.login(providerId, type, interaction);
28
+ log(`Signed in to ${brand(provider.label)}. Credentials saved in ${muted(Auth.path())}, shared with pi`);
29
+ const models = (await auth.runtime.getAvailable(provider.id)).map((m) => `${m.provider}/${m.id}`);
30
+ if (models.length) log(`${models.length} model(s) available, e.g. ${muted(models.slice(0, 3).join(', '))}`);
31
+ } finally {
32
+ process.off('SIGINT', cancel);
33
+ }
34
+ }
35
+
36
+ async list(auth, type) {
37
+ const stored = new Map((await auth.credentials()).map((c) => [c.providerId, c]));
38
+ const line = (id, label, tags) => process.stdout.write(`${id.padEnd(16)} ${label}${tags.length ? ` ${muted(tags.join(', '))}` : ''}\n`);
39
+ for (const p of auth.providers(type)) {
40
+ const credential = stored.get(p.id);
41
+ line(p.id, p.label, [p.subscription && 'subscription', credential && `signed in (${credential.type})`].filter(Boolean));
42
+ }
43
+ }
44
+ }