@kartiksomani/ais 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/README.md CHANGED
@@ -1,3 +1,116 @@
1
- # Temporary Holding Version
1
+ # ais
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
+ Fast, deterministic, failure-first PR triage CLI that compiles a sub-1,000-token Markdown brief for unblocking stuck GitHub PRs.
4
+
5
+ Zero LLM calls. Exact `o200k_base` token budgeting. Cross-platform (Windows, macOS, Linux).
6
+
7
+ ## Why `ais`?
8
+
9
+ Raw GitHub PRs dump tens of thousands of tokens of runner setup logs, ANSI codes, resolved review chatter, and third-party stack frames into your context window. `ais` deterministically strips the noise and compiles only what you need to unblock a PR:
10
+
11
+ 1. **Failing CI Checks (~45% budget)** — Strips ANSI codes, timestamps, runner setup/teardown blocks, and third-party/stdlib stack frames (`node_modules`, `site-packages`, `/usr/local/go`, etc.). Retains job/step name, command, primary error, and user-land frames.
12
+ 2. **Unresolved Review Hunks (~35% budget)** — Fetches only `isResolved: false` threads via GitHub GraphQL, drops outdated/collapsed noise and bot badge markup, and anchors each comment to its 5–10 line diff hunk. Switches to compact 1-line summaries on overflow unless `--full` is set.
13
+ 3. **Filtered Blast Radius (~15% budget)** — Scopes strictly to files and symbols already referenced in failing stack traces or unresolved reviews, emitting `file -> symbol -> callers | tests` tuples via local `git grep`.
14
+
15
+ ## Requirements
16
+
17
+ - Node.js 20+
18
+ - GitHub credentials via `GITHUB_TOKEN` or an authenticated [GitHub CLI (`gh`)](https://cli.github.com/) session
19
+
20
+ ## Installation
21
+
22
+ bash
23
+ git clone [https://github.com/ktsomani/ais.git](https://github.com/ktsomani/ais.git)
24
+ cd ais
25
+ npm install
26
+ npm run build
27
+ npm link
28
+
29
+
30
+ ## Authentication
31
+
32
+ `ais` requires no login flow or config file. It resolves credentials automatically in this order:
33
+
34
+ 1. process.env.GITHUB_TOKEN`
35
+ 2. gh auth token`
36
+
37
+ ## Usage
38
+
39
+ bash
40
+ # Auto-detect the open PR for your current local git branch
41
+ ais fix
42
+
43
+ # Triage by PR number in the current repo
44
+ ais fix 42
45
+
46
+ # Triage any PR by URL
47
+ ais fix [https://github.com/owner/repo/pull/42](https://github.com/owner/repo/pull/42)
48
+
49
+
50
+ ### Flags
51
+
52
+ | Flag | Default | Description |
53
+ | :--- | :--- | :--- |
54
+ | `--budget <number>` | `1000` | Max token cap counted with `o200k_base` |
55
+ | `--full` | `false` | Disable truncation when unresolved review threads overflow the budget |
56
+ | `--json` | `false` | Output structured JSON instead of Markdown (for eval pipelines) |
57
+
58
+ ### Piping to Coding Agents
59
+
60
+ bash
61
+ ais fix 42 | pbcopy # macOS
62
+ ais fix 42 | clip # Windows
63
+ ais fix 42 --json > pr-brief.json # Downstream evals
64
+
65
+
66
+ ## Example Output
67
+
68
+ md
69
+ # PR #42: Fix JWT expiry check (fix/jwt-exp)
70
+ Tokens: 412/1000 | Failed Checks: 1 | Unresolved Threads: 1
71
+
72
+ ## 1. Failing CI
73
+ - **unit-tests (npm test)**: `FAIL src/auth/jwt.test.ts > verifySession > rejects expired tokens`
74
+ text
75
+ $ npm test
76
+ AssertionError: expected true to be false
77
+ ❯ src/auth/jwt.test.ts:42:28
78
+ at verifySession (src/auth/jwt.ts:19:12)
79
+
80
+ ## 2. Unresolved Reviews
81
+ - **`src/auth/jwt.ts:24`** (@alice): Check `exp` against UTC seconds instead of milliseconds.
82
+ diff
83
+ const payload = decode(token);
84
+ if (!payload) return false;
85
+ const now = Date.now();
86
+ - return payload.exp > now;
87
+ + return payload.exp >= now;
88
+
89
+
90
+ ## 3. Blast Radius
91
+ - src/auth/jwt.ts -> verifySession -> callers: [src/routes/login.ts] | tests: [src/auth/jwt.test.ts]
92
+
93
+
94
+ ## Development
95
+
96
+ bash
97
+ npm run build # Compile TypeScript to dist/
98
+ npm test # Run Vitest unit test suite
99
+
100
+ ## Benchmarks (10 Live PRs)
101
+
102
+ Measured with `o200k_base` comparing raw PR context (`gh pr view` + `gh pr diff`) against `ais fix`:
103
+
104
+ | PR | Raw Tokens | `ais` Tokens | Ratio | CI Checks | Reviews | Time |
105
+ | :--- | ---: | ---: | ---: | ---: | ---: | ---: |
106
+ | `twentyhq/twenty#31534` | 22,881 | 338 | 67.7x | 2 | 1 | 6.3s |
107
+ | `twentyhq/twenty#31494` | 30,255 | 844 | 35.8x | 1 | 4 | 6.6s |
108
+ | `twentyhq/twenty#31377` | 30,013 | 747 | 40.2x | 6 | 1 | 7.4s |
109
+ | `vitest-dev/vitest#12029` | 8,045 | 382 | 21.1x | 3 | 0 | 6.2s |
110
+ | `vitest-dev/vitest#10691` | 9,423 | 750 | 12.6x | 7 | 3 | 2.8s |
111
+ | `pydantic/pydantic#14342` | 13,176 | 97 | 135.8x | 1 | 0 | 3.0s |
112
+ | `pydantic/pydantic#14339` | 14,346 | 77 | 186.3x | 0 | 0 | 2.9s |
113
+ | `kubernetes/kubernetes#144485` | 4,222 | 83 | 50.9x | 0 | 0 | 2.3s |
114
+ | `kubernetes/kubernetes#144461` | 5,165 | 80 | 64.6x | 0 | 0 | 2.5s |
115
+ | `kubernetes/kubernetes#144410` | 4,623 | 447 | 10.3x | 0 | 2 | 2.5s |
116
+ | **Total** | **142,149** | **3,845** | **37.0x** | **20** | **11** | **4.2s avg** |
package/dist/auth.d.ts ADDED
@@ -0,0 +1 @@
1
+ export declare function resolveGitHubToken(): string;
package/dist/auth.js ADDED
@@ -0,0 +1,21 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ export function resolveGitHubToken() {
3
+ const envToken = globalThis.process?.env?.GITHUB_TOKEN?.trim();
4
+ if (envToken) {
5
+ return envToken;
6
+ }
7
+ try {
8
+ const ghToken = execFileSync('gh', ['auth', 'token'], {
9
+ encoding: 'utf8',
10
+ stdio: ['ignore', 'pipe', 'pipe'],
11
+ timeout: 5000,
12
+ }).trim();
13
+ if (ghToken) {
14
+ return ghToken;
15
+ }
16
+ }
17
+ catch {
18
+ // Fall through to unified error message
19
+ }
20
+ throw new Error('No GitHub token found. Set GITHUB_TOKEN or authenticate with `gh auth login`.');
21
+ }
@@ -0,0 +1,2 @@
1
+ import type { BlastRadiusTuple, FailingCheck, UnresolvedReview } from './types.js';
2
+ export declare function computeBlastRadius(failingChecks: FailingCheck[], unresolvedReviews: UnresolvedReview[], cwd?: string): BlastRadiusTuple[];
@@ -0,0 +1,132 @@
1
+ import { execFileSync } from 'child_process';
2
+ import fs from 'node:fs';
3
+ import * as path from 'node:path';
4
+ const TEST_FILE_PATTERN = /(?:^|\/)(?:__tests__\/|tests?\/|test_[^/]+\.py$|[^/]+\.(?:test|spec)\.[jt]sx?$|[^/]+_test\.go$)/i;
5
+ const NON_CODE_FILE_PATTERN = /\.(?:md|txt|json|lock|ya?ml|toml|ini|svg|png|jpe?g|gif|ico|map|snap)$/i;
6
+ const GENERIC_STEMS = new Set(['index', 'main', 'mod', 'lib', '__init__', 'app', 'types']);
7
+ function normalizePath(filePath) {
8
+ return filePath.trim().replace(/\\/g, '/').replace(/^\.\//, '');
9
+ }
10
+ function stemOf(filePath) {
11
+ const base = path.posix.basename(normalizePath(filePath));
12
+ return base.replace(/\.[^.]+$/, '');
13
+ }
14
+ function isTestFile(filePath) {
15
+ return TEST_FILE_PATTERN.test(filePath);
16
+ }
17
+ function gitGrepFiles(pattern, cwd) {
18
+ const clean = pattern.trim();
19
+ if (!clean || clean.length < 2)
20
+ return [];
21
+ try {
22
+ const out = execFileSync('git', ['grep', '-l', '-F', '-w', '--', clean], {
23
+ cwd,
24
+ encoding: 'utf8',
25
+ stdio: ['ignore', 'pipe', 'pipe'],
26
+ timeout: 3000,
27
+ });
28
+ return out
29
+ .split(/\r?\n/)
30
+ .map((s) => normalizePath(s))
31
+ .filter((s) => Boolean(s) && !NON_CODE_FILE_PATTERN.test(s));
32
+ }
33
+ catch {
34
+ return [];
35
+ }
36
+ }
37
+ function findMatchingTests(file, cwd) {
38
+ const normalized = normalizePath(file);
39
+ if (isTestFile(normalized))
40
+ return [];
41
+ const dir = path.posix.dirname(normalized);
42
+ const ext = path.posix.extname(normalized);
43
+ const stem = stemOf(normalized);
44
+ if (!stem)
45
+ return [];
46
+ // Mirror subdirectory under tests/ (e.g. src/auth/jwt.ts -> tests/auth/jwt.test.ts)
47
+ const subDir = dir.replace(/^(?:src|lib|app|pkg)(?:\/|$)/, '');
48
+ const candidates = new Set([
49
+ path.posix.join(dir, `${stem}.test${ext}`),
50
+ path.posix.join(dir, `${stem}.spec${ext}`),
51
+ path.posix.join(dir, '__tests__', `${stem}.test${ext}`),
52
+ path.posix.join('tests', `${stem}.test${ext}`),
53
+ path.posix.join('test', `${stem}.test${ext}`),
54
+ ...(subDir
55
+ ? [
56
+ path.posix.join('tests', subDir, `${stem}.test${ext}`),
57
+ path.posix.join('test', subDir, `${stem}.test${ext}`),
58
+ path.posix.join('tests', subDir, `test_${stem}.py`),
59
+ ]
60
+ : []),
61
+ path.posix.join(dir, `test_${stem}.py`),
62
+ path.posix.join('tests', `test_${stem}.py`),
63
+ path.posix.join(dir, `${stem}_test.go`),
64
+ ]);
65
+ const found = [];
66
+ for (const candidate of candidates) {
67
+ const cleanCandidate = normalizePath(candidate);
68
+ if (cleanCandidate === normalized)
69
+ continue;
70
+ const abs = path.resolve(cwd, cleanCandidate);
71
+ if (fs.existsSync(abs) && fs.statSync(abs).isFile()) {
72
+ found.push(cleanCandidate);
73
+ }
74
+ }
75
+ return found;
76
+ }
77
+ export function computeBlastRadius(failingChecks, unresolvedReviews, cwd = process.cwd()) {
78
+ // Key by normalized file -> set of explicit symbols (falls back to stem only if none found)
79
+ const fileSymbols = new Map();
80
+ const record = (rawFile, rawSymbol) => {
81
+ const file = normalizePath(rawFile);
82
+ if (!file)
83
+ return;
84
+ if (!fileSymbols.has(file)) {
85
+ fileSymbols.set(file, new Set());
86
+ }
87
+ const sym = rawSymbol?.trim();
88
+ if (sym) {
89
+ fileSymbols.get(file).add(sym);
90
+ }
91
+ };
92
+ for (const check of failingChecks) {
93
+ for (const ref of check.referencedFiles) {
94
+ record(ref.file, ref.symbol);
95
+ }
96
+ }
97
+ for (const review of unresolvedReviews) {
98
+ record(review.file, review.symbol);
99
+ }
100
+ const tuples = [];
101
+ for (const [file, symbolsSet] of fileSymbols.entries()) {
102
+ const stem = stemOf(file);
103
+ const symbols = symbolsSet.size > 0 ? Array.from(symbolsSet) : [stem];
104
+ const baseTests = findMatchingTests(file, cwd);
105
+ for (const symbol of symbols) {
106
+ const matchingTests = new Set(baseTests);
107
+ const callers = new Set();
108
+ const searchStem = stem && stem !== symbol && !GENERIC_STEMS.has(stem.toLowerCase());
109
+ const grepHits = new Set([
110
+ ...(GENERIC_STEMS.has(symbol.toLowerCase()) ? [] : gitGrepFiles(symbol, cwd)),
111
+ ...(searchStem ? gitGrepFiles(stem, cwd) : []),
112
+ ]);
113
+ for (const hit of grepHits) {
114
+ if (hit === file)
115
+ continue;
116
+ if (isTestFile(hit)) {
117
+ matchingTests.add(hit);
118
+ }
119
+ else {
120
+ callers.add(hit);
121
+ }
122
+ }
123
+ tuples.push({
124
+ file,
125
+ symbol,
126
+ callers: Array.from(callers).sort().slice(0, 3),
127
+ tests: Array.from(matchingTests).sort().slice(0, 3),
128
+ });
129
+ }
130
+ }
131
+ return tuples;
132
+ }
@@ -0,0 +1,3 @@
1
+ import type { FailingCheck } from './types.js';
2
+ export declare function stripAnsiAndTimestamps(raw: string): string;
3
+ export declare function parseFailingJobLog(jobName: string, rawLog: string): FailingCheck;
@@ -0,0 +1,151 @@
1
+ // eslint-disable-next-line no-control-regex
2
+ const ANSI_REGEX = /\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g;
3
+ const TIMESTAMP_REGEX = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z\s?/;
4
+ const SETUP_TEARDOWN_GROUP = /^(?:Set up job|Complete job|Post\s|Run actions\/|Setup\s|Cache\s|Fetching the repository|Checking out the ref|Getting Git version|Initializing the repository|Cleaning up|Evaluate and set job outputs)/i;
5
+ const RUNNER_NOISE_LINE = /^(?:##\[debug\]|##\[notice\]|Current runner version:|Operating System|Runner Image|GITHUB_TOKEN Permissions|Secret source:|Prepare workflow directory|Prepare all required actions|Getting action download info|Cleaning up orphan processes)/i;
6
+ const THIRD_PARTY_FRAME = /(?:node_modules|node:internal\/|internal\/modules\/|site-packages|dist-packages|\/usr\/lib\/python|\/usr\/local\/lib\/python|\/opt\/hostedtoolcache\/|\/usr\/local\/go\/src\/|\/go\/pkg\/mod\/|\bruntime\/proc\.go|\btesting\/testing\.go|\b_pytest\/|\bpluggy\/|\bvitest\/dist\/|\bjest-circus\/)/i;
7
+ const ERROR_PATTERNS = [
8
+ /^##\[error\]\s*(.+)/i,
9
+ /^(?:FAIL|FAILED)\s+.+/,
10
+ /^---\s*FAIL:\s*.+/,
11
+ /^(?:AssertionError|TypeError|ReferenceError|SyntaxError|RangeError|ValueError|KeyError|AttributeError|RuntimeError|ImportError|ModuleNotFoundError|Error):.*/,
12
+ /^error TS\d+:.+/,
13
+ /^E\s{2,}.+/,
14
+ /^[×✕]\s+.+/,
15
+ /^(?:Expected|Received|Actual)\s*[:(].*/,
16
+ /^panic:\s*.+/,
17
+ /^\s*Error(?:\s+Trace)?:\s+.+/,
18
+ /^\s*[\w./-]+_test\.go:\d+:\s+.+/,
19
+ ];
20
+ const USER_FRAME_PATTERNS = [
21
+ // JS / TS: at fn (src/file.ts:12:5) or src/file.ts:12:5
22
+ /^\s*at\s+(?:(?<sym>[\w$.<>[\] ]+)\s+)?\(?(?<file>(?:[A-Za-z]:)?\/?(?:[\w@.-]+\/)*[\w.-]+\.(?:ts|tsx|js|jsx|mjs|cjs)):\d+(?::\d+)?\)?/,
23
+ /^\s*[❯>]\s*(?<file>(?:[A-Za-z]:)?\/?(?:[\w@.-]+\/)*[\w.-]+\.(?:ts|tsx|js|jsx|mjs|cjs)):\d+:\d+/,
24
+ // Python: File "app/service.py", line 42, in process
25
+ /^\s*File\s+"(?<file>[^"]+\.py)",\s+line\s+\d+(?:,\s+in\s+(?<sym>[\w.<>]+))?/,
26
+ // Go: /abs/path/pkg/foo/bar.go:42 +0x1a or pkg/foo/bar_test.go:18: msg
27
+ /^\s*(?<file>(?:[A-Za-z]:)?\/?(?:[\w.-]+\/)*[\w.-]+\.go):\d+/,
28
+ ];
29
+ export function stripAnsiAndTimestamps(raw) {
30
+ return raw
31
+ .replace(/\r\n/g, '\n')
32
+ .replace(ANSI_REGEX, '')
33
+ .split('\n')
34
+ .map((line) => line.replace(TIMESTAMP_REGEX, ''))
35
+ .join('\n');
36
+ }
37
+ function normalizeRepoPath(filePath) {
38
+ return filePath
39
+ .replace(/\\/g, '/')
40
+ .replace(/^\/home\/runner\/work\/[^/]+\/[^/]+\//, '')
41
+ .replace(/^\/github\/workspace\//, '')
42
+ .replace(/^[A-Za-z]:\/a\/[^/]+\/[^/]+\//, '')
43
+ .replace(/^\.\//, '');
44
+ }
45
+ export function parseFailingJobLog(jobName, rawLog) {
46
+ const cleaned = stripAnsiAndTimestamps(rawLog);
47
+ const lines = cleaned.split('\n');
48
+ let inIgnoredGroup = false;
49
+ let lastCommand;
50
+ let activeStepName;
51
+ const errorLines = [];
52
+ const stackLines = [];
53
+ const referencedFiles = new Map();
54
+ for (let i = 0; i < lines.length; i++) {
55
+ const line = lines[i];
56
+ const trimmed = line.trim();
57
+ if (!trimmed)
58
+ continue;
59
+ if (trimmed.startsWith('##[group]')) {
60
+ const groupTitle = trimmed.slice('##[group]'.length).trim();
61
+ if (SETUP_TEARDOWN_GROUP.test(groupTitle)) {
62
+ inIgnoredGroup = true;
63
+ continue;
64
+ }
65
+ inIgnoredGroup = false;
66
+ if (/^Run\s+/i.test(groupTitle)) {
67
+ lastCommand = groupTitle.replace(/^Run\s+/i, '').trim();
68
+ activeStepName = lastCommand;
69
+ }
70
+ continue;
71
+ }
72
+ if (trimmed.startsWith('##[endgroup]')) {
73
+ inIgnoredGroup = false;
74
+ continue;
75
+ }
76
+ if (inIgnoredGroup || RUNNER_NOISE_LINE.test(trimmed)) {
77
+ continue;
78
+ }
79
+ if (trimmed.startsWith('##[command]')) {
80
+ const cmd = trimmed.slice('##[command]'.length).trim();
81
+ if (!SETUP_TEARDOWN_GROUP.test(cmd)) {
82
+ lastCommand = cmd;
83
+ }
84
+ continue;
85
+ }
86
+ // Drop third-party / stdlib stack frames
87
+ if (THIRD_PARTY_FRAME.test(trimmed)) {
88
+ continue;
89
+ }
90
+ // Check for user-land stack frames
91
+ let matchedFrame = false;
92
+ for (const pattern of USER_FRAME_PATTERNS) {
93
+ const m = line.match(pattern);
94
+ if (m?.groups?.file) {
95
+ const normalizedFile = normalizeRepoPath(m.groups.file);
96
+ const sym = m.groups.sym?.trim();
97
+ if (!referencedFiles.has(normalizedFile) || (!referencedFiles.get(normalizedFile) && sym)) {
98
+ referencedFiles.set(normalizedFile, sym);
99
+ }
100
+ // Preserve Go's preceding function line if present (e.g. github.com/org/repo/pkg.Fn(...))
101
+ if (normalizedFile.endsWith('.go') && i > 0) {
102
+ const prev = lines[i - 1].trim();
103
+ const goFn = prev.match(/([A-Za-z0-9_.*()]+)\([^)]*\)$/);
104
+ if (goFn && !THIRD_PARTY_FRAME.test(prev)) {
105
+ const cleanedSym = goFn[1].replace(/^.*\./, '');
106
+ if (!referencedFiles.get(normalizedFile)) {
107
+ referencedFiles.set(normalizedFile, cleanedSym);
108
+ }
109
+ }
110
+ }
111
+ stackLines.push(trimmed.replace(m.groups.file, normalizedFile));
112
+ matchedFrame = true;
113
+ break;
114
+ }
115
+ }
116
+ // Check for primary error / assertion lines
117
+ if (ERROR_PATTERNS.some((p) => p.test(trimmed))) {
118
+ const cleanErr = trimmed.replace(/^##\[error\]\s*/i, '');
119
+ // Ignore generic exit-code wrapper if we already have a real error
120
+ if (/^Process completed with exit code \d+\.?$/i.test(cleanErr)) {
121
+ if (errorLines.length === 0)
122
+ errorLines.push(cleanErr);
123
+ }
124
+ else {
125
+ errorLines.push(cleanErr);
126
+ if (!matchedFrame) {
127
+ stackLines.push(cleanErr);
128
+ }
129
+ }
130
+ }
131
+ }
132
+ // Deduplicate while preserving deterministic order
133
+ const uniqueTrace = Array.from(new Set(stackLines)).slice(0, 14);
134
+ const primaryError = errorLines.find((e) => !/^Process completed with exit code/i.test(e)) ??
135
+ errorLines[0] ??
136
+ 'Job failed (see CI logs)';
137
+ const displayJob = activeStepName ? `${jobName} (${activeStepName})` : jobName;
138
+ if (lastCommand && uniqueTrace.length > 0 && !uniqueTrace[0].startsWith('$ ')) {
139
+ uniqueTrace.unshift(`$ ${lastCommand}`);
140
+ }
141
+ return {
142
+ jobName: displayJob,
143
+ command: lastCommand,
144
+ errorSummary: primaryError.slice(0, 180),
145
+ stackTrace: uniqueTrace,
146
+ referencedFiles: Array.from(referencedFiles.entries()).map(([file, symbol]) => ({
147
+ file,
148
+ symbol,
149
+ })),
150
+ };
151
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,38 @@
1
+ #!/usr/bin/env node
2
+ import { Command } from 'commander';
3
+ import { runFix } from './index.js';
4
+ const program = new Command();
5
+ program
6
+ .name('ais')
7
+ .description('Fast, deterministic, failure-first PR triage CLI')
8
+ .version('0.1.0');
9
+ program
10
+ .command('fix')
11
+ .description('Compile a failure-first triage brief for a GitHub PR')
12
+ .argument('[pr]', 'PR number or full GitHub PR URL (auto-detects current branch if omitted)')
13
+ .option('--budget <number>', 'Max token cap using o200k_base', '1000')
14
+ .option('--full', 'Disable truncation when unresolved review threads overflow budget', false)
15
+ .option('--json', 'Output structured JSON instead of Markdown', false)
16
+ .action(async (pr, opts) => {
17
+ const budget = Number.parseInt(opts.budget, 10);
18
+ if (!Number.isFinite(budget) || budget < 50) {
19
+ process.stderr.write('Error: --budget must be an integer >= 50.\n');
20
+ process.exitCode = 1;
21
+ return;
22
+ }
23
+ try {
24
+ const output = await runFix({
25
+ pr,
26
+ budget,
27
+ full: Boolean(opts.full),
28
+ json: Boolean(opts.json),
29
+ });
30
+ process.stdout.write(output + '\n');
31
+ }
32
+ catch (err) {
33
+ const message = err instanceof Error ? err.message : String(err);
34
+ process.stderr.write(`Error: ${message}\n`);
35
+ process.exitCode = 1;
36
+ }
37
+ });
38
+ program.parseAsync(process.argv);
@@ -0,0 +1,5 @@
1
+ import type { BlastRadiusTuple, CompileOptions, FailingCheck, PRMetadata, TriageBrief, UnresolvedReview } from './types.js';
2
+ export declare function compileBrief(pr: PRMetadata, failingChecks: FailingCheck[], unresolvedReviews: UnresolvedReview[], blastRadius: BlastRadiusTuple[], options: CompileOptions): {
3
+ markdown: string;
4
+ brief: TriageBrief;
5
+ };
@@ -0,0 +1,137 @@
1
+ import { renderReviewsWithinBudget } from './reviews.js';
2
+ import { countTokens, truncateToTokens } from './tokens.js';
3
+ function formatCheckBlock(check, maxTraceLines) {
4
+ const lines = check.stackTrace.slice(0, maxTraceLines);
5
+ if (lines.length === 0) {
6
+ return `- **${check.jobName}**: \`${check.errorSummary}\``;
7
+ }
8
+ return [
9
+ `- **${check.jobName}**: \`${check.errorSummary}\``,
10
+ ' ```text',
11
+ ...lines.map((l) => ` ${l}`),
12
+ ' ```',
13
+ ].join('\n');
14
+ }
15
+ function renderCISection(checks, budgetTokens, full) {
16
+ if (checks.length === 0)
17
+ return '- None';
18
+ const blocks = [];
19
+ let used = 0;
20
+ for (const check of checks) {
21
+ let block = formatCheckBlock(check, check.stackTrace.length);
22
+ if (!full && used + countTokens(block) > budgetTokens) {
23
+ // Progressively trim stack trace lines to stay within Priority 1 budget
24
+ const remaining = Math.max(0, budgetTokens - used);
25
+ let fitted = null;
26
+ for (let keep = Math.min(check.stackTrace.length, 6); keep >= 0; keep--) {
27
+ const candidate = formatCheckBlock(check, keep);
28
+ if (countTokens(candidate) <= remaining) {
29
+ fitted = candidate;
30
+ break;
31
+ }
32
+ }
33
+ if (!fitted) {
34
+ if (blocks.length === 0 && remaining > 12) {
35
+ fitted = truncateToTokens(formatCheckBlock(check, 0), remaining);
36
+ }
37
+ else {
38
+ break;
39
+ }
40
+ }
41
+ block = fitted;
42
+ }
43
+ blocks.push(block);
44
+ used += countTokens((blocks.length > 1 ? '\n' : '') + block);
45
+ }
46
+ return blocks.join('\n') || '- None';
47
+ }
48
+ function renderBlastRadiusSection(tuples, budgetTokens, full) {
49
+ if (tuples.length === 0)
50
+ return '- None';
51
+ const lines = [];
52
+ let used = 0;
53
+ for (const t of tuples) {
54
+ const callers = t.callers.join(', ');
55
+ const tests = t.tests.join(', ');
56
+ const line = `- \`${t.file} -> ${t.symbol} -> callers: [${callers}] | tests: [${tests}]\``;
57
+ const cost = countTokens((lines.length > 0 ? '\n' : '') + line);
58
+ if (!full && used + cost > budgetTokens) {
59
+ break;
60
+ }
61
+ lines.push(line);
62
+ used += cost;
63
+ }
64
+ return lines.join('\n') || '- None';
65
+ }
66
+ function assembleMarkdown(pr, tokenCount, budget, failedChecksCount, unresolvedThreadsCount, ciBody, reviewsBody, blastBody) {
67
+ return [
68
+ `# PR #${pr.number}: ${pr.title} (${pr.branch})`,
69
+ `Tokens: ${tokenCount}/${budget} | Failed Checks: ${failedChecksCount} | Unresolved Threads: ${unresolvedThreadsCount}`,
70
+ '',
71
+ '## 1. Failing CI',
72
+ ciBody,
73
+ '',
74
+ '## 2. Unresolved Reviews',
75
+ reviewsBody,
76
+ '',
77
+ '## 3. Blast Radius',
78
+ blastBody,
79
+ ].join('\n');
80
+ }
81
+ export function compileBrief(pr, failingChecks, unresolvedReviews, blastRadius, options) {
82
+ const { budget, full } = options;
83
+ // Measure fixed scaffolding overhead (~5% of budget)
84
+ const scaffoldTokens = countTokens(assembleMarkdown(pr, budget, budget, failingChecks.length, unresolvedReviews.length, '', '', ''));
85
+ const available = Math.max(0, budget - scaffoldTokens);
86
+ // Priority allocations: 45% CI, 35% Reviews, 15% Blast Radius (unused budget rolls forward)
87
+ const ciBudget = Math.floor(available * 0.45);
88
+ let ciBody = renderCISection(failingChecks, ciBudget, full);
89
+ const ciUsed = countTokens(ciBody);
90
+ const reviewBudget = Math.floor(available * 0.35) + Math.max(0, ciBudget - ciUsed);
91
+ const reviewResult = renderReviewsWithinBudget(unresolvedReviews, reviewBudget, full);
92
+ let reviewsBody = reviewResult.markdown;
93
+ const reviewsUsed = countTokens(reviewsBody);
94
+ const blastBudget = Math.max(0, available - ciUsed - reviewsUsed);
95
+ let blastBody = renderBlastRadiusSection(blastRadius, blastBudget, full);
96
+ // Strict budget enforcement when --full is not set
97
+ let finalMarkdown = assembleMarkdown(pr, 0, budget, failingChecks.length, unresolvedReviews.length, ciBody, reviewsBody, blastBody);
98
+ let actualTokens = countTokens(finalMarkdown);
99
+ finalMarkdown = assembleMarkdown(pr, actualTokens, budget, failingChecks.length, unresolvedReviews.length, ciBody, reviewsBody, blastBody);
100
+ actualTokens = countTokens(finalMarkdown);
101
+ // Hard cap fallback in case of tight custom --budget values
102
+ if (!full && actualTokens > budget) {
103
+ const excess = actualTokens - budget;
104
+ if (blastBody !== '- None') {
105
+ blastBody = '- None';
106
+ }
107
+ finalMarkdown = assembleMarkdown(pr, actualTokens, budget, failingChecks.length, unresolvedReviews.length, ciBody, reviewsBody, blastBody);
108
+ actualTokens = countTokens(finalMarkdown);
109
+ if (actualTokens > budget) {
110
+ const targetBodyTokens = Math.max(0, countTokens(ciBody) - (actualTokens - budget) - 2);
111
+ ciBody = truncateToTokens(ciBody, targetBodyTokens);
112
+ finalMarkdown = assembleMarkdown(pr, actualTokens, budget, failingChecks.length, unresolvedReviews.length, ciBody, reviewsBody, blastBody);
113
+ actualTokens = countTokens(finalMarkdown);
114
+ }
115
+ if (actualTokens > budget && excess > 0) {
116
+ finalMarkdown = truncateToTokens(finalMarkdown, budget, '');
117
+ actualTokens = countTokens(finalMarkdown);
118
+ }
119
+ else {
120
+ // Refresh exact token header after trimming
121
+ finalMarkdown = assembleMarkdown(pr, actualTokens, budget, failingChecks.length, unresolvedReviews.length, ciBody, reviewsBody, blastBody);
122
+ actualTokens = countTokens(finalMarkdown);
123
+ }
124
+ }
125
+ const brief = {
126
+ pr,
127
+ tokens: actualTokens,
128
+ budget,
129
+ failedChecksCount: failingChecks.length,
130
+ unresolvedThreadsCount: unresolvedReviews.length,
131
+ truncatedThreadsCount: reviewResult.truncatedCount,
132
+ failingChecks,
133
+ unresolvedReviews: reviewResult.included,
134
+ blastRadius,
135
+ };
136
+ return { markdown: finalMarkdown, brief };
137
+ }
package/dist/git.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ import type { PRTarget } from './types.js';
2
+ export declare function parsePRUrl(input: string): PRTarget | null;
3
+ export declare function parseGitRemoteUrl(remoteUrl: string): {
4
+ owner: string;
5
+ repo: string;
6
+ };
7
+ export declare function getLocalGitContext(cwd?: string): {
8
+ owner: string;
9
+ repo: string;
10
+ branch: string;
11
+ };
package/dist/git.js ADDED
@@ -0,0 +1,47 @@
1
+ // @ts-ignore Node.js type definitions are not available in this project.
2
+ import { execFileSync } from 'child_process';
3
+ const PR_URL_REGEX = /^https?:\/\/github\.com\/([^/]+)\/([^/]+)\/pull\/(\d+)(?:[/?#].*)?$/i;
4
+ export function parsePRUrl(input) {
5
+ const match = input.trim().match(PR_URL_REGEX);
6
+ if (!match)
7
+ return null;
8
+ return {
9
+ owner: match[1],
10
+ repo: match[2],
11
+ number: Number.parseInt(match[3], 10),
12
+ };
13
+ }
14
+ export function parseGitRemoteUrl(remoteUrl) {
15
+ const trimmed = remoteUrl.trim();
16
+ // SSH: git@github.com:owner/repo.git
17
+ const sshMatch = trimmed.match(/^git@github\.com:([^/]+)\/(.+?)(?:\.git)?$/i);
18
+ if (sshMatch) {
19
+ return { owner: sshMatch[1], repo: sshMatch[2] };
20
+ }
21
+ // HTTPS / SSH URL: https://github.com/owner/repo.git or ssh://git@github.com/owner/repo.git
22
+ const urlMatch = trimmed.match(/github\.com[/:]([^/]+)\/([^/]+?)(?:\.git)?\/?$/i);
23
+ if (urlMatch) {
24
+ return { owner: urlMatch[1], repo: urlMatch[2] };
25
+ }
26
+ throw new Error(`Could not parse GitHub owner/repo from git remote: ${trimmed}`);
27
+ }
28
+ export function getLocalGitContext(cwd) {
29
+ try {
30
+ const remoteUrl = execFileSync('git', ['remote', 'get-url', 'origin'], {
31
+ cwd,
32
+ encoding: 'utf8',
33
+ stdio: ['ignore', 'pipe', 'pipe'],
34
+ }).trim();
35
+ const branch = execFileSync('git', ['rev-parse', '--abbrev-ref', 'HEAD'], {
36
+ cwd,
37
+ encoding: 'utf8',
38
+ stdio: ['ignore', 'pipe', 'pipe'],
39
+ }).trim();
40
+ const { owner, repo } = parseGitRemoteUrl(remoteUrl);
41
+ return { owner, repo, branch };
42
+ }
43
+ catch (err) {
44
+ const msg = err instanceof Error ? err.message : String(err);
45
+ throw new Error(`Failed to detect local git repository/branch: ${msg}`);
46
+ }
47
+ }
@@ -0,0 +1,20 @@
1
+ import type { PRMetadata, PRTarget, RawReviewThread } from './types.js';
2
+ export interface CheckRunSummary {
3
+ id: number;
4
+ name: string;
5
+ conclusion: string | null;
6
+ appSlug: string | null;
7
+ outputTitle: string | null;
8
+ outputSummary: string | null;
9
+ outputText: string | null;
10
+ }
11
+ export declare class GitHubClient {
12
+ private readonly token;
13
+ constructor(token: string);
14
+ private headers;
15
+ findOpenPRForBranch(owner: string, repo: string, branch: string): Promise<PRMetadata>;
16
+ getPRMetadata(target: PRTarget): Promise<PRMetadata>;
17
+ getFailingCheckRuns(owner: string, repo: string, headSha: string): Promise<CheckRunSummary[]>;
18
+ getActionsJobLog(owner: string, repo: string, jobId: number): Promise<string | null>;
19
+ getReviewThreads(target: PRTarget): Promise<RawReviewThread[]>;
20
+ }
package/dist/github.js ADDED
@@ -0,0 +1,165 @@
1
+ const REST_BASE = 'https://api.github.com';
2
+ const GRAPHQL_URL = 'https://api.github.com/graphql';
3
+ const FAILING_CONCLUSIONS = new Set([
4
+ 'failure',
5
+ 'timed_out',
6
+ 'action_required',
7
+ 'startup_failure',
8
+ ]);
9
+ export class GitHubClient {
10
+ token;
11
+ constructor(token) {
12
+ this.token = token;
13
+ }
14
+ headers(accept = 'application/vnd.github+json') {
15
+ return {
16
+ Authorization: `Bearer ${this.token}`,
17
+ Accept: accept,
18
+ 'X-GitHub-Api-Version': '2022-11-28',
19
+ 'User-Agent': 'ais-cli/0.1.0',
20
+ };
21
+ }
22
+ async findOpenPRForBranch(owner, repo, branch) {
23
+ const url = `${REST_BASE}/repos/${owner}/${repo}/pulls?state=open&head=${encodeURIComponent(`${owner}:${branch}`)}&per_page=1`;
24
+ const res = await fetch(url, { headers: this.headers() });
25
+ if (!res.ok) {
26
+ throw new Error(`GitHub API error (${res.status}) finding PR for branch "${branch}"`);
27
+ }
28
+ const prs = (await res.json());
29
+ if (prs.length === 0) {
30
+ throw new Error(`No open PR found for branch "${branch}" in ${owner}/${repo}.`);
31
+ }
32
+ const pr = prs[0];
33
+ return {
34
+ owner,
35
+ repo,
36
+ number: pr.number,
37
+ title: pr.title,
38
+ branch: pr.head.ref,
39
+ headSha: pr.head.sha,
40
+ };
41
+ }
42
+ async getPRMetadata(target) {
43
+ const url = `${REST_BASE}/repos/${target.owner}/${target.repo}/pulls/${target.number}`;
44
+ const res = await fetch(url, { headers: this.headers() });
45
+ if (!res.ok) {
46
+ throw new Error(`GitHub API error (${res.status}) fetching PR #${target.number} in ${target.owner}/${target.repo}`);
47
+ }
48
+ const pr = (await res.json());
49
+ return {
50
+ owner: target.owner,
51
+ repo: target.repo,
52
+ number: pr.number,
53
+ title: pr.title,
54
+ branch: pr.head.ref,
55
+ headSha: pr.head.sha,
56
+ };
57
+ }
58
+ async getFailingCheckRuns(owner, repo, headSha) {
59
+ const url = `${REST_BASE}/repos/${owner}/${repo}/commits/${headSha}/check-runs?per_page=100`;
60
+ const res = await fetch(url, { headers: this.headers() });
61
+ if (!res.ok) {
62
+ throw new Error(`GitHub API error (${res.status}) fetching check runs for ${headSha}`);
63
+ }
64
+ const data = (await res.json());
65
+ return data.check_runs
66
+ .filter((run) => run.conclusion !== null && FAILING_CONCLUSIONS.has(run.conclusion))
67
+ .map((run) => ({
68
+ id: run.id,
69
+ name: run.name,
70
+ conclusion: run.conclusion,
71
+ appSlug: run.app?.slug ?? null,
72
+ outputTitle: run.output?.title ?? null,
73
+ outputSummary: run.output?.summary ?? null,
74
+ outputText: run.output?.text ?? null,
75
+ }));
76
+ }
77
+ async getActionsJobLog(owner, repo, jobId) {
78
+ const url = `${REST_BASE}/repos/${owner}/${repo}/actions/jobs/${jobId}/logs`;
79
+ const res = await fetch(url, {
80
+ headers: this.headers(),
81
+ redirect: 'manual',
82
+ });
83
+ // GitHub redirects to a signed Azure Blob URL; fetch without Authorization header
84
+ if (res.status >= 300 && res.status < 400) {
85
+ const location = res.headers.get('location');
86
+ if (!location)
87
+ return null;
88
+ const logRes = await fetch(location);
89
+ if (!logRes.ok)
90
+ return null;
91
+ return await logRes.text();
92
+ }
93
+ if (res.ok) {
94
+ return await res.text();
95
+ }
96
+ return null;
97
+ }
98
+ async getReviewThreads(target) {
99
+ const query = `
100
+ query($owner: String!, $repo: String!, $number: Int!, $cursor: String) {
101
+ repository(owner: $owner, name: $repo) {
102
+ pullRequest(number: $number) {
103
+ reviewThreads(first: 100, after: $cursor) {
104
+ pageInfo {
105
+ hasNextPage
106
+ endCursor
107
+ }
108
+ nodes {
109
+ id
110
+ isResolved
111
+ isOutdated
112
+ isCollapsed
113
+ path
114
+ line
115
+ originalLine
116
+ comments(first: 10) {
117
+ nodes {
118
+ author { login }
119
+ body
120
+ diffHunk
121
+ }
122
+ }
123
+ }
124
+ }
125
+ }
126
+ }
127
+ }
128
+ `;
129
+ const allThreads = [];
130
+ let cursor = null;
131
+ while (true) {
132
+ const res = await fetch(GRAPHQL_URL, {
133
+ method: 'POST',
134
+ headers: {
135
+ ...this.headers(),
136
+ 'Content-Type': 'application/json',
137
+ },
138
+ body: JSON.stringify({
139
+ query,
140
+ variables: {
141
+ owner: target.owner,
142
+ repo: target.repo,
143
+ number: target.number,
144
+ cursor,
145
+ },
146
+ }),
147
+ });
148
+ if (!res.ok) {
149
+ throw new Error(`GitHub GraphQL error (${res.status}) fetching review threads`);
150
+ }
151
+ const payload = (await res.json());
152
+ if (payload.errors?.length) {
153
+ throw new Error(`GitHub GraphQL error: ${payload.errors[0].message}`);
154
+ }
155
+ const conn = payload.data?.repository?.pullRequest?.reviewThreads;
156
+ if (!conn)
157
+ break;
158
+ allThreads.push(...conn.nodes);
159
+ if (!conn.pageInfo.hasNextPage || !conn.pageInfo.endCursor)
160
+ break;
161
+ cursor = conn.pageInfo.endCursor;
162
+ }
163
+ return allThreads;
164
+ }
165
+ }
@@ -0,0 +1,8 @@
1
+ export interface FixCommandOptions {
2
+ pr?: string;
3
+ budget: number;
4
+ full: boolean;
5
+ json: boolean;
6
+ cwd?: string;
7
+ }
8
+ export declare function runFix(options: FixCommandOptions): Promise<string>;
package/dist/index.js ADDED
@@ -0,0 +1,53 @@
1
+ import { resolveGitHubToken } from './auth.js';
2
+ import { computeBlastRadius } from './blast-radius.js';
3
+ import { parseFailingJobLog } from './ci-parser.js';
4
+ import { compileBrief } from './compiler.js';
5
+ import { getLocalGitContext, parsePRUrl } from './git.js';
6
+ import { GitHubClient } from './github.js';
7
+ import { filterUnresolvedThreads } from './reviews.js';
8
+ export async function runFix(options) {
9
+ const token = resolveGitHubToken();
10
+ const client = new GitHubClient(token);
11
+ const cwd = options.cwd ?? '.';
12
+ let pr;
13
+ const rawPr = options.pr?.trim();
14
+ if (!rawPr) {
15
+ const local = getLocalGitContext(cwd);
16
+ pr = await client.findOpenPRForBranch(local.owner, local.repo, local.branch);
17
+ }
18
+ else {
19
+ const parsedUrl = parsePRUrl(rawPr);
20
+ if (parsedUrl) {
21
+ pr = await client.getPRMetadata(parsedUrl);
22
+ }
23
+ else if (/^#?\d+$/.test(rawPr)) {
24
+ const local = getLocalGitContext(cwd);
25
+ pr = await client.getPRMetadata({
26
+ owner: local.owner,
27
+ repo: local.repo,
28
+ number: Number.parseInt(rawPr.replace(/^#/, ''), 10),
29
+ });
30
+ }
31
+ else {
32
+ throw new Error(`Invalid PR identifier "${rawPr}". Pass a PR number (e.g. 42) or full GitHub PR URL.`);
33
+ }
34
+ }
35
+ const [failedCheckRuns, rawThreads] = await Promise.all([
36
+ client.getFailingCheckRuns(pr.owner, pr.repo, pr.headSha),
37
+ client.getReviewThreads(pr),
38
+ ]);
39
+ const failingChecks = await Promise.all(failedCheckRuns.map(async (run) => {
40
+ const rawLog = await client.getActionsJobLog(pr.owner, pr.repo, run.id);
41
+ if (rawLog) {
42
+ return parseFailingJobLog(run.name, rawLog);
43
+ }
44
+ const fallbackText = [run.outputTitle, run.outputSummary, run.outputText]
45
+ .filter((s) => Boolean(s))
46
+ .join('\n');
47
+ return parseFailingJobLog(run.name, fallbackText);
48
+ }));
49
+ const unresolvedReviews = filterUnresolvedThreads(rawThreads);
50
+ const blastRadius = computeBlastRadius(failingChecks, unresolvedReviews, cwd);
51
+ const { markdown, brief } = compileBrief(pr, failingChecks, unresolvedReviews, blastRadius, { budget: options.budget, full: options.full });
52
+ return options.json ? JSON.stringify(brief, null, 2) : markdown;
53
+ }
@@ -0,0 +1,14 @@
1
+ import type { RawReviewThread, UnresolvedReview } from './types.js';
2
+ export declare function extractAnchoredHunk(diffHunk: string, maxLines?: number): string;
3
+ export declare function extractSymbolFromHunk(diffHunk: string): string | undefined;
4
+ export declare function trimReviewComment(body: string, maxChars?: number): string;
5
+ export declare function filterUnresolvedThreads(rawThreads: RawReviewThread[]): UnresolvedReview[];
6
+ export declare function formatFullReviewItem(r: UnresolvedReview): string;
7
+ export declare function formatCompactReviewItem(r: UnresolvedReview): string;
8
+ export interface RenderedReviewsResult {
9
+ markdown: string;
10
+ included: UnresolvedReview[];
11
+ truncatedCount: number;
12
+ usedCompactMode: boolean;
13
+ }
14
+ export declare function renderReviewsWithinBudget(reviews: UnresolvedReview[], budgetTokens: number, full: boolean): RenderedReviewsResult;
@@ -0,0 +1,116 @@
1
+ import { countTokens } from './tokens.js';
2
+ const MAX_HUNK_LINES = 8;
3
+ const MIN_HUNK_LINES = 5;
4
+ const SYMBOL_DECLARATION_REGEX = /(?:export\s+)?(?:async\s+)?(?:function|class|interface|type|const|let|def|func)\s+(?:\([^)]+\)\s+)?([A-Za-z_][A-Za-z0-9_]*)/;
5
+ export function extractAnchoredHunk(diffHunk, maxLines = MAX_HUNK_LINES) {
6
+ const lines = diffHunk
7
+ .replace(/\r\n/g, '\n')
8
+ .split('\n')
9
+ .filter((l, idx, arr) => !(idx === arr.length - 1 && l === ''));
10
+ if (lines.length <= maxLines) {
11
+ return lines.join('\n');
12
+ }
13
+ // GitHub anchors review comments to the end of diffHunk; take the trailing 5–10 lines
14
+ const windowSize = Math.max(MIN_HUNK_LINES, Math.min(10, maxLines));
15
+ return lines.slice(-windowSize).join('\n');
16
+ }
17
+ export function extractSymbolFromHunk(diffHunk) {
18
+ const lines = diffHunk.split('\n').reverse();
19
+ for (const line of lines) {
20
+ const clean = line.replace(/^[+-@ ]+/, '');
21
+ const match = clean.match(SYMBOL_DECLARATION_REGEX);
22
+ if (match?.[1]) {
23
+ return match[1];
24
+ }
25
+ }
26
+ return undefined;
27
+ }
28
+ export function trimReviewComment(body, maxChars = 160) {
29
+ const collapsed = body
30
+ .replace(/\r\n/g, '\n')
31
+ .replace(/<!--[\s\S]*?-->/g, '')
32
+ .replace(/!\[[^\]]*\]\([^)]+\)/g, '')
33
+ .replace(/<\/?[^>]+(>|$)/g, '')
34
+ .replace(/```[\s\S]*?```/g, '[code]')
35
+ .replace(/\s+/g, ' ')
36
+ .trim();
37
+ if (collapsed.length <= maxChars)
38
+ return collapsed;
39
+ return collapsed.slice(0, maxChars - 1).trimEnd() + '…';
40
+ }
41
+ export function filterUnresolvedThreads(rawThreads) {
42
+ return rawThreads
43
+ .filter((t) => !t.isResolved &&
44
+ !t.isOutdated &&
45
+ !t.isCollapsed &&
46
+ t.comments.nodes.length > 0)
47
+ .map((t) => {
48
+ const first = t.comments.nodes[0];
49
+ const hunk = extractAnchoredHunk(first.diffHunk);
50
+ return {
51
+ file: t.path,
52
+ line: t.line ?? t.originalLine ?? 1,
53
+ author: first.author?.login ?? 'reviewer',
54
+ comment: trimReviewComment(first.body),
55
+ diffHunk: hunk,
56
+ symbol: extractSymbolFromHunk(first.diffHunk),
57
+ };
58
+ });
59
+ }
60
+ export function formatFullReviewItem(r) {
61
+ return [
62
+ `- **\`${r.file}:${r.line}\`** (@${r.author}): ${r.comment}`,
63
+ ' ```diff',
64
+ ...r.diffHunk.split('\n').map((l) => ` ${l}`),
65
+ ' ```',
66
+ ].join('\n');
67
+ }
68
+ export function formatCompactReviewItem(r) {
69
+ return `- **\`${r.file}:${r.line}\`** (@${r.author}): ${r.comment}`;
70
+ }
71
+ export function renderReviewsWithinBudget(reviews, budgetTokens, full) {
72
+ if (reviews.length === 0) {
73
+ return {
74
+ markdown: '- None',
75
+ included: [],
76
+ truncatedCount: 0,
77
+ usedCompactMode: false,
78
+ };
79
+ }
80
+ const fullBlocks = reviews.map(formatFullReviewItem);
81
+ const fullMarkdown = fullBlocks.join('\n');
82
+ if (full || countTokens(fullMarkdown) <= budgetTokens) {
83
+ return {
84
+ markdown: fullMarkdown,
85
+ included: reviews,
86
+ truncatedCount: 0,
87
+ usedCompactMode: false,
88
+ };
89
+ }
90
+ // Overflow without --full: switch to compact 1-line-per-thread summaries
91
+ const footerReserve = countTokens(`\n[TRUNCATED: ${reviews.length} more unresolved threads — rerun with --full]`);
92
+ const compactLimit = Math.max(0, budgetTokens - footerReserve);
93
+ const lines = [];
94
+ const included = [];
95
+ let usedTokens = 0;
96
+ for (const review of reviews) {
97
+ const line = formatCompactReviewItem(review);
98
+ const lineTokens = countTokens((lines.length > 0 ? '\n' : '') + line);
99
+ if (usedTokens + lineTokens > compactLimit) {
100
+ break;
101
+ }
102
+ lines.push(line);
103
+ included.push(review);
104
+ usedTokens += lineTokens;
105
+ }
106
+ const truncatedCount = reviews.length - included.length;
107
+ if (truncatedCount > 0) {
108
+ lines.push(`[TRUNCATED: ${truncatedCount} more unresolved threads — rerun with --full]`);
109
+ }
110
+ return {
111
+ markdown: lines.join('\n'),
112
+ included,
113
+ truncatedCount,
114
+ usedCompactMode: true,
115
+ };
116
+ }
@@ -0,0 +1,2 @@
1
+ export declare function countTokens(text: string): number;
2
+ export declare function truncateToTokens(text: string, maxTokens: number, suffix?: string): string;
package/dist/tokens.js ADDED
@@ -0,0 +1,26 @@
1
+ import { getEncoding } from 'js-tiktoken';
2
+ let encoder = null;
3
+ function getEncoder() {
4
+ if (!encoder) {
5
+ encoder = getEncoding('o200k_base');
6
+ }
7
+ return encoder;
8
+ }
9
+ export function countTokens(text) {
10
+ if (!text)
11
+ return 0;
12
+ return getEncoder().encode(text).length;
13
+ }
14
+ export function truncateToTokens(text, maxTokens, suffix = '…') {
15
+ if (maxTokens <= 0)
16
+ return '';
17
+ const enc = getEncoder();
18
+ const tokens = enc.encode(text);
19
+ if (tokens.length <= maxTokens)
20
+ return text;
21
+ const suffixTokens = enc.encode(suffix).length;
22
+ const keep = Math.max(0, maxTokens - suffixTokens);
23
+ if (keep === 0)
24
+ return '';
25
+ return enc.decode(tokens.slice(0, keep)).trimEnd() + suffix;
26
+ }
@@ -0,0 +1,67 @@
1
+ export interface PRTarget {
2
+ owner: string;
3
+ repo: string;
4
+ number: number;
5
+ }
6
+ export interface PRMetadata extends PRTarget {
7
+ title: string;
8
+ branch: string;
9
+ headSha: string;
10
+ }
11
+ export interface FailingCheck {
12
+ jobName: string;
13
+ command?: string;
14
+ errorSummary: string;
15
+ stackTrace: string[];
16
+ referencedFiles: Array<{
17
+ file: string;
18
+ symbol?: string;
19
+ }>;
20
+ }
21
+ export interface RawReviewThread {
22
+ id: string;
23
+ isResolved: boolean;
24
+ isOutdated: boolean;
25
+ isCollapsed: boolean;
26
+ path: string;
27
+ line: number | null;
28
+ originalLine: number | null;
29
+ comments: {
30
+ nodes: Array<{
31
+ author: {
32
+ login: string;
33
+ } | null;
34
+ body: string;
35
+ diffHunk: string;
36
+ }>;
37
+ };
38
+ }
39
+ export interface UnresolvedReview {
40
+ file: string;
41
+ line: number;
42
+ author: string;
43
+ comment: string;
44
+ diffHunk: string;
45
+ symbol?: string;
46
+ }
47
+ export interface BlastRadiusTuple {
48
+ file: string;
49
+ symbol: string;
50
+ callers: string[];
51
+ tests: string[];
52
+ }
53
+ export interface CompileOptions {
54
+ budget: number;
55
+ full: boolean;
56
+ }
57
+ export interface TriageBrief {
58
+ pr: PRMetadata;
59
+ tokens: number;
60
+ budget: number;
61
+ failedChecksCount: number;
62
+ unresolvedThreadsCount: number;
63
+ truncatedThreadsCount: number;
64
+ failingChecks: FailingCheck[];
65
+ unresolvedReviews: UnresolvedReview[];
66
+ blastRadius: BlastRadiusTuple[];
67
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,30 @@
1
1
  {
2
2
  "name": "@kartiksomani/ais",
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": "Fast, deterministic, failure-first PR triage CLI that compiles a sub-1,000-token Markdown brief.",
5
+ "type": "module",
6
+ "bin": {
7
+ "ais": "./dist/cli.js"
8
+ },
9
+ "engines": {
10
+ "node": ">=20.0.0"
11
+ },
12
+ "scripts": {
13
+ "build": "tsc",
14
+ "test": "vitest run",
15
+ "test:watch": "vitest"
16
+ },
17
+ "dependencies": {
18
+ "commander": "^12.1.0",
19
+ "js-tiktoken": "^1.0.15"
20
+ },
21
+ "devDependencies": {
22
+ "@types/node": "^22.20.7",
23
+ "typescript": "^5.6.3",
24
+ "vitest": "^2.1.4"
25
+ },
26
+ "files": [
27
+ "dist",
28
+ "README.md"
29
+ ]
30
+ }