changeguard 0.0.0-stage → 0.7.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 (69) hide show
  1. package/CHANGELOG.md +440 -0
  2. package/LICENSE +202 -0
  3. package/LICENSE-PROPRIETARY +94 -0
  4. package/README.md +317 -2
  5. package/SECURITY.md +40 -0
  6. package/data/changes/openai.seed.json +87 -0
  7. package/data/changes/shopify.seed.json +42 -0
  8. package/data/changes/stripe.seed.json +60 -0
  9. package/data/changes/supabase.seed.json +56 -0
  10. package/data/changes/twilio.seed.json +63 -0
  11. package/data/openapi/openai/meta.json +9 -0
  12. package/data/openapi/openai/new.json +24 -0
  13. package/data/openapi/openai/old.json +68 -0
  14. package/data/providers/openai.json +60 -0
  15. package/data/providers/shopify.json +52 -0
  16. package/data/providers/stripe.json +57 -0
  17. package/data/providers/supabase.json +56 -0
  18. package/data/providers/twilio.json +57 -0
  19. package/dist/analyze/go-analyzer.js +343 -0
  20. package/dist/analyze/index.js +77 -0
  21. package/dist/analyze/js-analyzer.js +380 -0
  22. package/dist/analyze/parser.js +78 -0
  23. package/dist/analyze/py-analyzer.js +313 -0
  24. package/dist/analyze/rules.js +1 -0
  25. package/dist/analyze/ts-utils.js +62 -0
  26. package/dist/cli.js +335 -0
  27. package/dist/codemod/apply.js +159 -0
  28. package/dist/config.js +121 -0
  29. package/dist/deps/manifests.js +145 -0
  30. package/dist/github/api.js +136 -0
  31. package/dist/github/auth.js +54 -0
  32. package/dist/impact/engine.js +384 -0
  33. package/dist/ingest/canonical.js +52 -0
  34. package/dist/ingest/changelog-html.js +63 -0
  35. package/dist/ingest/feed-client.js +99 -0
  36. package/dist/ingest/feed-keys.js +198 -0
  37. package/dist/ingest/feed.js +178 -0
  38. package/dist/ingest/github-releases.js +59 -0
  39. package/dist/ingest/note-parser.js +274 -0
  40. package/dist/ingest/openapi-diff.js +217 -0
  41. package/dist/ingest/store.js +181 -0
  42. package/dist/llm/explanation.js +273 -0
  43. package/dist/mcp/format.js +116 -0
  44. package/dist/mcp/index.js +29 -0
  45. package/dist/mcp/protocol.js +36 -0
  46. package/dist/mcp/server.js +110 -0
  47. package/dist/mcp/standalone.js +12 -0
  48. package/dist/mcp/tools.js +189 -0
  49. package/dist/notify/index.js +174 -0
  50. package/dist/providers/registry.js +215 -0
  51. package/dist/report/html.js +194 -0
  52. package/dist/report/markdown.js +90 -0
  53. package/dist/report/pr-draft.js +37 -0
  54. package/dist/scan.js +168 -0
  55. package/dist/source/repo-source.js +100 -0
  56. package/dist/types.js +6 -0
  57. package/dist/util/http.js +40 -0
  58. package/dist/util/logger.js +61 -0
  59. package/dist/util/metrics.js +99 -0
  60. package/dist/util/request-context.js +22 -0
  61. package/dist/util/task-queue.js +69 -0
  62. package/dist/util/versions.js +52 -0
  63. package/fixtures/sample-repo/cmd/billing/main.go +47 -0
  64. package/fixtures/sample-repo/go.mod +12 -0
  65. package/fixtures/sample-repo/package.json +17 -0
  66. package/fixtures/sample-repo/requirements.txt +7 -0
  67. package/fixtures/sample-repo/services/ai.py +65 -0
  68. package/fixtures/sample-repo/src/billing.ts +68 -0
  69. package/package.json +84 -4
