@infosupport/huddle-cli 0.0.0-experiment-167.144.1 → 0.0.0-experiment-137.146.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.
@@ -0,0 +1,373 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.runTriageAgent = runTriageAgent;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const api_1 = require("./api");
10
+ const agent_container_1 = require("./agent-container");
11
+ const config_1 = require("./config");
12
+ const github_app_1 = require("./github-app");
13
+ const runtime_1 = require("./runtime");
14
+ const triage_agent_guard_1 = require("./triage-agent-guard");
15
+ const utils_1 = require("./utils");
16
+ const MAX_TURNS = 60;
17
+ const CLAUDE_TIMEOUT_MS = 20 * 60 * 1000;
18
+ const PROMPT_PATH = '.github/agent/triage-agent.md';
19
+ const PR_FIELDS = 'number,title,author,isCrossRepository,headRefName,headRefOid,labels,state';
20
+ /** The design doc's allowlist for the triage agent (airlock mode, so no global rules apply). */
21
+ const TRIAGE_RULES = [
22
+ { domain: 'registry.npmjs.org', status: 'allow' }, // npm view, npm pack of the old and new version
23
+ { domain: 'github.com', status: 'allow' },
24
+ { domain: 'api.github.com', status: 'allow' }, // advisories and the upstream fix commit, unauthenticated
25
+ { domain: 'api.osv.dev', status: 'allow' },
26
+ { domain: 'api.anthropic.com', status: 'allow' },
27
+ { domain: 'huddle', status: 'allow' }, // huddle's own audit forwarder
28
+ ];
29
+ /**
30
+ * What reading needs. The file tools write only in /workspace/out, but these
31
+ * shell commands can write files and run code inside the container (`tar
32
+ * --to-command`, `npm pack` of a local folder runs its prepack script): the
33
+ * airlocked, credential-free container is the boundary, not this list. The
34
+ * prompt asks for `npm pack <name>@<version> --ignore-scripts` and never
35
+ * `npm install`, so the bumped package's install scripts are not run on purpose.
36
+ */
37
+ const ALLOWED_TOOLS = [
38
+ // Edit rules cover every file-writing tool, Write included; a Write(path) rule would match nothing.
39
+ 'Read', 'Glob', 'Grep', 'Edit(//workspace/out/**)',
40
+ 'Bash(curl:*)', 'Bash(npm view:*)', 'Bash(npm pack:*)', 'Bash(tar:*)', 'Bash(diff:*)', 'Bash(mkdir:*)',
41
+ 'Bash(ls:*)', 'Bash(cat:*)', 'Bash(head:*)',
42
+ 'Bash(git log:*)', 'Bash(git show:*)', 'Bash(git diff:*)', 'Bash(git grep:*)',
43
+ ].join(',');
44
+ /** Where the agent unpacks the old and new package. */
45
+ const SCRATCH_DIR = '/tmp/triage';
46
+ /** Working directories next to /workspace/repo: its inputs, its output and its scratch space. */
47
+ const WORK_DIRS = ['/workspace/input', '/workspace/out', SCRATCH_DIR];
48
+ /** A token for comments only, when the CLI runs as a GitHub App. */
49
+ const APP_PERMISSIONS = { contents: 'read', pull_requests: 'write' };
50
+ // ── entry point ──────────────────────────────────────────────────────────────
51
+ async function runTriageAgent(opts) {
52
+ const engine = (0, runtime_1.resolveRuntime)(opts.runtime).name;
53
+ // With a GitHub App, or the token in GH_TOKEN (the CI job's own), or the developer's `gh` login.
54
+ const appConfig = (0, github_app_1.appConfigFromEnv)();
55
+ const app = appConfig ? new github_app_1.GithubApp(appConfig, APP_PERMISSIONS) : null;
56
+ delete process.env.HUDDLE_GITHUB_APP_PRIVATE_KEY;
57
+ if (app)
58
+ await app.refresh();
59
+ else if (!process.env.GH_TOKEN && !process.env.GITHUB_TOKEN && (0, agent_container_1.run)('gh', ['auth', 'status']).status !== 0) {
60
+ throw new Error('GitHub CLI is not logged in. Run `gh auth login` first.');
61
+ }
62
+ const repo = app?.repo ?? (process.env.GH_REPO?.trim() || (0, agent_container_1.must)('gh', ['repo', 'view', '--json', 'nameWithOwner', '-q', '.nameWithOwner']).trim());
63
+ const credential = (0, agent_container_1.claudeCredential)();
64
+ // Doubles as the "is Huddle running and are we authenticated" check.
65
+ const { imageName } = await (0, api_1.get)('/api/docker/base-image?ide=vscode');
66
+ const prompt = localPrompt() ?? (0, agent_container_1.fetchPrompt)(repo, PROMPT_PATH, 'HUDDLE_TRIAGE_AGENT_PROMPT_REF', 'triage agent');
67
+ const login = app ? (await app.identity()).name : githubLogin();
68
+ const refreshGithub = async () => { await app?.refresh(); };
69
+ const prs = listPrs(repo, opts.pr);
70
+ if (prs.length === 0) {
71
+ console.log(opts.pr ? `PR #${opts.pr} not found.` : 'No open PRs labelled security.');
72
+ return;
73
+ }
74
+ const results = [];
75
+ await (0, agent_container_1.withInterruptHandler)(() => processAll(prs, { repo, engine, imageName, credential, prompt, login, opts, refreshGithub }, results));
76
+ console.log(`\n${(0, utils_1.bold)('Triage agent summary')}`);
77
+ for (const r of results) {
78
+ const color = r.outcome === 'commented' || r.outcome === 'dry-run' ? utils_1.green : r.outcome === 'skipped' ? utils_1.dim : utils_1.red;
79
+ console.log(` #${r.pr} ${color(r.outcome.padEnd(9))} ${r.detail}`);
80
+ }
81
+ if (results.some((r) => r.outcome === 'error'))
82
+ process.exitCode = 1;
83
+ }
84
+ /**
85
+ * HUDDLE_TRIAGE_AGENT_PROMPT_FILE: a prompt from your own disk, to tune it
86
+ * locally before it is pushed anywhere. Not in GitHub Actions, where the
87
+ * prompt must come from the default branch.
88
+ */
89
+ function localPrompt() {
90
+ const file = process.env.HUDDLE_TRIAGE_AGENT_PROMPT_FILE?.trim();
91
+ if (!file)
92
+ return null;
93
+ if ((0, agent_container_1.inActions)())
94
+ throw new Error('HUDDLE_TRIAGE_AGENT_PROMPT_FILE is for local runs only; in CI the prompt comes from the default branch.');
95
+ const prompt = fs_1.default.readFileSync(file, 'utf8');
96
+ if (!prompt.trim())
97
+ throw new Error(`${file} is empty`);
98
+ console.log((0, utils_1.yellow)(`Using the local prompt ${file} instead of ${PROMPT_PATH} from the default branch.`));
99
+ return prompt;
100
+ }
101
+ /** Who posts the comment, to find its own earlier one: the developer, or the CI job's token. */
102
+ function githubLogin() {
103
+ const r = (0, agent_container_1.run)('gh', ['api', 'user', '-q', '.login']);
104
+ if (r.status === 0 && r.stdout.trim())
105
+ return r.stdout.trim();
106
+ // The job's GITHUB_TOKEN cannot read /user; its comments are github-actions[bot]'s.
107
+ if ((0, agent_container_1.inActions)())
108
+ return 'github-actions[bot]';
109
+ throw new Error(`Could not read your GitHub login: ${r.stderr.trim()}`);
110
+ }
111
+ function listPrs(repo, only) {
112
+ if (only) {
113
+ const r = (0, agent_container_1.run)('gh', ['pr', 'view', String(only), '--repo', repo, '--json', PR_FIELDS]);
114
+ if (r.status === 0)
115
+ return [JSON.parse(r.stdout)];
116
+ if (/could not resolve|not found/i.test(r.stderr))
117
+ return [];
118
+ throw new Error(`gh pr view ${only} failed: ${r.stderr.trim()}`);
119
+ }
120
+ const out = (0, agent_container_1.must)('gh', ['pr', 'list', '--repo', repo, '--label', 'security', '--state', 'open', '--limit', '100', '--json', PR_FIELDS]);
121
+ return JSON.parse(out);
122
+ }
123
+ async function processAll(prs, base, results) {
124
+ const { opts } = base;
125
+ for (const pr of prs) {
126
+ if ((0, agent_container_1.isInterrupted)())
127
+ break;
128
+ const decision = (0, triage_agent_guard_1.decideTriage)(pr);
129
+ if (decision.action === 'skip') {
130
+ if (opts.pr)
131
+ console.log((0, utils_1.yellow)(`Skipping #${pr.number}: ${decision.reason}`));
132
+ results.push({ pr: pr.number, outcome: 'skipped', detail: decision.reason });
133
+ continue;
134
+ }
135
+ console.log(`\n${(0, utils_1.bold)(`PR #${pr.number}`)} ${pr.title} ${(0, utils_1.dim)(`(${pr.headRefName})`)}`);
136
+ const ctx = { ...base, pr, usage: { costUsd: 0, turns: 0 } };
137
+ try {
138
+ await ctx.refreshGithub();
139
+ results.push(await processPr(ctx));
140
+ }
141
+ catch (err) {
142
+ const msg = err instanceof Error ? err.message : String(err);
143
+ (0, agent_container_1.printUntrusted)(` error: ${msg}`, utils_1.red, 20_000, true);
144
+ results.push({ pr: pr.number, outcome: 'error', detail: msg });
145
+ }
146
+ }
147
+ }
148
+ // ── one PR ───────────────────────────────────────────────────────────────────
149
+ async function processPr(ctx) {
150
+ const { pr, opts } = ctx;
151
+ const name = `triage-agent-pr-${pr.number}`;
152
+ const dir = path_1.default.join(config_1.CONFIG_DIR, 'triage-agent', `pr-${pr.number}`);
153
+ // A container from an earlier --keep run is someone's debugging session.
154
+ if (await (0, agent_container_1.containerExists)(name)) {
155
+ return { pr: pr.number, outcome: 'skipped', detail: `container ${name} from an earlier --keep run still exists; remove it first` };
156
+ }
157
+ fs_1.default.rmSync(dir, { recursive: true, force: true });
158
+ try {
159
+ return await triagePr(ctx, name, path_1.default.join(dir, 'workspace'));
160
+ }
161
+ finally {
162
+ if (opts.out && ctx.container) {
163
+ try {
164
+ await (0, agent_container_1.saveNetworkLog)(ctx.container, path_1.default.join(opts.out, `pr-${pr.number}-network.json`), { pr: pr.number });
165
+ }
166
+ catch (err) {
167
+ console.log((0, utils_1.yellow)(` could not write the network log: ${err instanceof Error ? err.message : String(err)}`));
168
+ }
169
+ }
170
+ if (!opts.keep && ctx.container)
171
+ (0, agent_container_1.wipeWorkspace)(ctx.engine, name);
172
+ await (0, agent_container_1.cleanup)(name, opts.keep);
173
+ if (!opts.keep)
174
+ (0, agent_container_1.removeDir)(dir);
175
+ }
176
+ }
177
+ /** dir/workspace is mounted at /workspace: repo/ (the PR head), input/ and out/. */
178
+ async function triagePr(ctx, name, ws) {
179
+ const { pr, repo } = ctx;
180
+ for (const d of ['input', 'out'])
181
+ fs_1.default.mkdirSync(path_1.default.join(ws, d), { recursive: true });
182
+ const repoDir = path_1.default.join(ws, 'repo');
183
+ (0, agent_container_1.must)('gh', ['repo', 'clone', repo, repoDir, '--', '--config', 'core.autocrlf=false', '--quiet', '--no-tags', '--single-branch', '--depth', '1', '--branch', pr.headRefName]);
184
+ if ((0, agent_container_1.must)('git', ['-C', repoDir, 'rev-parse', 'HEAD']).trim() !== pr.headRefOid) {
185
+ return { pr: pr.number, outcome: 'skipped', detail: 'branch moved while starting; run again' };
186
+ }
187
+ // Read before the container exists (afterwards the host never reads the mounted folder),
188
+ // from git's objects rather than the checkout, so a symlink in the PR is not followed.
189
+ // grep exits 1 when nothing matched: a repository without text files.
190
+ const grep = (0, agent_container_1.run)('git', ['-C', repoDir, 'grep', '-c', '-I', '-z', '', 'HEAD']);
191
+ if (grep.status !== 0 && grep.status !== 1)
192
+ throw new Error(`git grep in the PR checkout failed: ${grep.stderr.trim()}`);
193
+ const lineCounts = (0, triage_agent_guard_1.parseLineCounts)(grep.stdout);
194
+ const { bumps, advisories } = writeInputs(ctx, path_1.default.join(ws, 'input'));
195
+ ctx.container = name;
196
+ const agent = await (0, agent_container_1.startAgent)({
197
+ name, engine: ctx.engine, imageName: ctx.imageName, credential: ctx.credential, rules: TRIAGE_RULES, workspace: ws,
198
+ description: 'airlocked: npm registry, GitHub, OSV and Anthropic API only',
199
+ });
200
+ // Scratch space for the package tarballs: outside the mount, so they never land on the host.
201
+ const scratch = await agent.exec(['mkdir', '-p', SCRATCH_DIR], '/workspace');
202
+ if (scratch.status !== 0)
203
+ throw new Error(`could not create ${SCRATCH_DIR} in ${name}: ${scratch.stderr.trim()}`);
204
+ console.log((0, utils_1.dim)(' running Claude Code'));
205
+ const model = process.env.HUDDLE_TRIAGE_AGENT_MODEL?.trim();
206
+ const claude = await agent.exec([
207
+ 'claude', '-p', ctx.prompt, '--output-format', 'json', '--max-turns', String(MAX_TURNS),
208
+ ...(model ? ['--model', model] : []), '--allowedTools', ALLOWED_TOOLS,
209
+ // Claude Code refuses even `cat` and `ls` on paths outside its working directories.
210
+ ...WORK_DIRS.flatMap((d) => ['--add-dir', d]),
211
+ ], '/workspace/repo', { timeout: CLAUDE_TIMEOUT_MS, liveStderr: !(0, agent_container_1.inActions)() });
212
+ const answer = reportClaude(ctx, claude);
213
+ agent.stopAll();
214
+ // The prompt asks for the same JSON in the final answer, in case writing the file failed.
215
+ const raw = (await agent.readFile('/workspace/out/triage.json')).trim() || (0, triage_agent_guard_1.extractTriageJson)(answer);
216
+ if (!raw && claude.status !== 0) {
217
+ // Not the PR's fault: credential, firewall or Claude Code itself.
218
+ throw new Error(`Claude Code ${claude.timedOut ? 'timed out' : `exited with ${claude.status}`} without an analysis. ` +
219
+ `Check the credential and the requested rules for ${name} in the portal.`);
220
+ }
221
+ const parsed = raw ? (0, triage_agent_guard_1.parseTriage)(raw, lineCounts) : { ok: false, errors: ['the agent wrote no triage.json'] };
222
+ let report = null;
223
+ let problem;
224
+ if (parsed.ok) {
225
+ report = parsed.report;
226
+ }
227
+ else {
228
+ problem = 'the agent wrote no valid analysis';
229
+ console.log((0, utils_1.yellow)(` ${problem}:\n${parsed.errors.map((e) => ` ${e}`).join('\n')}`));
230
+ // An unchecked file can still hold an analysis that must stay private: keep it as is.
231
+ if (claimsBeyondAdvisory(raw))
232
+ keepPrivate(ctx, `# Triage agent: ${repo} PR #${pr.number} (triage.json failed the check)\n\n\`\`\`json\n${raw}\n\`\`\`\n`);
233
+ }
234
+ if (report?.beyondAdvisory)
235
+ keepPrivate(ctx, (0, triage_agent_guard_1.renderPrivate)(report, { number: pr.number, title: pr.title, repo }));
236
+ const url = (0, agent_container_1.actionsRunUrl)();
237
+ const body = (0, triage_agent_guard_1.renderComment)({
238
+ report, problem, bumps, title: pr.title, advisories, repo, headSha: pr.headRefOid,
239
+ facts: await (0, agent_container_1.runFacts)(ctx.container, ctx.usage),
240
+ runner: url ? `Run by [GitHub Actions](${url})` : `Run by ${ctx.login}`,
241
+ });
242
+ const verdict = report ? (report.beyondAdvisory ? 'withheld, deep-dive' : `affected: ${report.affected}`) : 'no valid analysis';
243
+ if (ctx.opts.dryRun) {
244
+ console.log((0, utils_1.dim)('\n--- PR comment that would be posted ---'));
245
+ (0, agent_container_1.printUntrusted)(body, (s) => s, 40_000);
246
+ return { pr: pr.number, outcome: 'dry-run', detail: `${verdict}; nothing posted` };
247
+ }
248
+ await ctx.refreshGithub();
249
+ postComment(ctx, body);
250
+ return { pr: pr.number, outcome: 'commented', detail: verdict };
251
+ }
252
+ /**
253
+ * The PR's title and body, what its lockfiles bump, and the GitHub advisories
254
+ * it names, read with the host's GitHub access (the container has none).
255
+ */
256
+ function writeInputs(ctx, input) {
257
+ const { pr, repo } = ctx;
258
+ const view = JSON.parse((0, agent_container_1.must)('gh', ['pr', 'view', String(pr.number), '--repo', repo, '--json', 'title,body,baseRefName,files']));
259
+ fs_1.default.writeFileSync(path_1.default.join(input, 'pr.md'), `# ${view.title}\n\n${view.body ?? ''}\n`);
260
+ // Versions at the merge base, as the PR's diff shows them.
261
+ const mergeBase = (0, agent_container_1.must)('gh', ['api', `repos/${repo}/compare/${encodeURIComponent(view.baseRefName)}...${pr.headRefOid}`, '-q', '.merge_base_commit.sha']).trim();
262
+ const readAt = (file, ref) => {
263
+ const r = (0, agent_container_1.run)('gh', ['api', '-H', 'Accept: application/vnd.github.raw', `repos/${repo}/contents/${file.split('/').map(encodeURIComponent).join('/')}?ref=${ref}`]);
264
+ if (r.status === 0)
265
+ return r.stdout;
266
+ if (/HTTP 404/.test(r.stderr))
267
+ return null;
268
+ throw new Error(`could not read ${file} at ${ref}: ${r.stderr.trim()}`);
269
+ };
270
+ const bumps = [];
271
+ const unreadable = [];
272
+ for (const f of view.files ?? []) {
273
+ if (!/(^|\/)package-lock\.json$/.test(f.path))
274
+ continue;
275
+ try {
276
+ bumps.push(...(0, triage_agent_guard_1.lockfileBumps)(f.path, readAt(f.path, mergeBase), readAt(f.path, pr.headRefOid)));
277
+ }
278
+ catch (err) {
279
+ // A broken lockfile (conflict markers, say) still gets an analysis, or at least the fallback comment.
280
+ unreadable.push(f.path);
281
+ console.log((0, utils_1.yellow)(` could not read the versions in ${f.path}: ${err instanceof Error ? err.message : String(err)}`));
282
+ }
283
+ }
284
+ fs_1.default.writeFileSync(path_1.default.join(input, 'bumps.json'), `${JSON.stringify(bumps, null, 2)}\n`);
285
+ if (unreadable.length) {
286
+ fs_1.default.writeFileSync(path_1.default.join(input, 'bumps-incomplete.txt'), `bumps.json leaves out these lockfiles, which could not be parsed:\n${unreadable.join('\n')}\n`);
287
+ }
288
+ const advisories = (0, triage_agent_guard_1.advisoryIds)(`${view.title}\n${view.body ?? ''}`);
289
+ fs_1.default.mkdirSync(path_1.default.join(input, 'advisories'));
290
+ for (const id of advisories.slice(0, 10)) {
291
+ const r = id.startsWith('GHSA-')
292
+ ? (0, agent_container_1.run)('gh', ['api', `advisories/${id}`])
293
+ : (0, agent_container_1.run)('gh', ['api', `advisories?cve_id=${id}`]);
294
+ // A CVE search answers with a list, empty when GitHub has no advisory for it.
295
+ const found = r.status === 0 && r.stdout.trim() !== '[]';
296
+ fs_1.default.writeFileSync(path_1.default.join(input, 'advisories', `${id}.json`), found ? r.stdout : `{"error": "not found on GitHub; look it up on OSV"}\n`);
297
+ }
298
+ console.log((0, utils_1.dim)(` ${bumps.length} package version change(s), advisories: ${advisories.join(', ') || 'none named in the PR'}`));
299
+ return { bumps, advisories };
300
+ }
301
+ function claimsBeyondAdvisory(raw) {
302
+ try {
303
+ return JSON.parse(raw)?.beyondAdvisory === true;
304
+ }
305
+ catch {
306
+ return false;
307
+ }
308
+ }
309
+ /**
310
+ * Prints the agent's final answer (not in Actions: the log is public), adds
311
+ * its cost and turns to ctx.usage, and returns the answer.
312
+ */
313
+ function reportClaude(ctx, r) {
314
+ const out = (0, agent_container_1.parseClaudeOutput)(r.stdout);
315
+ if (out) {
316
+ ctx.usage.costUsd += out.costUsd;
317
+ ctx.usage.turns += out.turns;
318
+ }
319
+ // Its answer may hold an analysis that must stay private (beyondAdvisory).
320
+ if (!(0, agent_container_1.inActions)()) {
321
+ if (out?.result)
322
+ (0, agent_container_1.printUntrusted)(out.result.replace(/^/gm, ' '));
323
+ else if (!out && r.stdout.trim())
324
+ (0, agent_container_1.printUntrusted)(r.stdout.trim());
325
+ }
326
+ // A refused call is a check the agent could not do: ALLOWED_TOOLS or the prompt needs a look.
327
+ // In Actions only the tools: a command line can carry what the agent was looking into.
328
+ if (out?.denials.length) {
329
+ console.log((0, utils_1.yellow)(` Claude Code refused ${out.denials.length} tool call(s) that no allow rule matched:`));
330
+ (0, agent_container_1.printUntrusted)(out.denials.map((d) => ` ${d.tool}${(0, agent_container_1.inActions)() ? '' : `: ${d.input}`}`).join('\n'), utils_1.yellow, 6_000);
331
+ }
332
+ if (r.status !== 0 && r.stderr.trim())
333
+ (0, agent_container_1.printUntrusted)(r.stderr.trim());
334
+ return out?.result ?? '';
335
+ }
336
+ /**
337
+ * An analysis that goes beyond the advisory is not posted (design doc,
338
+ * "Keeping vulnerabilities private"). With --out it is written next to the
339
+ * network log, for the workflow to encrypt; locally it is printed.
340
+ */
341
+ function keepPrivate(ctx, markdown) {
342
+ const { pr, opts } = ctx;
343
+ if (opts.out) {
344
+ fs_1.default.mkdirSync(opts.out, { recursive: true });
345
+ const file = path_1.default.join(opts.out, `pr-${pr.number}-private.md`);
346
+ fs_1.default.writeFileSync(file, markdown, { mode: 0o600 });
347
+ console.log((0, utils_1.yellow)(` the analysis goes beyond the advisory: written to ${file}, not posted`));
348
+ }
349
+ else if (!(0, agent_container_1.inActions)()) {
350
+ console.log((0, utils_1.yellow)(' the analysis goes beyond the advisory, so it is not posted. Share it with maintainers privately:'));
351
+ (0, agent_container_1.printUntrusted)(markdown, (s) => s, 40_000);
352
+ }
353
+ else {
354
+ console.log((0, utils_1.yellow)(' the analysis goes beyond the advisory; without --out it is not kept anywhere'));
355
+ }
356
+ }
357
+ /** Updates this login's earlier triage comment on the PR, or adds one. */
358
+ function postComment(ctx, body) {
359
+ const { pr, repo, login } = ctx;
360
+ const lines = (0, agent_container_1.must)('gh', [
361
+ 'api', '--paginate', `repos/${repo}/issues/${pr.number}/comments`,
362
+ '--jq', `.[] | select(.body | startswith(${JSON.stringify(triage_agent_guard_1.TRIAGE_MARKER)})) | "\\(.id)\\t\\(.user.login)"`,
363
+ ]);
364
+ const id = (0, triage_agent_guard_1.ownCommentId)(lines, login);
365
+ if (id) {
366
+ (0, agent_container_1.must)('gh', ['api', '-X', 'PATCH', `repos/${repo}/issues/comments/${id}`, '--input', '-'], { input: JSON.stringify({ body }) });
367
+ console.log((0, utils_1.green)(` updated the triage comment on #${pr.number}`));
368
+ }
369
+ else {
370
+ (0, agent_container_1.must)('gh', ['pr', 'comment', String(pr.number), '--repo', repo, '--body-file', '-'], { input: body });
371
+ console.log((0, utils_1.green)(` commented on #${pr.number}`));
372
+ }
373
+ }
@@ -0,0 +1,268 @@
1
+ "use strict";
2
+ // Pure decision logic for `huddle update-agent`: which PRs to work on, which
3
+ // files the agent may never change, and which changes a reviewer should look at
4
+ // twice. No I/O here, so it is unit-tested in cli/test/.
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.PROJECTS = exports.AGENT_TRAILER = exports.MAJOR_LABEL = exports.GAVE_UP_LABEL = void 0;
7
+ exports.isGuardedPath = isGuardedPath;
8
+ exports.guardViolations = guardViolations;
9
+ exports.parseNameStatus = parseNameStatus;
10
+ exports.testWeakeningFlags = testWeakeningFlags;
11
+ exports.renovatePrAuthor = renovatePrAuthor;
12
+ exports.isRenovatePrAuthor = isRenovatePrAuthor;
13
+ exports.renovateBranchPrefix = renovateBranchPrefix;
14
+ exports.isRenovateBranch = isRenovateBranch;
15
+ exports.sanitizeCommitMessage = sanitizeCommitMessage;
16
+ exports.isAgentCommit = isAgentCommit;
17
+ exports.isRenovateAuthor = isRenovateAuthor;
18
+ exports.ciWorkflows = ciWorkflows;
19
+ exports.hasFailingChecks = hasFailingChecks;
20
+ exports.failedJobs = failedJobs;
21
+ exports.affectedProjects = affectedProjects;
22
+ exports.decide = decide;
23
+ exports.requestsByHost = requestsByHost;
24
+ /** Files only a person may change (design doc, Part 2 "Agents never"). */
25
+ const GUARDED = [
26
+ /^\.github\//,
27
+ /(^|\/)renovate\.json5?$/,
28
+ /(^|\/)Dockerfile[^/]*$/,
29
+ /^base-devimage[^/]*\//,
30
+ // The security boundary: auth, TLS interception, firewall decisions, the
31
+ // Docker socket filter, sudo grants and the credential exchange.
32
+ /^gateway\/src\/(auth|tls-ca|proxy|rules|socket-proxy|docker-actions|sudo-grant|token-exchange|token-exchange-api)\.ts$/,
33
+ ];
34
+ function isGuardedPath(file) {
35
+ const p = file.replace(/\\/g, '/');
36
+ return GUARDED.some((re) => re.test(p));
37
+ }
38
+ /** Changed files the agent was not allowed to touch (empty = OK). */
39
+ function guardViolations(changedFiles) {
40
+ return changedFiles.filter(isGuardedPath);
41
+ }
42
+ /** Parses `git diff --name-status` output. For renames, the old path counts as deleted. */
43
+ function parseNameStatus(output) {
44
+ const out = [];
45
+ for (const line of output.split('\n')) {
46
+ if (!line.trim())
47
+ continue;
48
+ const [status, ...paths] = line.split('\t');
49
+ if (status.startsWith('R') && paths.length === 2) {
50
+ out.push({ status: 'D', path: paths[0] }, { status: 'A', path: paths[1] });
51
+ }
52
+ else if (paths[0]) {
53
+ out.push({ status: status[0], path: paths[0] });
54
+ }
55
+ }
56
+ return out;
57
+ }
58
+ const TEST_FILE = /(^|\/)(test|tests|__tests__|e2e)\/|\.(test|spec|e2e)\.[cm]?[jt]sx?$/;
59
+ /**
60
+ * Signs that a test was weakened instead of the code being fixed. These are
61
+ * flags for the reviewer, not a hard block: removing an assertion can be the
62
+ * right fix for an API that changed.
63
+ */
64
+ function testWeakeningFlags(files, unifiedDiff) {
65
+ const flags = [];
66
+ for (const f of files) {
67
+ if (f.status === 'D' && TEST_FILE.test(f.path))
68
+ flags.push(`deleted test file ${f.path}`);
69
+ }
70
+ let added = 0;
71
+ let removed = 0;
72
+ for (const line of unifiedDiff.split('\n')) {
73
+ if (line.startsWith('+++') || line.startsWith('---'))
74
+ continue;
75
+ if (line.startsWith('+') && /\b(it|test|describe)\.(skip|only|todo)\b|\bx(it|describe)\(/.test(line)) {
76
+ flags.push(`added ${line.slice(1).trim().slice(0, 80)}`);
77
+ }
78
+ if (/\bexpect\(/.test(line)) {
79
+ if (line.startsWith('+'))
80
+ added++;
81
+ else if (line.startsWith('-'))
82
+ removed++;
83
+ }
84
+ }
85
+ if (removed > added)
86
+ flags.push(`${removed - added} fewer expect() assertions`);
87
+ return flags;
88
+ }
89
+ exports.GAVE_UP_LABEL = 'agent-gave-up';
90
+ /** Renovate adds it to major updates (`addLabels` on the majors rule in renovate.json5); see --skip-majors. */
91
+ exports.MAJOR_LABEL = 'major';
92
+ /** Trailer the CLI adds to every commit the agent pushes, so a later run recognises it. */
93
+ exports.AGENT_TRAILER = 'Huddle-Update-Agent';
94
+ const FAILED = new Set(['FAILURE', 'TIMED_OUT', 'CANCELLED', 'ACTION_REQUIRED', 'STARTUP_FAILURE', 'ERROR']);
95
+ const SAFE_REF_CHARS = /^[A-Za-z0-9._\/()+-]+$/;
96
+ /** Renovate's GitHub account, as `gh --author` takes it: the Mend app unless HUDDLE_RENOVATE_AUTHOR says otherwise. */
97
+ function renovatePrAuthor() {
98
+ return process.env.HUDDLE_RENOVATE_AUTHOR?.trim() || 'app/renovate';
99
+ }
100
+ /**
101
+ * Whether GitHub says Renovate opened the PR. An `app/<name>` author must be
102
+ * that app's bot account, so a user who happens to be called "renovate" does
103
+ * not pass.
104
+ */
105
+ function isRenovatePrAuthor(author, expected = renovatePrAuthor()) {
106
+ const login = (author?.login ?? '').trim().toLowerCase();
107
+ const want = expected.trim().toLowerCase();
108
+ if (!login)
109
+ return false;
110
+ if (want.startsWith('app/')) {
111
+ return author?.is_bot === true && (login === want || login === `${want.slice(4)}[bot]`);
112
+ }
113
+ return login === want;
114
+ }
115
+ /** Renovate's branchPrefix: 'renovate/' unless HUDDLE_RENOVATE_BRANCH_PREFIX says otherwise. */
116
+ function renovateBranchPrefix() {
117
+ return process.env.HUDDLE_RENOVATE_BRANCH_PREFIX?.trim() || 'renovate/';
118
+ }
119
+ /** A branch Renovate made, with only characters that are safe to pass to git. */
120
+ function isRenovateBranch(branch, prefix = renovateBranchPrefix()) {
121
+ return branch.startsWith(prefix) && branch.length > prefix.length && SAFE_REF_CHARS.test(branch);
122
+ }
123
+ const TRAILER = /^(co-authored-by|signed-off-by|reviewed-by|acked-by|approved-by|tested-by|reported-by|huddle-update-agent)\s*:/i;
124
+ /**
125
+ * The agent writes its own commit message after reading untrusted input. Keep
126
+ * it, but drop attribution trailers (they would credit or implicate other
127
+ * people) and cap its size. Falls back when nothing usable is left. Ends with
128
+ * the AGENT_TRAILER, so a later run knows this commit is the agent's.
129
+ */
130
+ function sanitizeCommitMessage(message, fallback, source = 'huddle update-agent') {
131
+ const lines = message.replace(/\r\n/g, '\n').split('\n').filter((l) => !TRAILER.test(l.trim()));
132
+ const subject = (lines.shift() ?? '').trim().slice(0, 100) || fallback;
133
+ const body = lines.join('\n').trim().slice(0, 4000);
134
+ const trailer = `${exports.AGENT_TRAILER}: ${source.replace(/\s+/g, ' ').trim()}`;
135
+ return body ? `${subject}\n\n${body}\n\n${trailer}\n` : `${subject}\n\n${trailer}\n`;
136
+ }
137
+ /** A commit the update agent pushed: its message carries the AGENT_TRAILER. */
138
+ function isAgentCommit(commit) {
139
+ return new RegExp(`^${exports.AGENT_TRAILER}:`, 'im').test(commit.messageBody ?? '');
140
+ }
141
+ /**
142
+ * Renovate as the Mend app (`renovate[bot]`), as a self-hosted bot account
143
+ * (`renovate-bot`, Renovate's default `bot@renovateapp.com` git author), or as
144
+ * extra logins/emails listed in HUDDLE_RENOVATE_AUTHORS (comma-separated).
145
+ */
146
+ function isRenovateAuthor(a, extra = renovateAuthorsFromEnv()) {
147
+ const ids = [a.login, a.name, a.email].map((v) => (v ?? '').trim().toLowerCase()).filter(Boolean);
148
+ return ids.some((id) => /^renovate(\[bot\]|-bot)?$/.test(id) ||
149
+ /^(\d+\+)?renovate\[bot\]@users\.noreply\.github\.com$/.test(id) ||
150
+ id === 'bot@renovateapp.com' ||
151
+ extra.includes(id));
152
+ }
153
+ function renovateAuthorsFromEnv() {
154
+ return (process.env.HUDDLE_RENOVATE_AUTHORS ?? '').split(',').map((s) => s.trim().toLowerCase()).filter(Boolean);
155
+ }
156
+ /**
157
+ * The GitHub Actions workflows whose result is "CI" for the agent: 'Test'
158
+ * unless HUDDLE_UPDATE_AGENT_CI_WORKFLOWS (comma-separated) says otherwise.
159
+ * Other red checks are not a build the agent can fix: the security review gate
160
+ * waits for a person, a scanner reports a vulnerability, the test agent
161
+ * reports a security finding.
162
+ */
163
+ function ciWorkflows() {
164
+ const list = (process.env.HUDDLE_UPDATE_AGENT_CI_WORKFLOWS ?? '').split(',').map((s) => s.trim()).filter(Boolean);
165
+ return list.length ? list : ['Test'];
166
+ }
167
+ function isFailedCheck(c, workflows) {
168
+ if (!workflows.includes((c.workflowName ?? '').trim()))
169
+ return false;
170
+ return FAILED.has((c.conclusion ?? '').toUpperCase()) || FAILED.has((c.state ?? '').toUpperCase());
171
+ }
172
+ function hasFailingChecks(pr, workflows = ciWorkflows()) {
173
+ return pr.statusCheckRollup.some((c) => isFailedCheck(c, workflows));
174
+ }
175
+ /**
176
+ * The failing GitHub Actions jobs, for `gh run view --job <id> --log`. Job logs
177
+ * are readable as soon as the job finishes, even while other jobs of the same
178
+ * run are still going (`--log-failed` waits for the whole run).
179
+ */
180
+ function failedJobs(pr, workflows = ciWorkflows()) {
181
+ const jobs = new Map();
182
+ for (const c of pr.statusCheckRollup) {
183
+ if (!isFailedCheck(c, workflows))
184
+ continue;
185
+ const m = /\/actions\/runs\/(\d+)\/job\/(\d+)/.exec(c.detailsUrl ?? c.targetUrl ?? '');
186
+ if (m)
187
+ jobs.set(m[2], { runId: m[1], jobId: m[2] });
188
+ }
189
+ return [...jobs.values()];
190
+ }
191
+ /** The npm projects CI builds, in build order: the gateway build compiles the frontend. */
192
+ exports.PROJECTS = ['gateway/frontend', 'gateway', 'cli'];
193
+ /**
194
+ * Which projects to verify for a set of changed files. CI checks everything
195
+ * after the push; locally only what the change can break, so a `cli` update
196
+ * does not depend on installing the gateway's native modules. A gateway
197
+ * change needs the frontend too (`build:ui`). A file outside the projects
198
+ * (root config, workflows, ...) could affect any of them, so it means all.
199
+ */
200
+ function affectedProjects(changedFiles) {
201
+ const hit = new Set();
202
+ for (const raw of changedFiles) {
203
+ const f = raw.replace(/\\/g, '/');
204
+ if (f.startsWith('gateway/')) {
205
+ hit.add('gateway/frontend');
206
+ hit.add('gateway');
207
+ }
208
+ else if (f.startsWith('cli/')) {
209
+ hit.add('cli');
210
+ }
211
+ else {
212
+ return [...exports.PROJECTS];
213
+ }
214
+ }
215
+ return exports.PROJECTS.filter((p) => hit.has(p));
216
+ }
217
+ /** What the agent should do with this PR. */
218
+ function decide(pr, opts = {}) {
219
+ const skip = (reason) => ({ action: 'skip', reason });
220
+ // Listing filters on the author already; a PR named on the command line
221
+ // gets the same check here, so a Renovate-looking branch is not enough.
222
+ if (!isRenovatePrAuthor(pr.author))
223
+ return skip(`not opened by ${renovatePrAuthor()}`);
224
+ if (pr.isCrossRepository !== false)
225
+ return skip('not a branch in this repository');
226
+ const prefix = renovateBranchPrefix();
227
+ if (!isRenovateBranch(pr.headRefName, prefix))
228
+ return skip(`branch ${pr.headRefName} is not a ${prefix}* branch`);
229
+ if (pr.labels.some((l) => l.name === exports.GAVE_UP_LABEL))
230
+ return skip(`labelled ${exports.GAVE_UP_LABEL}`);
231
+ if (opts.skipMajors && pr.labels.some((l) => l.name === exports.MAJOR_LABEL))
232
+ return skip(`a major update (labelled ${exports.MAJOR_LABEL})`);
233
+ const others = pr.commits.filter((c) => !c.authors.every((a) => isRenovateAuthor(a)));
234
+ if (others.some((c) => !isAgentCommit(c)))
235
+ return skip('has commits from someone other than Renovate (already being worked on)');
236
+ const failing = hasFailingChecks(pr);
237
+ // The agent never builds on its own pushed fix: that would lift the limit of
238
+ // MAX_ATTEMPTS. Renovate's rebase checkbox drops the fix to start over.
239
+ if (others.length) {
240
+ return failing
241
+ ? { action: 'give-up', reason: 'CI still fails after the agent\'s fix' }
242
+ : skip('the agent already pushed a fix');
243
+ }
244
+ if (!failing)
245
+ return skip('CI is not failing');
246
+ return { action: 'fix' };
247
+ }
248
+ /**
249
+ * Requests per host from Huddle's audit log, busiest first. Only proxy
250
+ * decisions count: `allow`, and as blocked `deny` and `requested` (no rule
251
+ * yet; the proxy answered 403 and asked the operator). The log also holds
252
+ * Huddle's own events for the container (`admin:token-register`,
253
+ * `airlock:on`, ...), which are no requests.
254
+ */
255
+ function requestsByHost(rows) {
256
+ const byHost = new Map();
257
+ for (const r of rows) {
258
+ if (r.action !== 'allow' && r.action !== 'deny' && r.action !== 'requested')
259
+ continue;
260
+ const h = byHost.get(r.domain) ?? { allowed: 0, denied: 0 };
261
+ if (r.action === 'allow')
262
+ h.allowed++;
263
+ else
264
+ h.denied++;
265
+ byHost.set(r.domain, h);
266
+ }
267
+ return [...byHost.entries()].sort((a, b) => b[1].allowed + b[1].denied - (a[1].allowed + a[1].denied));
268
+ }