@agentic-sdlc-kit/cli 1.1.0 → 1.2.1

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 (67) hide show
  1. package/dist/application/agent/gateway.d.ts +15 -1
  2. package/dist/application/agent/gateway.d.ts.map +1 -1
  3. package/dist/application/agent/gateway.js +60 -4
  4. package/dist/application/agent/gateway.js.map +1 -1
  5. package/dist/application/dispatcher.d.ts.map +1 -1
  6. package/dist/application/dispatcher.js +3 -0
  7. package/dist/application/dispatcher.js.map +1 -1
  8. package/dist/application/improvement/capture.d.ts +25 -0
  9. package/dist/application/improvement/capture.d.ts.map +1 -0
  10. package/dist/application/improvement/capture.js +45 -0
  11. package/dist/application/improvement/capture.js.map +1 -0
  12. package/dist/application/improvement/github-api.d.ts +38 -0
  13. package/dist/application/improvement/github-api.d.ts.map +1 -0
  14. package/dist/application/improvement/github-api.js +132 -0
  15. package/dist/application/improvement/github-api.js.map +1 -0
  16. package/dist/application/improvement/github-context.d.ts +19 -0
  17. package/dist/application/improvement/github-context.d.ts.map +1 -0
  18. package/dist/application/improvement/github-context.js +39 -0
  19. package/dist/application/improvement/github-context.js.map +1 -0
  20. package/dist/application/improvement/scrub-terms.d.ts +12 -0
  21. package/dist/application/improvement/scrub-terms.d.ts.map +1 -0
  22. package/dist/application/improvement/scrub-terms.js +66 -0
  23. package/dist/application/improvement/scrub-terms.js.map +1 -0
  24. package/dist/application/improvement/upstream.d.ts +18 -0
  25. package/dist/application/improvement/upstream.d.ts.map +1 -0
  26. package/dist/application/improvement/upstream.js +32 -0
  27. package/dist/application/improvement/upstream.js.map +1 -0
  28. package/dist/commands/improve-kit.d.ts +10 -0
  29. package/dist/commands/improve-kit.d.ts.map +1 -0
  30. package/dist/commands/improve-kit.js +79 -0
  31. package/dist/commands/improve-kit.js.map +1 -0
  32. package/dist/commands/improve-project.d.ts +18 -0
  33. package/dist/commands/improve-project.d.ts.map +1 -0
  34. package/dist/commands/improve-project.js +133 -0
  35. package/dist/commands/improve-project.js.map +1 -0
  36. package/dist/commands/improve-review.d.ts +12 -0
  37. package/dist/commands/improve-review.d.ts.map +1 -0
  38. package/dist/commands/improve-review.js +56 -0
  39. package/dist/commands/improve-review.js.map +1 -0
  40. package/dist/commands/improve.d.ts +12 -0
  41. package/dist/commands/improve.d.ts.map +1 -0
  42. package/dist/commands/improve.js +185 -0
  43. package/dist/commands/improve.js.map +1 -0
  44. package/dist/index.js +19 -2
  45. package/dist/index.js.map +1 -1
  46. package/package.json +4 -4
  47. package/src/application/agent/gateway.test.ts +80 -3
  48. package/src/application/agent/gateway.ts +61 -4
  49. package/src/application/dispatcher.ts +2 -0
  50. package/src/application/improvement/capture.test.ts +80 -0
  51. package/src/application/improvement/capture.ts +72 -0
  52. package/src/application/improvement/github-api.test.ts +191 -0
  53. package/src/application/improvement/github-api.ts +214 -0
  54. package/src/application/improvement/github-context.test.ts +55 -0
  55. package/src/application/improvement/github-context.ts +67 -0
  56. package/src/application/improvement/scrub-terms.ts +76 -0
  57. package/src/application/improvement/upstream.test.ts +70 -0
  58. package/src/application/improvement/upstream.ts +43 -0
  59. package/src/commands/improve-kit.test.ts +126 -0
  60. package/src/commands/improve-kit.ts +93 -0
  61. package/src/commands/improve-project.test.ts +194 -0
  62. package/src/commands/improve-project.ts +192 -0
  63. package/src/commands/improve-review.test.ts +126 -0
  64. package/src/commands/improve-review.ts +75 -0
  65. package/src/commands/improve.test.ts +121 -0
  66. package/src/commands/improve.ts +215 -0
  67. package/src/index.ts +18 -2
