ai-policy-check 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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 animatorluffy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,91 @@
1
- # Temporary Holding Version
1
+ # ai-policy-check
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Check whether an open source project allows AI-assisted contributions **before** you spend time on a pull request.
4
+
5
+ More and more projects have rules about AI: some welcome it, some ask you to disclose it, some ban it, and some ban it only on `good first issue` issues (and close those PRs automatically). The rules live in different files — `CONTRIBUTING.md`, `AGENTS.md`, `AI_POLICY.md`, or the organization's `.github` repository — so they are easy to miss.
6
+
7
+ `ai-policy-check` reads those files for you and gives a quick verdict, with the exact sentences it based it on.
8
+
9
+ ## Usage
10
+
11
+ No install needed (Node.js 18 or newer):
12
+
13
+ ```sh
14
+ npx ai-policy-check immich-app/immich
15
+ ```
16
+
17
+ Check a specific issue too — beginner issues often have stricter rules:
18
+
19
+ ```sh
20
+ npx ai-policy-check https://github.com/immich-app/immich/issues/33847
21
+ npx ai-policy-check temporalio/sdk-typescript --issue 1656
22
+ ```
23
+
24
+ Example output:
25
+
26
+ ```text
27
+ immich-app/immich https://github.com/immich-app/immich
28
+
29
+ Verdict: AI help looks BANNED
30
+ ✗ AI is not allowed on "good first issue" / beginner issues
31
+ • You must understand and be able to explain your change
32
+
33
+ Issue #33847: External domain setting rejects plain domains
34
+ labels: good first issue, 🗄️server
35
+ ✗ This is a beginner issue and this project bans AI on it. Fix it by hand or pick another issue.
36
+
37
+ Why:
38
+ CONTRIBUTING.md
39
+ ✗ "We ask you not to open PRs generated with an LLM."
40
+ ✗ "LLMs must not be used to fix GitHub issues labelled good first issue."
41
+ ...
42
+ ```
43
+
44
+ ## Verdicts
45
+
46
+ | Verdict | Meaning |
47
+ | --- | --- |
48
+ | **BANNED** | The rules say not to send AI-generated contributions. |
49
+ | **allowed, with limits** | AI help is allowed, but some uses are not (for example beginner issues, or large unreviewed changes). |
50
+ | **allowed** | The rules say AI help is fine. |
51
+ | **unclear** | AI is mentioned, but no clear rule was found. Ask the maintainers. |
52
+ | **no policy** | No AI rules were found. Ask the maintainers if you are unsure. |
53
+
54
+ It also tells you when a project asks you to **disclose** AI use in your PR, and when it says you must **understand and explain** your change.
55
+
56
+ ## Options
57
+
58
+ | Option | What it does |
59
+ | --- | --- |
60
+ | `--issue <n>` | Also check an issue's labels. |
61
+ | `--json` | Print the full result as JSON. |
62
+ | `--fail-on-ban` | Exit with code 2 when AI looks banned (handy in scripts). |
63
+ | `-h`, `--help` | Show help. |
64
+ | `-v`, `--version` | Show the version. |
65
+
66
+ ## GitHub rate limit
67
+
68
+ Without a token, GitHub allows 60 requests an hour, and one check uses about 5. To raise the limit, set `GITHUB_TOKEN`. If you use the GitHub CLI:
69
+
70
+ ```powershell
71
+ $env:GITHUB_TOKEN = gh auth token # PowerShell
72
+ ```
73
+
74
+ ```sh
75
+ export GITHUB_TOKEN=$(gh auth token) # bash / zsh
76
+ ```
77
+
78
+ The token is only sent to `api.github.com`.
79
+
80
+ ## Files it reads
81
+
82
+ - In the repository: `CONTRIBUTING.md`, `AGENTS.md`, `CLAUDE.md`, `GEMINI.md`, `AI_POLICY.md`, and the same names under `.github/` and `docs/`, plus `.github/copilot-instructions.md` and the pull request template.
83
+ - In the organization's `.github` repository: `AI_POLICY.md`, and `CONTRIBUTING.md` when the repository has none.
84
+
85
+ ## Limits
86
+
87
+ This is an automatic guess based on keywords and sentence patterns, not a lawyer. It can miss rules written in unusual words, rules on a website, or rules in other languages. **Always read the policy yourself before opening a PR.** If it gets a project wrong, please open an issue with the repository name.
88
+
89
+ ## License
90
+
91
+ MIT
package/bin/cli.js ADDED
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env node
2
+ import { run } from '../src/cli.js';
3
+
4
+ run(process.argv.slice(2)).then(
5
+ (code) => {
6
+ process.exitCode = code;
7
+ },
8
+ (error) => {
9
+ process.stderr.write(`Unexpected error: ${error.message}\n`);
10
+ process.exitCode = 1;
11
+ },
12
+ );
package/package.json CHANGED
@@ -1,6 +1,33 @@
1
1
  {
2
2
  "name": "ai-policy-check",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Check whether an open source project allows AI-assisted contributions before you open a pull request.",
5
+ "type": "module",
6
+ "bin": {
7
+ "ai-policy-check": "bin/cli.js"
8
+ },
9
+ "files": [
10
+ "bin",
11
+ "src",
12
+ "README.md",
13
+ "LICENSE"
14
+ ],
15
+ "engines": {
16
+ "node": ">=18"
17
+ },
18
+ "scripts": {
19
+ "test": "node --test"
20
+ },
21
+ "keywords": [
22
+ "ai",
23
+ "llm",
24
+ "open-source",
25
+ "contributing",
26
+ "policy",
27
+ "github",
28
+ "pull-request",
29
+ "cli"
30
+ ],
31
+ "author": "animatorluffy",
32
+ "license": "MIT"
33
+ }
@@ -0,0 +1,160 @@
1
+ const AI_WORD = /\bAI\b/;
2
+ const AI_TERMS =
3
+ /\b(?:LLMs?|large language models?|generative|gen-?AI|copilot|chatgpt|claude|gemini|machine-generated|coding agents?|autonomous agents?)\b/i;
4
+
5
+ const BAN_PATTERNS = [
6
+ /\b(?:must not|may not|should not|shall not|do not|don't|never)\s+(?:be\s+)?(?:use|used|submit|submitted|open|opened|send|generate|generated|rely|work on|fix|contribute)\b/i,
7
+ /\bnot to (?:use|open|submit|send|generate|contribute)\b/i,
8
+ /\b(?:forbidden|prohibited|banned|disallowed|not allowed|not accepted|not acceptable|unacceptable|not permitted|(?:will|do|does) not accept|won't accept|don't accept|closed automatically|auto-closed|will be rejected)\b/i,
9
+ /^\W*no\s+(?:[\w-]+\s+){0,3}?(?:PRs?|pull requests?|contributions?|code|patches|submissions?)\b/i,
10
+ /^\W*no\s+(?:[\w-]+\s+){0,4}?(?:is|are|will be)\s+(?:allowed|permitted|accepted|welcome)\b/i,
11
+ ];
12
+
13
+ const ALLOW =
14
+ /\b(?:welcomes?|welcomed|acceptable|allowed|allows?|permitted|permits?|encouraged|is fine|are fine|is ok(?:ay)?|feel free to use|you (?:may|can) use)\b/i;
15
+ const LIMITED_KIND =
16
+ /\b(?:unless|unreviewed|unchecked|unverified|fully automat\w*|automated|farms?|mass|bulk|bursts?|large|blobs?|vibe|prompt[- ]dump\w*|on (?:your|its|their) own|low[- ]effort|spam\w*|media|images?|art(?:work)?|videos?|audio|illustrations?|logos?)\b|\bwithout (?:\w+ ){0,2}(?:review\w*|oversight|check\w*|understanding|testing|tests|human)\b/i;
17
+ const BEGINNER = /good[\s-]first[\s-]issues?|beginner|first[\s-]timers?/i;
18
+ const DISCLOSE =
19
+ /\b(?:disclos\w*|declare|assisted-by|transparent|to which degree)\b|\b(?:mention|state|note)\b.*\b(?:PR|pull request|description|commit)\b/i;
20
+ const UNDERSTAND = /\b(?:understand\w*|explain\w*|accountab\w*)\b/i;
21
+ const IF_YOU_CANNOT_UNDERSTAND =
22
+ /\b(?:if|when) you (?:can't|cannot|can not|don't|do not|aren't able to|are not able to|are unable to)\s+(?:fully\s+)?(?:explain|understand|justify|defend)\b/i;
23
+ const CONTRIBUTION_WORDS = /\b(?:PRs?|pull requests?|issues?|contribut\w*|commits?)\b/i;
24
+
25
+ const AI_FILE = /(?:^|\/)(?:AGENTS|CLAUDE|GEMINI)\.md$|copilot-instructions\.md$|AI[_-]?(?:POLICY)?\.md$/i;
26
+
27
+ export const mentionsAI = (text) => AI_WORD.test(text) || AI_TERMS.test(text);
28
+
29
+ export const isAIFile = (path) => AI_FILE.test(path);
30
+
31
+ function cleanInline(text) {
32
+ return text
33
+ .replace(/^\s*(?:>|[-*+]|\d+\.)\s*/, '')
34
+ .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
35
+ .replace(/\[([^\]]*)\]\[[^\]]*\]/g, '$1')
36
+ .replace(/<[^>]+>/g, ' ')
37
+ .replace(/\*\*|__|`/g, '')
38
+ .replace(/\s+/g, ' ')
39
+ .trim();
40
+ }
41
+
42
+ export function splitSentences(markdown) {
43
+ const lines = markdown
44
+ .replace(/\r\n?/g, '\n')
45
+ .replace(/<!--[\s\S]*?-->/g, '\n')
46
+ .split('\n');
47
+ let fence = null;
48
+
49
+ const sentences = [];
50
+ let buffer = [];
51
+ let aiSection = false;
52
+ let sectionLevel = 0;
53
+
54
+ const flush = () => {
55
+ if (!buffer.length) return;
56
+ const flat = cleanInline(buffer.join(' '));
57
+ buffer = [];
58
+ for (const part of flat.split(/(?<=[.!?:])\s+(?=["“*(\[]?[A-Z])/)) {
59
+ const text = part.trim();
60
+ if (text.length >= 3) sentences.push({ text, aiSection });
61
+ }
62
+ };
63
+
64
+ for (const line of lines) {
65
+ const fenceMark = line.match(/^ {0,3}(`{3,}|~{3,})/);
66
+ if (fence) {
67
+ if (fenceMark && fenceMark[1][0] === fence[0] && fenceMark[1].length >= fence.length) fence = null;
68
+ continue;
69
+ }
70
+ if (fenceMark) {
71
+ flush();
72
+ fence = fenceMark[1];
73
+ continue;
74
+ }
75
+ const heading = line.match(/^\s{0,3}(#{1,6})\s+(.*)$/);
76
+ if (heading) {
77
+ flush();
78
+ const level = heading[1].length;
79
+ if (mentionsAI(heading[2])) {
80
+ aiSection = true;
81
+ sectionLevel = level;
82
+ } else if (aiSection && level <= sectionLevel) {
83
+ aiSection = false;
84
+ }
85
+ continue;
86
+ }
87
+ if (!line.trim()) {
88
+ flush();
89
+ continue;
90
+ }
91
+ if (/^\s*(?:[-*+]|\d+\.)\s/.test(line)) flush();
92
+ buffer.push(line);
93
+ }
94
+ flush();
95
+ return sentences;
96
+ }
97
+
98
+ export function classifySentence(sentence, { aiFile = false, aiSection = false } = {}) {
99
+ const ai = mentionsAI(sentence);
100
+ if (!ai && !aiFile && !aiSection) return null;
101
+
102
+ const relevantAction = ai || CONTRIBUTION_WORDS.test(sentence);
103
+ // "If you can't explain your change, do not contribute" asks you to
104
+ // understand your code. It does not ban AI help.
105
+ if (IF_YOU_CANNOT_UNDERSTAND.test(sentence)) return 'understand';
106
+ if (relevantAction && BAN_PATTERNS.some((pattern) => pattern.test(sentence))) {
107
+ if (BEGINNER.test(sentence)) return 'beginner-ban';
108
+ if (!ai && !aiSection) return null;
109
+ return LIMITED_KIND.test(sentence) ? 'limit' : 'ban';
110
+ }
111
+ if (ai && ALLOW.test(sentence)) return 'allow';
112
+
113
+ const strongContext = ai || aiSection;
114
+ if ((strongContext || relevantAction) && DISCLOSE.test(sentence)) return 'disclose';
115
+ if (strongContext && UNDERSTAND.test(sentence)) return 'understand';
116
+ return ai ? 'mention' : null;
117
+ }
118
+
119
+ const normalize = (sentence) => sentence.toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
120
+
121
+ export function analyze(files) {
122
+ const seen = new Set();
123
+ const evidence = [];
124
+ const counts = { ban: 0, limit: 0, 'beginner-ban': 0, allow: 0, disclose: 0, understand: 0, mention: 0 };
125
+
126
+ for (const file of files) {
127
+ const aiFile = isAIFile(file.path);
128
+ const wholeFileIsPolicy = /AI[_-]?POLICY/i.test(file.path);
129
+ for (const { text, aiSection } of splitSentences(file.text)) {
130
+ if (text.split(' ').length < 4) continue;
131
+ const kind = classifySentence(text, { aiFile, aiSection: aiSection || wholeFileIsPolicy });
132
+ if (!kind) continue;
133
+ const key = normalize(text);
134
+ if (seen.has(key)) continue;
135
+ seen.add(key);
136
+ counts[kind] += 1;
137
+ if (kind !== 'mention') evidence.push({ file: file.label ?? file.path, kind, sentence: text });
138
+ }
139
+ }
140
+
141
+ return {
142
+ verdict: decideVerdict(counts),
143
+ beginnerBan: counts['beginner-ban'] > 0,
144
+ limits: counts.limit > 0,
145
+ disclosure: evidence.some((e) => e.kind === 'disclose' || DISCLOSE.test(e.sentence)),
146
+ mustUnderstand: evidence.some((e) => e.kind === 'understand' || UNDERSTAND.test(e.sentence)),
147
+ counts,
148
+ evidence,
149
+ };
150
+ }
151
+
152
+ function decideVerdict(counts) {
153
+ if (counts.ban > 0 && counts.ban >= counts.allow) return 'banned';
154
+ if (counts.allow > 0) {
155
+ const limited = counts.ban > 0 || counts.limit > 0 || counts['beginner-ban'] > 0;
156
+ return limited ? 'allowed-with-limits' : 'allowed';
157
+ }
158
+ if (Object.values(counts).some((n) => n > 0)) return 'unclear';
159
+ return 'no-policy';
160
+ }
package/src/cli.js ADDED
@@ -0,0 +1,168 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { analyze, isAIFile } from './classify.js';
3
+ import { createClient, GitHubError, parseTarget } from './github.js';
4
+
5
+ const { version } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
6
+
7
+ const HELP = `ai-policy-check ${version}
8
+
9
+ Check whether an open source project allows AI-assisted contributions.
10
+
11
+ Usage:
12
+ ai-policy-check <owner/repo> e.g. immich-app/immich
13
+ ai-policy-check <github url> repo, issue or pull request link
14
+ ai-policy-check <owner/repo> --issue 123 also check that issue's labels
15
+
16
+ Options:
17
+ --issue <n> check an issue too (beginner labels often have stricter rules)
18
+ --json print the result as JSON
19
+ --fail-on-ban exit with code 2 when AI help looks banned
20
+ -h, --help show this help
21
+ -v, --version show the version
22
+
23
+ Set GITHUB_TOKEN to raise GitHub's rate limit (60 requests an hour without it).`;
24
+
25
+ const BEGINNER_LABEL = /good[\s-]first[\s-]issue|beginner|first[\s-]timers?|starter/i;
26
+
27
+ const VERDICTS = {
28
+ banned: ['red', 'AI help looks BANNED'],
29
+ 'allowed-with-limits': ['yellow', 'AI help looks allowed, with limits'],
30
+ allowed: ['green', 'AI help looks allowed'],
31
+ unclear: ['yellow', 'AI is mentioned, but no clear rule was found'],
32
+ 'no-policy': ['dim', 'No AI policy found'],
33
+ };
34
+
35
+ const KIND_MARK = {
36
+ ban: ['red', '✗'],
37
+ 'beginner-ban': ['red', '✗'],
38
+ limit: ['yellow', '!'],
39
+ allow: ['green', '✓'],
40
+ disclose: ['dim', '•'],
41
+ understand: ['dim', '•'],
42
+ };
43
+ const NOTE_KINDS = new Set(['disclose', 'understand']);
44
+ const MAX_NOTES = 4;
45
+
46
+ export function parseArgs(argv) {
47
+ const options = { json: false, failOnBan: false, help: false, version: false };
48
+ const rest = [];
49
+ for (let i = 0; i < argv.length; i++) {
50
+ const arg = argv[i];
51
+ if (arg === '--json') options.json = true;
52
+ else if (arg === '--fail-on-ban') options.failOnBan = true;
53
+ else if (arg === '-h' || arg === '--help') options.help = true;
54
+ else if (arg === '-v' || arg === '--version') options.version = true;
55
+ else if (arg === '--issue') options.issue = Number(argv[++i]);
56
+ else if (arg.startsWith('--issue=')) options.issue = Number(arg.slice('--issue='.length));
57
+ else rest.push(arg);
58
+ }
59
+ options.target = rest[0];
60
+ return options;
61
+ }
62
+
63
+ function painter(enabled) {
64
+ const codes = { red: 31, green: 32, yellow: 33, dim: 2, bold: 1 };
65
+ return (color, text) => (enabled ? `\x1b[${codes[color]}m${text}\x1b[0m` : text);
66
+ }
67
+
68
+ function shorten(sentence, max = 160) {
69
+ return sentence.length > max ? `${sentence.slice(0, max - 1)}…` : sentence;
70
+ }
71
+
72
+ function render(result, paint) {
73
+ const lines = [];
74
+ const [color, label] = VERDICTS[result.verdict];
75
+ lines.push(`${paint('bold', result.repo)} ${paint('dim', result.url)}`, '');
76
+ lines.push(`Verdict: ${paint(color, paint('bold', label))}`);
77
+ if (result.beginnerBan) lines.push(paint('red', ' ✗ AI is not allowed on "good first issue" / beginner issues'));
78
+ if (result.limits) lines.push(paint('yellow', ' ! Some kinds of AI use are limited (see the ! lines below)'));
79
+ if (result.disclosure) lines.push(' • Say in your PR that AI helped');
80
+ if (result.mustUnderstand) lines.push(' • You must understand and be able to explain your change');
81
+ if (result.hasAgentInstructions && (result.verdict === 'unclear' || result.verdict === 'no-policy')) {
82
+ lines.push(' • It has instructions for AI coding tools (like AGENTS.md), so AI tools are expected,');
83
+ lines.push(' but no written rule for contributors was found. Ask in the issue before opening a PR.');
84
+ }
85
+
86
+ if (result.issue) {
87
+ const { number, title, labels } = result.issue;
88
+ const beginner = labels.some((l) => BEGINNER_LABEL.test(l));
89
+ lines.push('', `Issue #${number}: ${title}`);
90
+ lines.push(` labels: ${labels.length ? labels.join(', ') : '(none)'}`);
91
+ if (beginner && (result.beginnerBan || result.verdict === 'banned')) {
92
+ lines.push(paint('red', ' ✗ This is a beginner issue and this project bans AI on it. Fix it by hand or pick another issue.'));
93
+ } else if (beginner) {
94
+ lines.push(paint('yellow', ' ! This is a beginner issue. Many projects want these done by hand, so ask first.'));
95
+ }
96
+ }
97
+
98
+ const notes = result.evidence.filter((e) => NOTE_KINDS.has(e.kind));
99
+ const shownNotes = new Set(notes.slice(0, MAX_NOTES));
100
+ const shown = result.evidence.filter((e) => !NOTE_KINDS.has(e.kind) || shownNotes.has(e));
101
+ if (shown.length) {
102
+ lines.push('', 'Why:');
103
+ let lastFile;
104
+ for (const e of shown) {
105
+ if (e.file !== lastFile) lines.push(` ${paint('dim', e.file)}`);
106
+ lastFile = e.file;
107
+ const [markColor, mark] = KIND_MARK[e.kind];
108
+ lines.push(` ${paint(markColor, mark)} "${shorten(e.sentence)}"`);
109
+ }
110
+ const hidden = notes.length - shownNotes.size;
111
+ if (hidden > 0) lines.push(paint('dim', ` (+${hidden} more notes, use --json to see all)`));
112
+ }
113
+
114
+ lines.push('', paint('dim', `Checked: ${result.checked.length ? result.checked.join(', ') : 'no contributing or AI policy files found'}`));
115
+ lines.push(paint('dim', 'This is an automatic guess from keywords. Always read the policy yourself before opening a PR.'));
116
+ return lines.join('\n');
117
+ }
118
+
119
+ export async function run(
120
+ argv,
121
+ { stdout = process.stdout, stderr = process.stderr, env = process.env, fetchImpl = globalThis.fetch } = {},
122
+ ) {
123
+ const options = parseArgs(argv);
124
+ if (options.version) {
125
+ stdout.write(`${version}\n`);
126
+ return 0;
127
+ }
128
+ if (options.help || !options.target) {
129
+ stdout.write(`${HELP}\n`);
130
+ return options.help ? 0 : 1;
131
+ }
132
+
133
+ const target = parseTarget(options.target);
134
+ if (!target) {
135
+ stderr.write(`Could not read "${options.target}". Use owner/repo or a GitHub link.\n`);
136
+ return 1;
137
+ }
138
+ const issueNumber = options.issue ?? target.issue;
139
+ if (issueNumber !== undefined && !Number.isInteger(issueNumber)) {
140
+ stderr.write('--issue needs a number, for example --issue 123\n');
141
+ return 1;
142
+ }
143
+
144
+ const client = createClient({ token: env.GITHUB_TOKEN || env.GH_TOKEN, fetchImpl });
145
+ try {
146
+ const { fullName, url, files } = await client.collectPolicyFiles(target.owner, target.repo);
147
+ const result = {
148
+ repo: fullName,
149
+ url,
150
+ ...analyze(files),
151
+ hasAgentInstructions: files.some((f) => isAIFile(f.path) && !/AI[_-]?POLICY/i.test(f.path)),
152
+ checked: files.map((f) => f.label),
153
+ };
154
+ if (issueNumber !== undefined) result.issue = await client.getIssue(target.owner, target.repo, issueNumber);
155
+
156
+ if (options.json) stdout.write(`${JSON.stringify(result, null, 2)}\n`);
157
+ else stdout.write(`${render(result, painter(stdout.isTTY && !env.NO_COLOR))}\n`);
158
+
159
+ return options.failOnBan && result.verdict === 'banned' ? 2 : 0;
160
+ } catch (error) {
161
+ if (error instanceof GitHubError) {
162
+ stderr.write(`${error.message}\n`);
163
+ return 1;
164
+ }
165
+ throw error;
166
+ }
167
+ }
168
+
package/src/github.js ADDED
@@ -0,0 +1,81 @@
1
+ const API = 'https://api.github.com';
2
+
3
+ const WANTED = {
4
+ '': ['contributing.md', 'contributing', 'agents.md', 'claude.md', 'gemini.md', 'ai_policy.md', 'ai-policy.md', 'ai.md'],
5
+ '.github': ['contributing.md', 'ai_policy.md', 'ai-policy.md', 'copilot-instructions.md', 'pull_request_template.md'],
6
+ docs: ['contributing.md', 'ai_policy.md', 'ai-policy.md'],
7
+ };
8
+ const ORG_WANTED = ['ai_policy.md', 'ai-policy.md'];
9
+
10
+ export class GitHubError extends Error {}
11
+
12
+ export function parseTarget(input) {
13
+ const text = String(input ?? '').trim();
14
+ const match =
15
+ text.match(/^(?:https?:\/\/)?(?:www\.)?github\.com\/([\w.-]+)\/([\w.-]+?)(?:\.git)?(?:\/(?:issues|pull)\/(\d+))?\/?(?:[?#].*)?$/i) ??
16
+ text.match(/^([\w.-]+)\/([\w.-]+?)(?:#(\d+))?$/);
17
+ if (!match) return null;
18
+ return { owner: match[1], repo: match[2], issue: match[3] ? Number(match[3]) : undefined };
19
+ }
20
+
21
+ export function createClient({ token, fetchImpl = globalThis.fetch } = {}) {
22
+ const headers = { Accept: 'application/vnd.github+json', 'User-Agent': 'ai-policy-check' };
23
+ if (token) headers.Authorization = `Bearer ${token}`;
24
+
25
+ async function api(path) {
26
+ const res = await fetchImpl(`${API}${path}`, { headers });
27
+ if (res.status === 404) return null;
28
+ if (res.status === 403 || res.status === 429) {
29
+ throw new GitHubError(
30
+ 'GitHub rate limit reached. Wait an hour, or set a GITHUB_TOKEN environment variable to get a higher limit.',
31
+ );
32
+ }
33
+ if (!res.ok) throw new GitHubError(`GitHub API error ${res.status} for ${path}`);
34
+ return res.json();
35
+ }
36
+
37
+ async function text(url) {
38
+ const res = await fetchImpl(url, { headers: { 'User-Agent': 'ai-policy-check' } });
39
+ if (!res.ok) throw new GitHubError(`Could not download ${url} (${res.status})`);
40
+ return res.text();
41
+ }
42
+
43
+ async function listWanted(owner, repo, dir, names) {
44
+ const entries = await api(`/repos/${owner}/${repo}/contents/${dir}`);
45
+ if (!Array.isArray(entries)) return [];
46
+ return entries.filter((e) => e.type === 'file' && names.includes(e.name.toLowerCase()));
47
+ }
48
+
49
+ async function collectPolicyFiles(owner, repo) {
50
+ const info = await api(`/repos/${owner}/${repo}`);
51
+ if (!info) throw new GitHubError(`Repository ${owner}/${repo} not found (or it is private).`);
52
+ const fullName = info.full_name;
53
+
54
+ const found = [];
55
+ for (const [dir, names] of Object.entries(WANTED)) {
56
+ for (const entry of await listWanted(owner, repo, dir, names)) {
57
+ found.push({ path: entry.path, label: entry.path, url: entry.download_url });
58
+ }
59
+ }
60
+
61
+ const owners = info.owner?.login ?? owner;
62
+ if (repo.toLowerCase() !== '.github') {
63
+ const hasContributing = found.some((f) => /contributing/i.test(f.path));
64
+ const orgNames = hasContributing ? ORG_WANTED : [...ORG_WANTED, 'contributing.md'];
65
+ for (const entry of await listWanted(owners, '.github', '', orgNames)) {
66
+ found.push({ path: entry.path, label: `${owners}/.github: ${entry.path}`, url: entry.download_url });
67
+ }
68
+ }
69
+
70
+ const files = await Promise.all(found.map(async (f) => ({ ...f, text: await text(f.url) })));
71
+ return { fullName, url: info.html_url, files };
72
+ }
73
+
74
+ async function getIssue(owner, repo, number) {
75
+ const issue = await api(`/repos/${owner}/${repo}/issues/${number}`);
76
+ if (!issue) throw new GitHubError(`Issue #${number} not found in ${owner}/${repo}.`);
77
+ return { number, title: issue.title, labels: issue.labels.map((l) => (typeof l === 'string' ? l : l.name)) };
78
+ }
79
+
80
+ return { collectPolicyFiles, getIssue };
81
+ }