@@ -0,0 +1,145 @@
1
+ import { concreteFromSpec } from '../util/versions.js';
2
+ function dep(ecosystem, name, spec, manifest, dev, line, indirect = false) {
3
+ return {
4
+ ecosystem,
5
+ name,
6
+ spec,
7
+ version: concreteFromSpec(spec),
8
+ dev,
9
+ indirect,
10
+ manifest,
11
+ line,
12
+ };
13
+ }
14
+ export function parsePackageJson(content, manifest) {
15
+ const out = [];
16
+ let json;
17
+ try {
18
+ json = JSON.parse(content);
19
+ }
20
+ catch {
21
+ return out;
22
+ }
23
+ const buckets = [
24
+ ['dependencies', false],
25
+ ['optionalDependencies', false],
26
+ ['peerDependencies', false],
27
+ ['devDependencies', true],
28
+ ];
29
+ for (const [bucket, isDev] of buckets) {
30
+ const obj = json[bucket];
31
+ if (!obj || typeof obj !== 'object')
32
+ continue;
33
+ for (const [name, spec] of Object.entries(obj)) {
34
+ if (typeof spec !== 'string')
35
+ continue;
36
+ // link/workspace specs carry no upstream version signal.
37
+ if (/^(file:|link:|workspace:|git\+?|http)/.test(spec) && !/\d/.test(spec))
38
+ continue;
39
+ out.push(dep('npm', name, spec, manifest, isDev));
40
+ }
41
+ }
42
+ return out;
43
+ }
44
+ export function parseRequirementsTxt(content, manifest) {
45
+ const out = [];
46
+ const lines = content.split(/\r?\n/);
47
+ lines.forEach((rawLine, idx) => {
48
+ let line = rawLine.trim();
49
+ if (!line || line.startsWith('#'))
50
+ return;
51
+ // strip inline comments
52
+ line = line.replace(/\s+#.*$/, '');
53
+ // skip includes/options/URLs without egg name
54
+ if (line.startsWith('-'))
55
+ return;
56
+ let name;
57
+ let spec;
58
+ const egg = line.match(/[?&#]egg=([A-Za-z0-9._-]+)/);
59
+ if (!egg && /:\/\/|^git\+/.test(line))
60
+ return; // direct URL without package name
61
+ if (egg) {
62
+ name = egg[1];
63
+ }
64
+ else {
65
+ const m = line.match(/^([A-Za-z0-9._-]+)(\s*\[[^\]]+\])?\s*(.*)$/);
66
+ if (!m)
67
+ return;
68
+ name = m[1];
69
+ spec = m[3]?.trim() || undefined;
70
+ }
71
+ out.push(dep('pypi', normalizePyName(name), spec, manifest, false, idx + 1));
72
+ });
73
+ return out;
74
+ }
75
+ export function normalizePyName(name) {
76
+ return name.toLowerCase().replace(/[-_.]+/g, '-');
77
+ }
78
+ export function parseGoMod(content, manifest) {
79
+ const out = [];
80
+ const lines = content.split(/\r?\n/);
81
+ let inBlock = false;
82
+ lines.forEach((rawLine, idx) => {
83
+ const line = rawLine.trim();
84
+ if (line.startsWith('require (')) {
85
+ inBlock = true;
86
+ return;
87
+ }
88
+ if (inBlock && line === ')') {
89
+ inBlock = false;
90
+ return;
91
+ }
92
+ const single = !inBlock ? line.match(/^require\s+(\S+)\s+(\S+)(.*)$/) : undefined;
93
+ const m = inBlock ? line.match(/^(\S+)\s+(\S+)(.*)$/) : single;
94
+ if (!m || !m[1] || !m[2])
95
+ return;
96
+ const indirect = /\/\/\s*indirect/.test(m[3] ?? '');
97
+ out.push(dep('go', m[1], m[2], manifest, false, idx + 1, indirect));
98
+ });
99
+ return out;
100
+ }
101
+ export async function collectManifests(source) {
102
+ const files = await source.listFiles();
103
+ const result = [];
104
+ for (const path of files) {
105
+ const base = path.split('/').pop() ?? '';
106
+ let ecosystem;
107
+ if (base === 'package.json')
108
+ ecosystem = 'npm';
109
+ else if (base === 'go.mod')
110
+ ecosystem = 'go';
111
+ else if (/^requirements[\w.-]*\.txt$/.test(base) || base === 'pyproject.toml') {
112
+ if (base === 'pyproject.toml')
113
+ continue; // poetry/PEP621 parsing is on the roadmap
114
+ ecosystem = 'pypi';
115
+ }
116
+ if (!ecosystem)
117
+ continue;
118
+ const content = await source.readText(path);
119
+ if (typeof content !== 'string')
120
+ continue;
121
+ result.push({ path, ecosystem, content });
122
+ }
123
+ return result;
124
+ }
125
+ export async function collectDependencies(source) {
126
+ const manifests = await collectManifests(source);
127
+ const all = [];
128
+ for (const m of manifests) {
129
+ if (m.ecosystem === 'npm')
130
+ all.push(...parsePackageJson(m.content, m.path));
131
+ else if (m.ecosystem === 'pypi')
132
+ all.push(...parseRequirementsTxt(m.content, m.path));
133
+ else
134
+ all.push(...parseGoMod(m.content, m.path));
135
+ }
136
+ // de-dupe identical (ecosystem,name) pins, keeping the first (highest manifest)
137
+ const seen = new Set();
138
+ return all.filter((d) => {
139
+ const key = `${d.ecosystem}:${d.name}`;
140
+ if (seen.has(key))
141
+ return false;
142
+ seen.add(key);
143
+ return true;
144
+ });
145
+ }
@@ -0,0 +1,136 @@
1
+ /**
2
+ * GitHub REST/Git Data API client: read a repository tree into a
3
+ * VirtualRepoSource, open draft PRs from engine codemods, and file issues.
4
+ */
5
+ import { fetchJson } from '../util/http.js';
6
+ import { VirtualRepoSource } from '../source/repo-source.js';
7
+ import { resolveToken } from './auth.js';
8
+ const API = 'https://api.github.com';
9
+ export class GitHubClient {
10
+ token;
11
+ constructor(token) {
12
+ this.token = token;
13
+ }
14
+ static async forInstallation(installationId) {
15
+ return new GitHubClient(await resolveToken(installationId));
16
+ }
17
+ headers() {
18
+ return {
19
+ authorization: `Bearer ${this.token}`,
20
+ accept: 'application/vnd.github+json',
21
+ 'x-github-api-version': '2022-11-28',
22
+ };
23
+ }
24
+ async get(path) {
25
+ return fetchJson(`${API}${path}`, { headers: this.headers() });
26
+ }
27
+ async post(path, body) {
28
+ return fetchJson(`${API}${path}`, {
29
+ method: 'POST',
30
+ body: JSON.stringify(body),
31
+ headers: this.headers(),
32
+ });
33
+ }
34
+ /** Read the whole tracked tree (default branch) as an in-memory source. */
35
+ async fetchRepoSource(owner, repo, ref) {
36
+ const target = ref
37
+ ? encodeURIComponent(ref)
38
+ : (await this.get(`/repos/${owner}/${repo}`)).default_branch;
39
+ const tree = await this.get(`/repos/${owner}/${repo}/git/trees/${encodeURIComponent(target)}?recursive=1`);
40
+ if (tree.truncated) {
41
+ // Deterministic limitation surfaced instead of silently missing files.
42
+ throw new Error(`repository tree truncated by GitHub for ${owner}/${repo}; repo too large`);
43
+ }
44
+ const source = new VirtualRepoSource(`${owner}/${repo}@${target}`, new Map());
45
+ const SKIP = /^(?:node_modules|vendor|\.changeguard|dist|build|out|coverage)\//;
46
+ const SOURCE_EXT = /\.(?:[cm]?[jt]sx?|py|go|json|txt|mod|toml|ya?ml|yaml)$/;
47
+ const blobs = tree.tree.filter((e) => e.type === 'blob' &&
48
+ !SKIP.test(e.path) &&
49
+ SOURCE_EXT.test(e.path) &&
50
+ (e.size ?? 0) < 500_000);
51
+ for (const entry of blobs) {
52
+ const blob = await this.get(`/repos/${owner}/${repo}/git/blobs/${entry.sha}`);
53
+ if (blob.encoding !== 'base64')
54
+ continue;
55
+ source.put(entry.path, Buffer.from(blob.content, 'base64').toString('utf8'));
56
+ }
57
+ return source;
58
+ }
59
+ /**
60
+ * Create a branch, commit codemod patches, and open a DRAFT pull request.
61
+ * All changes come from deterministic engine codemods only.
62
+ */
63
+ async openDraftPr(owner, repo, opts) {
64
+ const source = await this.fetchRepoSource(owner, repo, opts.base);
65
+ const changed = [];
66
+ for (const patch of opts.patches) {
67
+ const original = source.readText(patch.file);
68
+ if (original === undefined)
69
+ continue;
70
+ // Re-run the same deterministic transforms the FilePatch recorded.
71
+ const reapplied = applyCodemodsToContent(original, patch);
72
+ if (reapplied && reapplied !== original)
73
+ changed.push({ path: patch.file, content: reapplied });
74
+ }
75
+ if (changed.length === 0)
76
+ throw new Error('codemod patches produced no changes on remote');
77
+ const baseRef = await this.get(`/repos/${owner}/${repo}/git/ref/heads/${encodeURIComponent(opts.base)}`);
78
+ const baseSha = baseRef.object.sha;
79
+ const baseTree = await this.get(`/repos/${owner}/${repo}/git/commits/${baseSha}`);
80
+ const treeItems = await Promise.all(changed.map(async (c) => {
81
+ const blob = await this.post(`/repos/${owner}/${repo}/git/blobs`, {
82
+ content: c.content,
83
+ encoding: 'utf-8',
84
+ });
85
+ return { path: c.path, mode: '100644', type: 'blob', sha: blob.sha };
86
+ }));
87
+ const tree = await this.post(`/repos/${owner}/${repo}/git/trees`, {
88
+ base_tree: baseTree.tree.sha,
89
+ tree: treeItems,
90
+ });
91
+ const commit = await this.post(`/repos/${owner}/${repo}/git/commits`, {
92
+ message: `chore(changeguard): apply breaking API renames
93
+
94
+ ChangeGuard deterministic codemods for ${changed.length} file(s).
95
+ Draft - requires human review for semantic changes.`,
96
+ tree: tree.sha,
97
+ parents: [baseSha],
98
+ });
99
+ try {
100
+ await this.post(`/repos/${owner}/${repo}/git/refs`, {
101
+ ref: `refs/heads/${opts.head}`,
102
+ sha: commit.sha,
103
+ });
104
+ }
105
+ catch (err) {
106
+ throw new Error(`failed to create branch ${opts.head} (it may already exist): ${err.message}`, { cause: err });
107
+ }
108
+ return this.post(`/repos/${owner}/${repo}/pulls`, {
109
+ title: opts.title,
110
+ head: opts.head,
111
+ base: opts.base,
112
+ body: opts.body,
113
+ draft: true,
114
+ });
115
+ }
116
+ async createIssue(owner, repo, issue) {
117
+ return this.post(`/repos/${owner}/${repo}/issues`, issue);
118
+ }
119
+ }
120
+ /** Rebuild patched content deterministically: the FilePatch only carries a diff. */
121
+ function applyCodemodsToContent(original, patch) {
122
+ let content = original;
123
+ for (const a of patch.applied) {
124
+ if (a.kind === 'rename-method') {
125
+ content = content.replace(new RegExp(`\\.${escapeRe(a.from)}(?=\\s*[(<])`, 'g'), `.${a.to}`);
126
+ }
127
+ else if (a.kind === 'rename-parameter') {
128
+ const sep = a.language === 'python' ? '=' : ':';
129
+ content = content.replace(new RegExp(`\\b${escapeRe(a.from)}(?=\\s*${sep})`, 'g'), a.to);
130
+ }
131
+ }
132
+ return content === original ? undefined : content;
133
+ }
134
+ function escapeRe(s) {
135
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
136
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * GitHub App authentication without third-party JWT libraries.
3
+ * RS256 app JWTs are signed with node:crypto, then exchanged for
4
+ * installation access tokens (cached until 5 minutes before expiry).
5
+ */
6
+ import { createSign } from 'node:crypto';
7
+ import { fetchJson } from '../util/http.js';
8
+ import { config } from '../config.js';
9
+ function base64url(input) {
10
+ return Buffer.from(input).toString('base64url');
11
+ }
12
+ export function createAppJwt(now = Math.floor(Date.now() / 1000)) {
13
+ const appId = config.github.appId;
14
+ const key = config.github.privateKey;
15
+ if (!appId || !key) {
16
+ throw new Error('GITHUB_APP_ID and GITHUB_PRIVATE_KEY are required for GitHub App auth');
17
+ }
18
+ const header = base64url(JSON.stringify({ alg: 'RS256', typ: 'JWT' }));
19
+ const payload = base64url(JSON.stringify({ iat: now - 60, exp: now + 9 * 60, iss: appId }));
20
+ const signer = createSign('RSA-SHA256');
21
+ signer.update(`${header}.${payload}`);
22
+ signer.end();
23
+ const signature = signer.sign(key).toString('base64url');
24
+ return `${header}.${payload}.${signature}`;
25
+ }
26
+ const tokenCache = new Map();
27
+ export async function getInstallationToken(installationId) {
28
+ const cached = tokenCache.get(installationId);
29
+ if (cached && cached.expiresAt - 5 * 60_000 > Date.now())
30
+ return cached.token;
31
+ const jwt = createAppJwt();
32
+ const res = await fetchJson(`https://api.github.com/app/installations/${installationId}/access_tokens`, {
33
+ method: 'POST',
34
+ body: '',
35
+ headers: {
36
+ authorization: `Bearer ${jwt}`,
37
+ accept: 'application/vnd.github+json',
38
+ 'x-github-api-version': '2022-11-28',
39
+ },
40
+ });
41
+ tokenCache.set(installationId, {
42
+ token: res.token,
43
+ expiresAt: Date.parse(res.expires_at),
44
+ });
45
+ return res.token;
46
+ }
47
+ /** Use a plain GITHUB_TOKEN when configured, otherwise App installation flow. */
48
+ export async function resolveToken(installationId) {
49
+ if (config.github.token)
50
+ return config.github.token;
51
+ if (installationId !== undefined)
52
+ return getInstallationToken(installationId);
53
+ throw new Error('No GitHub credentials: set GITHUB_TOKEN or GITHUB_APP_ID/GITHUB_PRIVATE_KEY');
54
+ }