@@ -0,0 +1,72 @@
1
+ // packages/cli/src/application/improvement/capture.ts
2
+ //
3
+ // Opt-in capture of kit failures as sanitized feedback (ADR-0028, "kit" target). Runs after a
4
+ // command fails. It records only when the user enabled kitFeedback.capture in
5
+ // .ai-kit/improvement.yml, writes only a sanitized record, sends nothing, never throws, and never
6
+ // changes the command's exit code.
7
+ import { improvement } from '@agentic-sdlc-kit/core';
8
+ import type { KitFeedback } from '@agentic-sdlc-kit/contracts';
9
+ import { VERSION } from '../version.js';
10
+ import { collectScrubTerms, defaultGit, type GitRunner } from './scrub-terms.js';
11
+
12
+ export interface FailureEvent {
13
+ readonly cwd: string;
14
+ readonly command: string;
15
+ readonly exitCode: number;
16
+ readonly failure: KitFeedback['failure'];
17
+ readonly message?: string;
18
+ /** The full argv, command first. Everything the user typed is scrubbed out. */
19
+ readonly argv?: ReadonlyArray<string>;
20
+ }
21
+
22
+ export interface CaptureDeps {
23
+ readonly git?: GitRunner;
24
+ readonly env?: NodeJS.ProcessEnv;
25
+ readonly kitVersion?: string;
26
+ }
27
+
28
+ /** The stored record, or undefined when capture is off, the input is unusable, or anything fails. */
29
+ export async function captureKitFailure(event: FailureEvent, deps: CaptureDeps = {}): Promise<KitFeedback | undefined> {
30
+ try {
31
+ const config = await improvement.loadImprovementConfig(event.cwd);
32
+ if (!config.ok || !config.value.kitFeedback.capture) return undefined;
33
+ const terms = await collectScrubTerms(event.cwd, deps.git ?? defaultGit, event.argv ?? []);
34
+ const feedback = improvement.buildKitFeedback(
35
+ {
36
+ kitVersion: deps.kitVersion ?? VERSION,
37
+ command: event.command,
38
+ failure: event.failure,
39
+ exitCode: event.exitCode,
40
+ ...(event.message !== undefined ? { message: event.message } : {}),
41
+ platform: process.platform,
42
+ nodeVersion: process.versions.node,
43
+ },
44
+ { terms },
45
+ );
46
+ return feedback ? await improvement.recordKitFeedback(event.cwd, feedback, deps.env) : undefined;
47
+ } catch {
48
+ return undefined;
49
+ }
50
+ }
51
+
52
+ /** Called by the entry point after dispatch. Only runtime failures of known commands qualify. */
53
+ export async function afterDispatch(
54
+ cwd: string,
55
+ argv: ReadonlyArray<string>,
56
+ result: { readonly exitCode: number; readonly command?: string; readonly message?: string },
57
+ isKnownCommand: (name: string) => boolean,
58
+ deps: CaptureDeps = {},
59
+ ): Promise<void> {
60
+ if (result.exitCode < 2 || !result.command || !isKnownCommand(result.command)) return;
61
+ await captureKitFailure(
62
+ {
63
+ cwd,
64
+ argv,
65
+ command: result.command,
66
+ exitCode: result.exitCode,
67
+ failure: 'runtime-error',
68
+ ...(result.message !== undefined ? { message: result.message } : {}),
69
+ },
70
+ deps,
71
+ );
72
+ }
@@ -0,0 +1,191 @@
1
+ import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
2
+ import type { AddressInfo } from 'node:net';
3
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
4
+ import { createGitHubApi, GitHubApiError, type GitHubApi } from './github-api.js';
5
+
6
+ interface Seen {
7
+ readonly method: string;
8
+ readonly url: string;
9
+ readonly auth: string | undefined;
10
+ readonly body: string;
11
+ }
12
+ type Reply = (req: Seen) => { status: number; json?: unknown; headers?: Record<string, string> };
13
+
14
+ let server: Server;
15
+ let seen: Seen[];
16
+ let replies: Reply[];
17
+ let api: GitHubApi;
18
+
19
+ const issue = (n: number, extra: Record<string, unknown> = {}): Record<string, unknown> => ({
20
+ number: n,
21
+ state: 'open',
22
+ title: `t${n}`,
23
+ body: `b${n}`,
24
+ html_url: `https://example.invalid/i/${n}`,
25
+ labels: [{ name: 'sdlc:discovered' }],
26
+ ...extra,
27
+ });
28
+
29
+ function handle(req: IncomingMessage, res: ServerResponse): void {
30
+ let body = '';
31
+ req.on('data', (c: Buffer) => (body += c.toString()));
32
+ req.on('end', () => {
33
+ const s: Seen = {
34
+ method: req.method ?? '',
35
+ url: req.url ?? '',
36
+ auth: req.headers.authorization,
37
+ body,
38
+ };
39
+ seen.push(s);
40
+ const reply = (replies.shift() ?? (() => ({ status: 500 })))(s);
41
+ res.writeHead(reply.status, { 'content-type': 'application/json', ...reply.headers });
42
+ res.end(reply.json === undefined ? '' : JSON.stringify(reply.json));
43
+ });
44
+ }
45
+
46
+ beforeEach(async () => {
47
+ seen = [];
48
+ replies = [];
49
+ server = createServer(handle);
50
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
51
+ const { port } = server.address() as AddressInfo;
52
+ api = createGitHubApi({
53
+ token: 'test-token',
54
+ repo: { owner: 'o', name: 'r' },
55
+ baseUrl: `http://127.0.0.1:${port}`,
56
+ });
57
+ });
58
+
59
+ afterEach(async () => {
60
+ await new Promise<void>((resolve) => server.close(() => resolve()));
61
+ });
62
+
63
+ describe('reads', () => {
64
+ it('lists issues by label across pages, drops pull requests, and authenticates', async () => {
65
+ const page1 = Array.from({ length: 100 }, (_, i) =>
66
+ i === 0 ? issue(1, { pull_request: {} }) : issue(i + 1),
67
+ );
68
+ replies.push(
69
+ () => ({ status: 200, json: page1 }),
70
+ () => ({ status: 200, json: [issue(101, { state: 'closed' })] }),
71
+ );
72
+ const issues = await api.listIssuesByLabel('sdlc:discovered');
73
+ expect(issues).toHaveLength(100);
74
+ expect(issues.at(-1)).toMatchObject({
75
+ number: 101,
76
+ state: 'closed',
77
+ labels: ['sdlc:discovered'],
78
+ });
79
+ expect(seen[0]?.url).toBe(
80
+ '/repos/o/r/issues?labels=sdlc%3Adiscovered&state=all&per_page=100&page=1',
81
+ );
82
+ expect(seen[1]?.url).toContain('page=2');
83
+ expect(seen[0]?.auth).toBe('Bearer test-token');
84
+ });
85
+
86
+ it('retries a read once after a server error', async () => {
87
+ replies.push(
88
+ () => ({ status: 502 }),
89
+ () => ({ status: 200, json: [issue(1)] }),
90
+ );
91
+ expect(await api.listIssuesByLabel('x')).toHaveLength(1);
92
+ expect(seen).toHaveLength(2);
93
+ });
94
+
95
+ it('gives up on a read after the second server error', async () => {
96
+ replies.push(
97
+ () => ({ status: 503 }),
98
+ () => ({ status: 503 }),
99
+ );
100
+ await expect(api.listIssuesByLabel('x')).rejects.toMatchObject({ status: 503 });
101
+ });
102
+
103
+ it('reads a collaborator permission, and a non-collaborator as none', async () => {
104
+ replies.push(
105
+ () => ({ status: 200, json: { permission: 'write' } }),
106
+ () => ({ status: 404, json: {} }),
107
+ );
108
+ expect(await api.permissionOf('alice')).toBe('write');
109
+ expect(await api.permissionOf('mallory')).toBe('none');
110
+ expect(seen[0]?.url).toBe('/repos/o/r/collaborators/alice/permission');
111
+ });
112
+ });
113
+
114
+ describe('repository', () => {
115
+ it("reads the repository's default branch", async () => {
116
+ replies.push(() => ({ status: 200, json: { default_branch: 'trunk' } }));
117
+ expect(await api.defaultBranch()).toBe('trunk');
118
+ expect(seen[0]?.url).toBe('/repos/o/r');
119
+ });
120
+ });
121
+
122
+ describe('writes', () => {
123
+ it('creates an issue with title, body and labels', async () => {
124
+ replies.push(() => ({ status: 201, json: issue(7) }));
125
+ const created = await api.createIssue({ title: 'T', body: 'B', labels: ['a', 'b'] });
126
+ expect(created).toMatchObject({ number: 7, url: 'https://example.invalid/i/7' });
127
+ expect(seen[0]?.method).toBe('POST');
128
+ expect(JSON.parse(seen[0]?.body ?? '')).toEqual({ title: 'T', body: 'B', labels: ['a', 'b'] });
129
+ });
130
+
131
+ it('updates only the body of an existing issue', async () => {
132
+ replies.push(() => ({ status: 200, json: issue(7) }));
133
+ await api.updateIssueBody(7, 'new body');
134
+ expect(seen[0]).toMatchObject({ method: 'PATCH', url: '/repos/o/r/issues/7' });
135
+ expect(JSON.parse(seen[0]?.body ?? '')).toEqual({ body: 'new body' });
136
+ });
137
+
138
+ it('never retries a write, even after a server error', async () => {
139
+ replies.push(
140
+ () => ({ status: 502 }),
141
+ () => ({ status: 201, json: issue(8) }),
142
+ );
143
+ await expect(api.createIssue({ title: 'T', body: 'B', labels: [] })).rejects.toBeInstanceOf(
144
+ GitHubApiError,
145
+ );
146
+ expect(seen).toHaveLength(1);
147
+ });
148
+
149
+ it('dispatches a workflow on a ref with string inputs', async () => {
150
+ replies.push(() => ({ status: 204 }));
151
+ await api.dispatchWorkflow('ai-review.yml', 'main', { pr_number: '5', kind: 'security' });
152
+ expect(seen[0]).toMatchObject({
153
+ method: 'POST',
154
+ url: '/repos/o/r/actions/workflows/ai-review.yml/dispatches',
155
+ });
156
+ expect(JSON.parse(seen[0]?.body ?? '')).toEqual({
157
+ ref: 'main',
158
+ inputs: { pr_number: '5', kind: 'security' },
159
+ });
160
+ });
161
+ });
162
+
163
+ describe('errors are explicit', () => {
164
+ it('names a rejected token on 401', async () => {
165
+ replies.push(() => ({ status: 401, json: { message: 'Bad credentials' } }));
166
+ await expect(api.listIssuesByLabel('x')).rejects.toThrow(/401.*token/i);
167
+ });
168
+
169
+ it('separates a rate limit from a missing permission on 403', async () => {
170
+ replies.push(() => ({ status: 403, headers: { 'x-ratelimit-remaining': '0' } }));
171
+ await expect(api.listIssuesByLabel('x')).rejects.toThrow(/rate limit/i);
172
+ replies.push(() => ({
173
+ status: 403,
174
+ json: { message: 'Resource not accessible by integration' },
175
+ }));
176
+ await expect(api.createIssue({ title: 'T', body: 'B', labels: [] })).rejects.toThrow(
177
+ /permission/i,
178
+ );
179
+ });
180
+
181
+ it('reports a refused connection without retrying a write', async () => {
182
+ const dead = createGitHubApi({
183
+ token: 't',
184
+ repo: { owner: 'o', name: 'r' },
185
+ baseUrl: 'http://127.0.0.1:1',
186
+ });
187
+ await expect(dead.createIssue({ title: 'T', body: 'B', labels: [] })).rejects.toThrow(
188
+ /network/i,
189
+ );
190
+ });
191
+ });
@@ -0,0 +1,214 @@
1
+ // packages/cli/src/application/improvement/github-api.ts
2
+ //
3
+ // Minimal GitHub REST adapter for `kit improve` (ADR-0028 P2.2): issues in the user's own
4
+ // repository, a collaborator's permission, and workflow dispatch. Uses Node's fetch, with no new
5
+ // dependency.
6
+ //
7
+ // Failure policy: a read is retried once after a 5xx or a network error. A write is never retried,
8
+ // because a write that timed out may still have happened; the next sync finds it by its key
9
+ // instead of filing it twice. Every failure is a GitHubApiError with a message a user can act on.
10
+
11
+ export interface GitHubRepo {
12
+ readonly owner: string;
13
+ readonly name: string;
14
+ }
15
+
16
+ export interface GitHubApiOptions {
17
+ readonly token: string;
18
+ readonly repo: GitHubRepo;
19
+ readonly baseUrl?: string;
20
+ readonly fetch?: typeof fetch;
21
+ readonly timeoutMs?: number;
22
+ }
23
+
24
+ export interface IssueSummary {
25
+ readonly number: number;
26
+ readonly state: 'open' | 'closed';
27
+ readonly title: string;
28
+ readonly body: string;
29
+ readonly url: string;
30
+ readonly labels: ReadonlyArray<string>;
31
+ }
32
+
33
+ export interface NewIssue {
34
+ readonly title: string;
35
+ readonly body: string;
36
+ readonly labels: ReadonlyArray<string>;
37
+ }
38
+
39
+ export interface GitHubApi {
40
+ listIssuesByLabel(label: string): Promise<IssueSummary[]>;
41
+ createIssue(issue: NewIssue): Promise<IssueSummary>;
42
+ updateIssueBody(issueNumber: number, body: string): Promise<IssueSummary>;
43
+ permissionOf(username: string): Promise<string>;
44
+ dispatchWorkflow(
45
+ file: string,
46
+ ref: string,
47
+ inputs: Readonly<Record<string, string>>,
48
+ ): Promise<void>;
49
+ defaultBranch(): Promise<string>;
50
+ }
51
+
52
+ export class GitHubApiError extends Error {
53
+ constructor(
54
+ readonly status: number,
55
+ message: string,
56
+ ) {
57
+ super(message);
58
+ this.name = 'GitHubApiError';
59
+ }
60
+ }
61
+
62
+ const MAX_PAGES = 20;
63
+
64
+ function explain(status: number, headers: Headers, what: string): string {
65
+ if (status === 401)
66
+ return `GitHub rejected the token (401) for ${what}. Check GITHUB_TOKEN or GH_TOKEN.`;
67
+ if (status === 403 && headers.get('x-ratelimit-remaining') === '0') {
68
+ return `GitHub rate limit reached (403) for ${what}. Try again after the limit resets.`;
69
+ }
70
+ if (status === 403)
71
+ return `GitHub refused ${what} (403): the token lacks the permission it needs.`;
72
+ if (status === 404)
73
+ return `GitHub could not find ${what} (404). Check the repository and the token's access.`;
74
+ if (status >= 500) return `GitHub server error (${status}) for ${what}.`;
75
+ return `GitHub returned ${status} for ${what}.`;
76
+ }
77
+
78
+ interface IssueJson {
79
+ number: number;
80
+ state: string;
81
+ title: string;
82
+ body: string | null;
83
+ html_url: string;
84
+ labels: Array<{ name: string } | string>;
85
+ pull_request?: unknown;
86
+ }
87
+
88
+ function toSummary(j: IssueJson): IssueSummary {
89
+ return {
90
+ number: j.number,
91
+ state: j.state === 'closed' ? 'closed' : 'open',
92
+ title: j.title,
93
+ body: j.body ?? '',
94
+ url: j.html_url,
95
+ labels: j.labels.map((l) => (typeof l === 'string' ? l : l.name)),
96
+ };
97
+ }
98
+
99
+ type Requester = (method: string, path: string, body?: unknown) => Promise<unknown>;
100
+
101
+ interface Transport {
102
+ readonly base: string;
103
+ readonly doFetch: typeof fetch;
104
+ readonly headers: Readonly<Record<string, string>>;
105
+ readonly timeoutMs: number;
106
+ }
107
+
108
+ function transportOf(opts: GitHubApiOptions): Transport {
109
+ const headers = {
110
+ authorization: `Bearer ${opts.token}`,
111
+ accept: 'application/vnd.github+json',
112
+ 'x-github-api-version': '2022-11-28',
113
+ 'user-agent': 'agentic-sdlc-kit',
114
+ 'content-type': 'application/json',
115
+ };
116
+ const base = (opts.baseUrl ?? 'https://api.github.com').replace(/\/$/, '');
117
+ return { base, doFetch: opts.fetch ?? fetch, headers, timeoutMs: opts.timeoutMs ?? 30_000 };
118
+ }
119
+
120
+ async function sendOnce(
121
+ t: Transport,
122
+ method: string,
123
+ path: string,
124
+ body?: unknown,
125
+ ): Promise<unknown> {
126
+ const init: RequestInit = {
127
+ method,
128
+ headers: t.headers,
129
+ signal: AbortSignal.timeout(t.timeoutMs),
130
+ };
131
+ if (body !== undefined) init.body = JSON.stringify(body);
132
+ let res: Response;
133
+ try {
134
+ res = await t.doFetch(`${t.base}${path}`, init);
135
+ } catch (err) {
136
+ throw new GitHubApiError(0, `network error for ${method} ${path}: ${(err as Error).message}`);
137
+ }
138
+ if (!res.ok)
139
+ throw new GitHubApiError(res.status, explain(res.status, res.headers, `${method} ${path}`));
140
+ const text = await res.text();
141
+ return text.length > 0 ? JSON.parse(text) : undefined;
142
+ }
143
+
144
+ const retryable = (err: unknown): boolean =>
145
+ err instanceof GitHubApiError && (err.status === 0 || err.status >= 500);
146
+
147
+ function requester(opts: GitHubApiOptions): Requester {
148
+ const t = transportOf(opts);
149
+ return async (method, path, body) => {
150
+ if (method !== 'GET') return sendOnce(t, method, path, body);
151
+ try {
152
+ return await sendOnce(t, method, path);
153
+ } catch (err) {
154
+ if (retryable(err)) return sendOnce(t, method, path);
155
+ throw err;
156
+ }
157
+ };
158
+ }
159
+
160
+ async function listByLabel(
161
+ req: Requester,
162
+ repoPath: string,
163
+ label: string,
164
+ ): Promise<IssueSummary[]> {
165
+ const out: IssueSummary[] = [];
166
+ for (let page = 1; page <= MAX_PAGES; page++) {
167
+ const q = `labels=${encodeURIComponent(label)}&state=all&per_page=100&page=${page}`;
168
+ const items = (await req('GET', `${repoPath}/issues?${q}`)) as IssueJson[];
169
+ out.push(...items.filter((i) => i.pull_request === undefined).map(toSummary));
170
+ if (items.length < 100) break;
171
+ }
172
+ return out;
173
+ }
174
+
175
+ async function permission(req: Requester, repoPath: string, user: string): Promise<string> {
176
+ try {
177
+ const res = (await req(
178
+ 'GET',
179
+ `${repoPath}/collaborators/${encodeURIComponent(user)}/permission`,
180
+ )) as {
181
+ permission?: string;
182
+ };
183
+ return res.permission ?? 'none';
184
+ } catch (err) {
185
+ if (err instanceof GitHubApiError && err.status === 404) return 'none';
186
+ throw err;
187
+ }
188
+ }
189
+
190
+ export function createGitHubApi(opts: GitHubApiOptions): GitHubApi {
191
+ const req = requester(opts);
192
+ const repoPath = `/repos/${encodeURIComponent(opts.repo.owner)}/${encodeURIComponent(opts.repo.name)}`;
193
+ return {
194
+ listIssuesByLabel: (label) => listByLabel(req, repoPath, label),
195
+ createIssue: async (issue) =>
196
+ toSummary(
197
+ (await req('POST', `${repoPath}/issues`, {
198
+ ...issue,
199
+ labels: [...issue.labels],
200
+ })) as IssueJson,
201
+ ),
202
+ updateIssueBody: async (n, body) =>
203
+ toSummary((await req('PATCH', `${repoPath}/issues/${n}`, { body })) as IssueJson),
204
+ permissionOf: (user) => permission(req, repoPath, user),
205
+ dispatchWorkflow: async (file, ref, inputs) => {
206
+ await req('POST', `${repoPath}/actions/workflows/${encodeURIComponent(file)}/dispatches`, {
207
+ ref,
208
+ inputs,
209
+ });
210
+ },
211
+ defaultBranch: async () =>
212
+ ((await req('GET', repoPath)) as { default_branch: string }).default_branch,
213
+ };
214
+ }
@@ -0,0 +1,55 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { parseRepo, resolveRepo, resolveToken } from './github-context.js';
3
+ import type { GhRunner } from './upstream.js';
4
+
5
+ const noGit = async (): Promise<string | undefined> => undefined;
6
+ const gitRemote = (url: string) => async (): Promise<string | undefined> => url;
7
+ const gh =
8
+ (code: number, stdout: string): GhRunner =>
9
+ async () => ({ code, stdout, stderr: '' });
10
+
11
+ describe('resolveRepo', () => {
12
+ it('prefers --repo, then GITHUB_REPOSITORY, then the origin remote', async () => {
13
+ const env = { GITHUB_REPOSITORY: 'env-owner/env-repo' };
14
+ expect(await resolveRepo('/w', 'flag-owner/flag-repo', env, noGit)).toEqual({
15
+ owner: 'flag-owner',
16
+ name: 'flag-repo',
17
+ });
18
+ expect(await resolveRepo('/w', undefined, env, noGit)).toEqual({
19
+ owner: 'env-owner',
20
+ name: 'env-repo',
21
+ });
22
+ expect(
23
+ await resolveRepo('/w', undefined, {}, gitRemote('git@github.com:acme/app.git')),
24
+ ).toEqual({ owner: 'acme', name: 'app' });
25
+ expect(
26
+ await resolveRepo('/w', undefined, {}, gitRemote('https://github.com/acme/app')),
27
+ ).toEqual({ owner: 'acme', name: 'app' });
28
+ });
29
+
30
+ it('explains a malformed or missing repository instead of guessing', async () => {
31
+ expect(await resolveRepo('/w', 'not a slug', {}, noGit)).toMatch(/--repo must be owner\/name/);
32
+ expect(await resolveRepo('/w', undefined, {}, noGit)).toMatch(/pass --repo/);
33
+ });
34
+
35
+ it('parses only owner/name', () => {
36
+ expect(parseRepo('a/b')).toEqual({ owner: 'a', name: 'b' });
37
+ expect(parseRepo('a/b/c')).toBeUndefined();
38
+ expect(parseRepo('a b/c')).toBeUndefined();
39
+ });
40
+ });
41
+
42
+ describe('resolveToken', () => {
43
+ it('prefers GITHUB_TOKEN, then GH_TOKEN, then gh auth token', async () => {
44
+ expect(await resolveToken({ GITHUB_TOKEN: 'one', GH_TOKEN: 'two' }, gh(0, 'three'))).toBe(
45
+ 'one',
46
+ );
47
+ expect(await resolveToken({ GH_TOKEN: 'two' }, gh(0, 'three'))).toBe('two');
48
+ expect(await resolveToken({}, gh(0, 'three\n'))).toBe('three');
49
+ });
50
+
51
+ it('returns undefined when gh is missing or logged out', async () => {
52
+ expect(await resolveToken({}, gh(127, ''))).toBeUndefined();
53
+ expect(await resolveToken({}, gh(1, ''))).toBeUndefined();
54
+ });
55
+ });
@@ -0,0 +1,67 @@
1
+ // packages/cli/src/application/improvement/github-context.ts
2
+ //
3
+ // Which repository and which token `kit improve` uses for its own-repository writes (ADR-0028 P2).
4
+ // Repository: --repo, then GITHUB_REPOSITORY (set in Actions), then the `origin` remote.
5
+ // Token: GITHUB_TOKEN, then GH_TOKEN, then the user's own `gh auth token`. Nothing is cached.
6
+ import type { GitHubApi, GitHubApiOptions, GitHubRepo } from './github-api.js';
7
+ import { defaultGit, remoteParts, type GitRunner } from './scrub-terms.js';
8
+ import { defaultGh, type GhRunner } from './upstream.js';
9
+
10
+ const SLUG = /^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/;
11
+
12
+ export function parseRepo(slug: string): GitHubRepo | undefined {
13
+ const m = SLUG.exec(slug.trim());
14
+ return m?.[1] && m[2] ? { owner: m[1], name: m[2] } : undefined;
15
+ }
16
+
17
+ /** The target repository, or an error message saying how to name one. */
18
+ export async function resolveRepo(
19
+ cwd: string,
20
+ flag: string | undefined,
21
+ env: NodeJS.ProcessEnv = process.env,
22
+ git: GitRunner = defaultGit,
23
+ ): Promise<GitHubRepo | string> {
24
+ if (flag !== undefined) return parseRepo(flag) ?? `--repo must be owner/name, got "${flag}"`;
25
+ const fromEnv = env.GITHUB_REPOSITORY?.trim();
26
+ if (fromEnv)
27
+ return parseRepo(fromEnv) ?? `GITHUB_REPOSITORY must be owner/name, got "${fromEnv}"`;
28
+ const remote = await git(cwd, ['remote', 'get-url', 'origin']);
29
+ const slug = remote === undefined ? undefined : remoteParts(remote)[2];
30
+ const repo = slug === undefined ? undefined : parseRepo(slug);
31
+ return repo ?? 'cannot tell which repository to use: pass --repo owner/name';
32
+ }
33
+
34
+ /** A token, or undefined when none is available. */
35
+ export async function resolveToken(
36
+ env: NodeJS.ProcessEnv = process.env,
37
+ gh: GhRunner = defaultGh,
38
+ ): Promise<string | undefined> {
39
+ const fromEnv = env.GITHUB_TOKEN?.trim() || env.GH_TOKEN?.trim();
40
+ if (fromEnv) return fromEnv;
41
+ const r = await gh(['auth', 'token']);
42
+ const token = r.code === 0 ? r.stdout.trim() : '';
43
+ return token.length > 0 ? token : undefined;
44
+ }
45
+
46
+ export interface GitHubConnection {
47
+ readonly api: GitHubApi;
48
+ readonly slug: string;
49
+ }
50
+
51
+ /** A client for the resolved repository, or an error message saying what is missing. */
52
+ export async function connectGitHub(
53
+ cwd: string,
54
+ repoFlag: string | undefined,
55
+ deps: {
56
+ readonly env: NodeJS.ProcessEnv;
57
+ readonly gh: GhRunner;
58
+ readonly github: (opts: GitHubApiOptions) => GitHubApi;
59
+ },
60
+ ): Promise<GitHubConnection | string> {
61
+ const repo = await resolveRepo(cwd, repoFlag, deps.env);
62
+ if (typeof repo === 'string') return repo;
63
+ const token = await resolveToken(deps.env, deps.gh);
64
+ if (token === undefined)
65
+ return 'no GitHub token: set GITHUB_TOKEN or GH_TOKEN, or log in with gh';
66
+ return { api: deps.github({ token, repo }), slug: `${repo.owner}/${repo.name}` };
67
+ }
@@ -0,0 +1,76 @@
1
+ // packages/cli/src/application/improvement/scrub-terms.ts
2
+ //
3
+ // The literal terms that identify this installation: project path and folder name, home directory,
4
+ // OS user and host names, git remote owner and repository, branch, and the git author's name and
5
+ // email. They are inputs to the scrubber (ADR-0028, "kit" target) and are never written anywhere.
6
+ import { execFile } from 'node:child_process';
7
+ import os from 'node:os';
8
+ import path from 'node:path';
9
+ import { promisify } from 'node:util';
10
+
11
+ export type GitRunner = (cwd: string, args: string[]) => Promise<string | undefined>;
12
+
13
+ const run = promisify(execFile);
14
+
15
+ /** `git <args>` in `cwd`; undefined on any failure, so a missing git never blocks scrubbing. */
16
+ export const defaultGit: GitRunner = async (cwd, args) => {
17
+ try {
18
+ const { stdout } = await run('git', ['-C', cwd, ...args], { timeout: 2000 });
19
+ const out = stdout.trim();
20
+ return out.length > 0 ? out : undefined;
21
+ } catch {
22
+ return undefined;
23
+ }
24
+ };
25
+
26
+ /** Owner and repository from an https or ssh remote URL. */
27
+ export function remoteParts(url: string): string[] {
28
+ const m = /[:/]([^/:]+)\/([^/]+?)(?:\.git)?\/?$/.exec(url.trim());
29
+ return m?.[1] && m[2] ? [m[1], m[2], `${m[1]}/${m[2]}`] : [];
30
+ }
31
+
32
+ function safe(read: () => string): string | undefined {
33
+ try {
34
+ return read();
35
+ } catch {
36
+ return undefined;
37
+ }
38
+ }
39
+
40
+ async function gitTerms(cwd: string, git: GitRunner): Promise<string[]> {
41
+ const [remote, branch, name, email] = await Promise.all([
42
+ git(cwd, ['remote', 'get-url', 'origin']),
43
+ git(cwd, ['rev-parse', '--abbrev-ref', 'HEAD']),
44
+ git(cwd, ['config', 'user.name']),
45
+ git(cwd, ['config', 'user.email']),
46
+ ]);
47
+ const branchParts = branch && branch !== 'HEAD' ? [branch, ...branch.split('/')] : [];
48
+ return [...(remote ? remoteParts(remote) : []), ...branchParts, name, email].filter((t): t is string => !!t);
49
+ }
50
+
51
+ /**
52
+ * Everything the user typed after the command name (paths, refs, globs, names), including
53
+ * `--flag=value` values and their path segments. Echoed arguments must never reach a report.
54
+ */
55
+ export function userSuppliedTerms(argv: ReadonlyArray<string>): string[] {
56
+ return argv.slice(1).flatMap((arg) => {
57
+ const value = arg.startsWith('-') ? (arg.includes('=') ? arg.slice(arg.indexOf('=') + 1) : '') : arg;
58
+ return value ? [value, ...value.split(/[\\/,]/)] : [];
59
+ });
60
+ }
61
+
62
+ export async function collectScrubTerms(
63
+ cwd: string,
64
+ git: GitRunner = defaultGit,
65
+ argv: ReadonlyArray<string> = [],
66
+ ): Promise<string[]> {
67
+ const local = [
68
+ cwd,
69
+ path.basename(cwd),
70
+ safe(() => os.homedir()),
71
+ safe(() => os.userInfo().username),
72
+ safe(() => os.hostname()),
73
+ ];
74
+ const all = [...local, ...userSuppliedTerms(argv), ...(await gitTerms(cwd, git))];
75
+ return [...new Set(all.filter((t): t is string => typeof t === 'string' && t.length > 0))];
76
+ }