@infosupport/huddle-cli 0.0.0-experiment-167.144.1 → 0.0.0-experiment-137.147.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.
package/dist/images.js CHANGED
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.resolveImages = resolveImages;
4
4
  exports.gatewayEnvArgs = gatewayEnvArgs;
5
5
  const config_1 = require("./config");
6
+ const base_images_1 = require("./base-images");
6
7
  function resolveImages() {
7
8
  const experiment = (0, config_1.activeExperiment)();
8
9
  const tag = (0, config_1.imageTag)();
@@ -10,26 +11,28 @@ function resolveImages() {
10
11
  experiment,
11
12
  tag,
12
13
  image: process.env.HUDDLE_IMAGE ?? `ghcr.io/infosupport/huddle:${tag}`,
14
+ // Built locally (see base-images.ts), never pulled. BASE_IMAGE_<IDE> still
15
+ // overrides, e.g. to point at a self-built or team-registry image.
13
16
  baseImages: [
14
- { image: process.env.BASE_IMAGE ?? `ghcr.io/infosupport/base-devimage:${tag}` },
15
- { image: process.env.BASE_IMAGE_RIDER ?? `ghcr.io/infosupport/base-devimage-rider:${tag}`, gatewayEnv: 'BASE_IMAGE_RIDER' },
16
- { image: process.env.BASE_IMAGE_INTELLIJ ?? `ghcr.io/infosupport/base-devimage-intellij:${tag}`, gatewayEnv: 'BASE_IMAGE_INTELLIJ' },
17
- { image: process.env.BASE_IMAGE_VSCODE ?? `ghcr.io/infosupport/base-devimage-vscode:${tag}`, gatewayEnv: 'BASE_IMAGE_VSCODE' },
17
+ { image: process.env.BASE_IMAGE ?? (0, base_images_1.localImageName)(undefined, tag), gatewayEnv: 'BASE_IMAGE' },
18
+ { image: process.env.BASE_IMAGE_RIDER ?? (0, base_images_1.localImageName)('rider', tag), gatewayEnv: 'BASE_IMAGE_RIDER' },
19
+ { image: process.env.BASE_IMAGE_INTELLIJ ?? (0, base_images_1.localImageName)('intellij', tag), gatewayEnv: 'BASE_IMAGE_INTELLIJ' },
20
+ { image: process.env.BASE_IMAGE_WEBSTORM ?? (0, base_images_1.localImageName)('webstorm', tag), gatewayEnv: 'BASE_IMAGE_WEBSTORM' },
21
+ { image: process.env.BASE_IMAGE_VSCODE ?? (0, base_images_1.localImageName)('vscode', tag), gatewayEnv: 'BASE_IMAGE_VSCODE' },
18
22
  ],
19
23
  };
20
24
  }
21
25
  /**
22
- * `-e KEY=val` argv pairs for the gateway container. During an experiment (or
23
- * with an explicit override) the gateway must start devcontainers from the same
24
- * base images the CLI just pulled. Returned as an argv array (not a shell
25
- * string) so init can spawn `docker run` without a shell.
26
+ * `-e KEY=val` argv pairs for the gateway container, so it starts devcontainers
27
+ * from (and, if missing, builds) exactly the local images of the active channel.
28
+ * Returned as an argv array (not a shell string) so init can spawn `docker run`
29
+ * without a shell.
26
30
  */
27
31
  function gatewayEnvArgs(resolved) {
28
32
  const args = [];
29
33
  for (const b of resolved.baseImages) {
30
- if (b.gatewayEnv && (resolved.experiment !== undefined || process.env[b.gatewayEnv])) {
34
+ if (b.gatewayEnv)
31
35
  args.push('-e', `${b.gatewayEnv}=${b.image}`);
32
- }
33
36
  }
34
37
  return args;
35
38
  }
package/dist/index.js CHANGED
@@ -12,13 +12,18 @@ const firewall_1 = require("./firewall");
12
12
  const init_1 = require("./init");
13
13
  const migrate_1 = require("./migrate");
14
14
  const indexfolder_1 = require("./indexfolder");
15
+ const triage_agent_1 = require("./triage-agent");
16
+ const update_agent_1 = require("./update-agent");
15
17
  const images_1 = require("./images");
18
+ const base_images_1 = require("./base-images");
19
+ const config_1 = require("./config");
20
+ const runtime_1 = require("./runtime");
16
21
  const self_update_1 = require("./self-update");
17
22
  const utils_1 = require("./utils");
18
23
  const experiment_1 = require("./experiment");
19
24
  const VALUE_FLAGS = new Set(['url', 'ide', 'name', 'image', 'workspace', 'container', 'status', 'runtime', 'experiment', 'path', 'ca-path', 'output', 'out', 'workspace-root', 'depth']);
20
25
  const BOOLEAN_FLAGS = new Set(['help', 'h', 'empty', 'i', 'interactive', 'version', 'v', 'deny', 'docker-socket', 'force', 'replace', 'all', 'list', 'clear']);
21
- const COMMANDS = new Set(['start', 'firewall', 'fw', 'init', 'restart', 'experiment', 'migrate', 'indexfolder', 'indexfolders', 'help', 'version']);
26
+ const COMMANDS = new Set(['start', 'firewall', 'fw', 'init', 'restart', 'experiment', 'migrate', 'indexfolder', 'indexfolders', 'update-agent', 'triage-agent', 'images', 'help', 'version']);
22
27
  function parseArgs(argv) {
23
28
  const positional = [];
24
29
  const flags = {};
@@ -142,10 +147,20 @@ Usage:
142
147
  huddle firewall folder set <path> Set the team-managed rules folder
143
148
  huddle firewall folder reload Re-read the team-managed rules folder
144
149
  huddle firewall folder sync Write the portal's groups back to the folder
150
+ huddle update-agent [PR] Let Claude fix Renovate PRs whose CI is red,
151
+ inside an airlocked devcontainer (needs gh and
152
+ CLAUDE_CODE_OAUTH_TOKEN or ANTHROPIC_API_KEY)
153
+ huddle triage-agent [PR] Let Claude analyse open PRs labelled security
154
+ and comment its impact analysis, inside an
155
+ airlocked devcontainer (same requirements)
145
156
  huddle experiment use <nr> Activate the experimental build of issue/PR <nr>
146
157
  and run init
147
158
  huddle experiment reset Back to the stable release
148
159
  huddle experiment status Show the active channel and CLI version
160
+ huddle images build [--refresh] Build the devcontainer base images on this machine
161
+ (--refresh: rebuild with the latest Claude Code,
162
+ Codex and Copilot CLIs; --ide <ide>: one IDE only)
163
+ huddle images status Show which base images are present
149
164
 
150
165
  Init options:
151
166
  --runtime <docker|podman> Container runtime (default: auto-detected;
@@ -154,7 +169,7 @@ Init options:
154
169
  (same as "huddle experiment use <nr>")
155
170
 
156
171
  Start options:
157
- --ide <intellij|rider|vscode> IDE (default: intellij)
172
+ --ide <intellij|rider|webstorm|vscode> IDE (default: intellij)
158
173
  --workspace <path> Workspace directory (default: current directory)
159
174
  --mount <host>=<container> Mount a host folder at an absolute container path, e.g.
160
175
  C:/projects/my-repo/backend=/workspace/backend
@@ -165,6 +180,23 @@ Start options:
165
180
  --image <image> Use a specific image
166
181
  --empty Empty container without a workspace
167
182
 
183
+ Update-agent options:
184
+ --dry-run Fix and verify, but print the diff instead of
185
+ pushing or commenting
186
+ --keep Keep the agent container and its folder
187
+ (~/.huddle/update-agent) for inspection
188
+ --skip-majors Skip PRs Renovate labelled 'major'
189
+ --out <dir> Write each run's network log to <dir>
190
+ (pr-<n>-network.json)
191
+
192
+ Triage-agent options:
193
+ --dry-run Analyse, but print the comment instead of posting it
194
+ --keep Keep the agent container and its folder
195
+ (~/.huddle/triage-agent) for inspection
196
+ --out <dir> Write each run's network log (pr-<n>-network.json)
197
+ and any analysis that must stay private
198
+ (pr-<n>-private.md) to <dir>
199
+
168
200
  Migrate options:
169
201
  --ca-path <path> Where the Huddle CA lands in the container
170
202
  (NODE_EXTRA_CA_CERTS; default /home/vscode/.huddle-ca.crt)
@@ -275,6 +307,31 @@ async function main() {
275
307
  await (0, init_1.runInit)(initOpts, (0, images_1.resolveImages)());
276
308
  return;
277
309
  }
310
+ if (cmd === 'images') {
311
+ const subCmd = sub ?? 'status';
312
+ const rt = (0, runtime_1.resolveRuntime)(flagString(flags, 'runtime')).name;
313
+ // The background build from `huddle init` passes the channel tag explicitly.
314
+ const tag = process.env.HUDDLE_IMAGES_TAG?.trim() || (0, config_1.imageTag)();
315
+ if (subCmd === 'build') {
316
+ const ide = flagString(flags, 'ide');
317
+ if (ide !== undefined && !base_images_1.IDES.includes(ide)) {
318
+ console.error(`Unknown IDE: ${ide} (choose from ${base_images_1.IDES.join(', ')})`);
319
+ process.exit(1);
320
+ }
321
+ const ok = (0, base_images_1.buildImages)({ rt, tag, ides: ide ? [ide] : undefined, refresh: flagBool(flags, 'refresh') });
322
+ if (!ok)
323
+ process.exit(1);
324
+ }
325
+ else if (subCmd === 'status') {
326
+ (0, base_images_1.printStatus)(rt, tag);
327
+ }
328
+ else {
329
+ console.error(`Unknown images subcommand: ${subCmd}`);
330
+ console.error('Usage: huddle images <build [--refresh] [--ide <ide>]|status>');
331
+ process.exit(1);
332
+ }
333
+ return;
334
+ }
278
335
  if (cmd === 'experiment') {
279
336
  const subCmd = sub ?? 'status';
280
337
  if (subCmd === 'use') {
@@ -363,6 +420,27 @@ async function main() {
363
420
  });
364
421
  return;
365
422
  }
423
+ if (cmd === 'update-agent') {
424
+ await (0, update_agent_1.runUpdateAgent)({
425
+ pr: positional[1] !== undefined ? (0, experiment_1.parseIssueNumber)(positional[1]) : undefined,
426
+ dryRun: flagBool(flags, 'dry-run'),
427
+ keep: flagBool(flags, 'keep'),
428
+ skipMajors: flagBool(flags, 'skip-majors'),
429
+ out: flagString(flags, 'out'),
430
+ runtime: flagString(flags, 'runtime'),
431
+ });
432
+ return;
433
+ }
434
+ if (cmd === 'triage-agent') {
435
+ await (0, triage_agent_1.runTriageAgent)({
436
+ pr: positional[1] !== undefined ? (0, experiment_1.parseIssueNumber)(positional[1]) : undefined,
437
+ dryRun: flagBool(flags, 'dry-run'),
438
+ keep: flagBool(flags, 'keep'),
439
+ out: flagString(flags, 'out'),
440
+ runtime: flagString(flags, 'runtime'),
441
+ });
442
+ return;
443
+ }
366
444
  if (cmd === 'migrate') {
367
445
  await (0, migrate_1.runMigrate)({
368
446
  path: positional[1],
package/dist/init.js CHANGED
@@ -11,6 +11,7 @@ const utils_1 = require("./utils");
11
11
  const runtime_1 = require("./runtime");
12
12
  const images_1 = require("./images");
13
13
  const config_1 = require("./config");
14
+ const base_images_1 = require("./base-images");
14
15
  const fs_1 = __importDefault(require("fs"));
15
16
  const CONTAINER = 'huddle';
16
17
  const VOLUME = 'huddle-data';
@@ -45,28 +46,6 @@ function runArgsSilent(file, args) {
45
46
  return false;
46
47
  }
47
48
  }
48
- /**
49
- * Pulls the devcontainer base images ahead of time. Best-effort: if an image is
50
- * not (yet) available in the registry, we only warn — the gateway then builds it
51
- * from the bundled Dockerfile on the first start.
52
- */
53
- function pullBaseImages(rt, images) {
54
- console.log((0, utils_1.dim)(`Pulling devcontainer base images (${images.length})`));
55
- const failed = [];
56
- for (const image of images) {
57
- console.log((0, utils_1.dim)(` Pulling ${image}`));
58
- try {
59
- runArgs(rt, ['pull', image]);
60
- }
61
- catch {
62
- failed.push(image);
63
- console.log((0, utils_1.yellow)(` [!] Could not pull ${image} — the gateway will build it later if needed.`));
64
- }
65
- }
66
- if (failed.length === images.length) {
67
- console.log((0, utils_1.yellow)('[!] No base image could be pulled. Are the images published and reachable?'));
68
- }
69
- }
70
49
  /**
71
50
  * Starts the Huddle gateway. Which images run (stable or experiment) is decided
72
51
  * by the caller via `images` (see resolveImages() in images.ts); this function
@@ -87,7 +66,6 @@ async function runInit(opts, images) {
87
66
  else {
88
67
  console.log((0, utils_1.dim)(`Pulling ${IMAGE}`));
89
68
  runArgs(rt, ['pull', IMAGE]);
90
- pullBaseImages(rt, images.baseImages.map((b) => b.image));
91
69
  }
92
70
  console.log((0, utils_1.dim)(`Volume: ${VOLUME}`));
93
71
  runArgsSilent(rt, ['volume', 'inspect', VOLUME]) || runArgs(rt, ['volume', 'create', VOLUME]);
@@ -180,6 +158,20 @@ async function runInit(opts, images) {
180
158
  dockerArgs.push(...(0, images_1.gatewayEnvArgs)(images));
181
159
  dockerArgs.push(IMAGE);
182
160
  runArgs(rt, dockerArgs);
161
+ // Devcontainer base images are built on this machine, not pulled. Non-blocking:
162
+ // init returns right away; a devcontainer that starts before the build is done
163
+ // waits for it in the gateway. HUDDLE_NO_BUILD=1 skips it (CI builds itself).
164
+ if (process.env.HUDDLE_NO_BUILD === '1') {
165
+ console.log((0, utils_1.dim)('HUDDLE_NO_BUILD=1 → not building devcontainer base images'));
166
+ }
167
+ else {
168
+ try {
169
+ (0, base_images_1.startBackgroundBuild)(rt, images.tag);
170
+ }
171
+ catch (err) {
172
+ console.log((0, utils_1.yellow)(`[!] Could not start the base-image build: ${err}. Run "huddle images build".`));
173
+ }
174
+ }
183
175
  // Attaching devcontainer-net after the container has started pollutes
184
176
  // resolv.conf on Podman with that network's internal aardvark-DNS; the
185
177
  // gateway cleans that up itself (see dns-egress.ts / the startup sanitize in
package/dist/start.js CHANGED
@@ -132,7 +132,9 @@ function parseIde(value) {
132
132
  return 'rider';
133
133
  if (normalized === 'vscode' || normalized === 'code')
134
134
  return 'vscode';
135
+ if (normalized === 'webstorm' || normalized === 'ws')
136
+ return 'webstorm';
135
137
  if (normalized === 'intellij' || normalized === 'intelij' || normalized === 'idea')
136
138
  return 'intellij';
137
- throw new Error(`Unknown IDE: ${value}. Choose intellij, rider, or vscode.`);
139
+ throw new Error(`Unknown IDE: ${value}. Choose intellij, rider, webstorm, or vscode.`);
138
140
  }
@@ -0,0 +1,344 @@
1
+ "use strict";
2
+ // Pure logic for `huddle triage-agent`: which PRs to triage, what the PR
3
+ // bumps, and turning the agent's analysis into the one PR comment. The agent
4
+ // read untrusted advisory text and upstream commits, so the CLI checks every
5
+ // field and writes the comment itself; nothing the agent wrote can add a
6
+ // link, a mention or markup. No I/O here, so it is unit-tested in cli/test/.
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.TRIAGE_MARKER = exports.SECURITY_BRANCH_PREFIX = exports.SECURITY_LABEL = void 0;
9
+ exports.decideTriage = decideTriage;
10
+ exports.lockfileBumps = lockfileBumps;
11
+ exports.advisoryIds = advisoryIds;
12
+ exports.parseLineCounts = parseLineCounts;
13
+ exports.extractTriageJson = extractTriageJson;
14
+ exports.parseTriage = parseTriage;
15
+ exports.renderComment = renderComment;
16
+ exports.renderPrivate = renderPrivate;
17
+ exports.ownCommentId = ownCommentId;
18
+ const update_agent_guard_1 = require("./update-agent-guard");
19
+ exports.SECURITY_LABEL = 'security';
20
+ /** Branches made by scripts/security-bump.sh. */
21
+ exports.SECURITY_BRANCH_PREFIX = 'security/';
22
+ /** First line of every triage comment, so a re-run updates it instead of adding another. */
23
+ exports.TRIAGE_MARKER = '<!-- huddle-triage-agent -->';
24
+ /**
25
+ * A PR labelled `security`, on a branch in this repository, that either
26
+ * Renovate opened (its vulnerability alerts) or that comes from a
27
+ * `security/*` branch (security-bump.sh, opened by a person).
28
+ */
29
+ function decideTriage(pr) {
30
+ const skip = (reason) => ({ action: 'skip', reason });
31
+ // A merged PR's branch is usually gone, and its analysis no longer helps a reviewer.
32
+ if (pr.state !== undefined && pr.state.toUpperCase() !== 'OPEN')
33
+ return skip(`the PR is ${pr.state.toLowerCase()}`);
34
+ if (!pr.labels.some((l) => l.name === exports.SECURITY_LABEL))
35
+ return skip(`not labelled ${exports.SECURITY_LABEL}`);
36
+ if (pr.isCrossRepository !== false)
37
+ return skip('not a branch in this repository');
38
+ const prefix = (0, update_agent_guard_1.renovateBranchPrefix)();
39
+ const fromRenovate = (0, update_agent_guard_1.isRenovatePrAuthor)(pr.author) && (0, update_agent_guard_1.isRenovateBranch)(pr.headRefName, prefix);
40
+ const fromBump = (0, update_agent_guard_1.isRenovateBranch)(pr.headRefName, exports.SECURITY_BRANCH_PREFIX);
41
+ if (!fromRenovate && !fromBump) {
42
+ return skip(`neither a ${prefix}* PR opened by ${(0, update_agent_guard_1.renovatePrAuthor)()} nor a ${exports.SECURITY_BRANCH_PREFIX}* branch`);
43
+ }
44
+ return { action: 'triage' };
45
+ }
46
+ // ── what the PR bumps ────────────────────────────────────────────────────────
47
+ const NPM_NAME = /^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/;
48
+ const VERSION = /^[0-9A-Za-z.+-]{1,64}$/;
49
+ const isNpmName = (s) => typeof s === 'string' && s.length <= 214 && NPM_NAME.test(s);
50
+ const isVersion = (s) => typeof s === 'string' && VERSION.test(s);
51
+ function lockVersions(lockfile, text) {
52
+ const out = new Map();
53
+ if (text === null)
54
+ return out;
55
+ let json;
56
+ try {
57
+ json = JSON.parse(text);
58
+ }
59
+ catch {
60
+ throw new Error(`${lockfile} is not a valid package-lock.json`);
61
+ }
62
+ for (const [key, entry] of Object.entries(json.packages ?? {})) {
63
+ const i = key.lastIndexOf('node_modules/');
64
+ if (i === -1)
65
+ continue;
66
+ const name = key.slice(i + 'node_modules/'.length);
67
+ if (!isNpmName(name) || !isVersion(entry?.version))
68
+ continue;
69
+ const set = out.get(name) ?? new Set();
70
+ set.add(entry.version);
71
+ out.set(name, set);
72
+ }
73
+ return out;
74
+ }
75
+ /** Packages whose versions differ between two versions of a package-lock.json (null: the file did not exist). */
76
+ function lockfileBumps(lockfile, before, after) {
77
+ const a = lockVersions(lockfile, before);
78
+ const b = lockVersions(lockfile, after);
79
+ const sorted = (s) => [...(s ?? [])].sort();
80
+ const bumps = [];
81
+ for (const name of [...new Set([...a.keys(), ...b.keys()])].sort()) {
82
+ const was = sorted(a.get(name));
83
+ const now = sorted(b.get(name));
84
+ if (was.join('\n') !== now.join('\n'))
85
+ bumps.push({ lockfile, name, before: was, after: now });
86
+ }
87
+ return bumps;
88
+ }
89
+ const GHSA = /\bGHSA(-[23456789cfghjmpqrvwx]{4}){3}\b/gi;
90
+ const CVE = /\bCVE-\d{4}-\d{4,7}\b/gi;
91
+ const GHSA_EXACT = /^GHSA(-[23456789cfghjmpqrvwx]{4}){3}$/;
92
+ const CVE_EXACT = /^CVE-\d{4}-\d{4,7}$/;
93
+ /** GHSA and CVE ids in a text (the PR title and body), normalised: `GHSA-` + lower case, `CVE-` upper case. */
94
+ function advisoryIds(text) {
95
+ const ids = [
96
+ ...[...text.matchAll(GHSA)].map((m) => `GHSA-${m[0].slice(5).toLowerCase()}`),
97
+ ...[...text.matchAll(CVE)].map((m) => m[0].toUpperCase()),
98
+ ];
99
+ return [...new Set(ids)].slice(0, 20);
100
+ }
101
+ const YNU = ['yes', 'no', 'unclear'];
102
+ const RECOMMENDATIONS = ['merge-low-urgency', 'merge-now', 'deep-dive'];
103
+ // No `@`: a file name in the link text must not become a mention.
104
+ const REPO_PATH = /^[A-Za-z0-9._+-]+(\/[A-Za-z0-9._+-]+)*$/;
105
+ const TEXT_MAX = 500;
106
+ /**
107
+ * Line counts per text file from `git grep -c -I -z '' <ref>`, which reads
108
+ * git's objects, not the checkout: lines of "<ref>:<path>\0<count>\n".
109
+ * Binary and empty files are not listed.
110
+ */
111
+ function parseLineCounts(output, ref = 'HEAD') {
112
+ const counts = new Map();
113
+ const prefix = `${ref}:`;
114
+ for (const m of output.matchAll(/([^\0]*)\0(\d+)\n/g)) {
115
+ const entry = m[1].replace(/^\n/, '');
116
+ if (entry.startsWith(prefix))
117
+ counts.set(entry.slice(prefix.length), Number(m[2]));
118
+ }
119
+ return counts;
120
+ }
121
+ /**
122
+ * The JSON of the agent's final answer, for when it could not write
123
+ * triage.json: the answer itself, or its first ```json block. '' if none.
124
+ */
125
+ function extractTriageJson(answer) {
126
+ const fenced = /```(?:json)?\s*\n([\s\S]*?)\n\s*```/.exec(answer);
127
+ if (fenced)
128
+ return fenced[1].trim();
129
+ const t = answer.trim();
130
+ return t.startsWith('{') ? t : '';
131
+ }
132
+ /**
133
+ * Checks the agent's triage.json. Files must be text files in the PR, and
134
+ * line ranges must lie inside them (lineCounts, read by the CLI before the
135
+ * agent ran). Error messages never quote the agent's values, so they are
136
+ * safe to show.
137
+ */
138
+ function parseTriage(text, lineCounts) {
139
+ let raw;
140
+ try {
141
+ raw = JSON.parse(text);
142
+ }
143
+ catch {
144
+ return { ok: false, errors: ['triage.json is not valid JSON'] };
145
+ }
146
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
147
+ return { ok: false, errors: ['triage.json is not a JSON object'] };
148
+ const o = raw;
149
+ const errors = [];
150
+ const str = (key, max = TEXT_MAX, value = o[key]) => {
151
+ if (typeof value !== 'string' || value.length > max) {
152
+ errors.push(`${key} must be a string of at most ${max} characters`);
153
+ return '';
154
+ }
155
+ return value;
156
+ };
157
+ const oneOf = (key, allowed) => {
158
+ if (typeof o[key] !== 'string' || !allowed.includes(o[key]))
159
+ errors.push(`${key} must be one of ${allowed.join(', ')}`);
160
+ return o[key];
161
+ };
162
+ const list = (key, max, min = 0) => {
163
+ const v = o[key];
164
+ if (!Array.isArray(v) || v.length < min || v.length > max) {
165
+ errors.push(`${key} must be an array of ${min}-${max} entries`);
166
+ return [];
167
+ }
168
+ return v;
169
+ };
170
+ const packages = list('packages', 10, 1).map((p, i) => {
171
+ const e = (p ?? {});
172
+ if (!isNpmName(e.name) || !isVersion(e.from) || !isVersion(e.to))
173
+ errors.push(`packages[${i}] needs an npm name and plain from/to versions`);
174
+ return { name: String(e.name), from: String(e.from), to: String(e.to) };
175
+ });
176
+ const advisories = list('advisories', 20).map((a, i) => {
177
+ if (typeof a !== 'string' || !(GHSA_EXACT.test(a) || CVE_EXACT.test(a)))
178
+ errors.push(`advisories[${i}] must be a GHSA-… or CVE-… id`);
179
+ return String(a);
180
+ });
181
+ const usage = list('usage', 30).map((u, i) => {
182
+ const e = (u ?? {});
183
+ const file = typeof e.file === 'string' ? e.file : '';
184
+ if (!REPO_PATH.test(file) || file.split('/').some((s) => s === '.' || s === '..') || file.length > 300) {
185
+ errors.push(`usage[${i}].file must be a path relative to the repository root`);
186
+ }
187
+ else if (!lineCounts.has(file)) {
188
+ errors.push(`usage[${i}].file is not a text file in the PR`);
189
+ }
190
+ const lines = lineCounts.get(file) ?? 1_000_000;
191
+ const okLine = (n) => Number.isInteger(n) && n >= 1 && n <= lines;
192
+ if (!okLine(e.startLine) || !okLine(e.endLine) || e.startLine > e.endLine) {
193
+ errors.push(`usage[${i}] needs lines with 1 <= startLine <= endLine <= the file's length`);
194
+ }
195
+ return { file, startLine: Number(e.startLine), endLine: Number(e.endLine), note: str(`usage[${i}].note`, 200, e.note) };
196
+ });
197
+ const affected = oneOf('affected', YNU);
198
+ const reachable = oneOf('reachable', YNU);
199
+ const recommendation = oneOf('recommendation', RECOMMENDATIONS);
200
+ const reachableReason = str('reachableReason');
201
+ const breakingChanges = str('breakingChanges');
202
+ if (typeof o.beyondAdvisory !== 'boolean')
203
+ errors.push('beyondAdvisory must be true or false');
204
+ const beyondAdvisory = o.beyondAdvisory === true;
205
+ const privateDetails = o.privateDetails === undefined ? '' : str('privateDetails', 20_000);
206
+ if (errors.length)
207
+ return { ok: false, errors };
208
+ return { ok: true, report: { packages, advisories, affected, usage, reachable, reachableReason, breakingChanges, recommendation, beyondAdvisory, privateDetails } };
209
+ }
210
+ // ── the comment ──────────────────────────────────────────────────────────────
211
+ /** Agent text as an inline code span: one line, capped, no backticks, so nothing in it renders. */
212
+ function inert(text, max = TEXT_MAX) {
213
+ const flat = text.replace(/\s+/g, ' ').trim().replace(/`/g, "'").slice(0, max);
214
+ return flat ? `\`${flat}\`` : '';
215
+ }
216
+ /**
217
+ * A package name or version as an inline code span. Valid npm names and
218
+ * versions can still render as text: `@scope/x` as a mention, `www.x.com` as
219
+ * a link, `GH-1` as an issue reference.
220
+ */
221
+ const code = (s) => `\`${s.replace(/`/g, "'")}\``;
222
+ function advisoryLink(id) {
223
+ return GHSA_EXACT.test(id) ? `[${id}](https://github.com/advisories/${id})` : id;
224
+ }
225
+ function headline(packages, advisories) {
226
+ const pkgs = packages.length ? packages.slice(0, 3).map((p) => `${code(p.name)} ${code(p.from)} → ${code(p.to)}`).join(', ') : 'this PR';
227
+ const more = packages.length > 3 ? ` and ${packages.length - 3} more` : '';
228
+ // GHSA ids first: they link to the advisory. A CVE id only adds a name for the same issue.
229
+ const ordered = [...advisories.filter((a) => GHSA_EXACT.test(a)), ...advisories.filter((a) => !GHSA_EXACT.test(a))];
230
+ const moreIds = ordered.length > 5 ? `, +${ordered.length - 5} more` : '';
231
+ const ids = ordered.length ? ` (${ordered.slice(0, 5).map(advisoryLink).join(', ')}${moreIds})` : '';
232
+ return `### Security triage: ${pkgs}${more}${ids}`;
233
+ }
234
+ /**
235
+ * The packages the PR changed, as the headline shows them when the agent gave
236
+ * no valid report. Packages the PR title names come first ("update dependency
237
+ * node-forge to v1.3.2", or a security-bump.sh branch), so a transitive bump
238
+ * does not push the vulnerable package out of the headline.
239
+ */
240
+ function bumpPackages(bumps, title = '') {
241
+ const seen = new Map();
242
+ for (const b of bumps) {
243
+ if (!b.before.length || !b.after.length || seen.has(b.name))
244
+ continue;
245
+ seen.set(b.name, { name: b.name, from: b.before.join('/'), to: b.after.join('/') });
246
+ }
247
+ const words = new Set(title.toLowerCase().split(/[\s,;:()[\]]+/));
248
+ const named = (p) => words.has(p.name.toLowerCase());
249
+ const all = [...seen.values()];
250
+ return [...all.filter(named), ...all.filter((p) => !named(p))];
251
+ }
252
+ /** An answer whose recommendation does not follow from its own analysis. */
253
+ function contradicts(r) {
254
+ return r.reachable === 'yes' && (r.affected === 'no' || r.recommendation === 'merge-low-urgency');
255
+ }
256
+ const RECOMMENDATION_TEXT = {
257
+ 'merge-low-urgency': 'merge (low urgency)',
258
+ 'merge-now': 'merge now',
259
+ 'deep-dive': 'needs a human deep-dive',
260
+ };
261
+ /** The PR comment, in the fixed format of the design doc. ` ` ends a line without starting a paragraph. */
262
+ function renderComment(c) {
263
+ const footer = [
264
+ ...c.facts,
265
+ '',
266
+ `<sub>${c.runner} with \`huddle triage-agent\` inside an airlocked Huddle devcontainer. ` +
267
+ 'It read untrusted advisory text and upstream commits. It recommends; it never approves or merges, and a person decides.</sub>',
268
+ ];
269
+ const deepDive = `**Recommendation:** ${RECOMMENDATION_TEXT['deep-dive']}`;
270
+ const r = c.report;
271
+ if (!r) {
272
+ return [
273
+ exports.TRIAGE_MARKER,
274
+ headline(bumpPackages(c.bumps, c.title), c.advisories ?? []),
275
+ '',
276
+ `**Affected:** unclear (${c.problem ?? 'no analysis'}) `,
277
+ `${deepDive}: do the full manual review from the security fast lane.`,
278
+ ...footer,
279
+ ].join('\n');
280
+ }
281
+ if (r.beyondAdvisory) {
282
+ return [
283
+ exports.TRIAGE_MARKER,
284
+ headline(r.packages, r.advisories),
285
+ '',
286
+ `${deepDive}. The analysis goes beyond what the advisory says: details sent to maintainers, not posted here.`,
287
+ ...footer,
288
+ ].join('\n');
289
+ }
290
+ const lines = (u) => (u.startLine === u.endLine ? `L${u.startLine}` : `L${u.startLine}-L${u.endLine}`);
291
+ const blobUrl = (u) => `https://github.com/${c.repo}/blob/${c.headSha}/${u.file}#${lines(u)}`;
292
+ const usage = r.usage.length
293
+ ? r.usage.map((u) => `[${u.file}:${lines(u)}](${blobUrl(u)})${u.note.trim() ? ` ${inert(u.note, 200)}` : ''}`).join('; ')
294
+ : 'none found';
295
+ const unclear = r.affected === 'unclear' || r.reachable === 'unclear';
296
+ const recommendation = unclear
297
+ ? `${deepDive}: the agent could not settle this, so do the full manual review from the security fast lane.`
298
+ : contradicts(r)
299
+ ? `${deepDive}: the agent's own analysis contradicts its recommendation (${RECOMMENDATION_TEXT[r.recommendation]}), so do the full manual review.`
300
+ : `**Recommendation:** ${RECOMMENDATION_TEXT[r.recommendation]}`;
301
+ return [
302
+ exports.TRIAGE_MARKER,
303
+ headline(r.packages, r.advisories),
304
+ `**Affected:** ${r.affected} `,
305
+ `**Our usage:** ${usage} `,
306
+ `**Reachable from a devcontainer:** ${r.reachable}${r.reachableReason.trim() ? `, ${inert(r.reachableReason)}` : ''} `,
307
+ `**Breaking changes in the bump:** ${inert(r.breakingChanges) || 'not reported'} `,
308
+ recommendation,
309
+ ...footer,
310
+ ].join('\n');
311
+ }
312
+ /** The full analysis for maintainers (never posted publicly). */
313
+ function renderPrivate(r, pr) {
314
+ return [
315
+ `# Triage agent: ${pr.repo} PR #${pr.number}`,
316
+ '',
317
+ `PR title: ${pr.title}`,
318
+ `Packages: ${r.packages.map((p) => `${p.name} ${p.from} -> ${p.to}`).join(', ')}`,
319
+ `Advisories: ${r.advisories.join(', ') || 'none given'}`,
320
+ `Affected: ${r.affected}`,
321
+ `Usage: ${r.usage.map((u) => `${u.file}:L${u.startLine}-L${u.endLine} ${u.note}`).join('; ') || 'none found'}`,
322
+ `Reachable: ${r.reachable}, ${r.reachableReason}`,
323
+ `Breaking changes: ${r.breakingChanges}`,
324
+ `Recommendation: ${r.recommendation}`,
325
+ '',
326
+ '## Beyond the advisory',
327
+ '',
328
+ r.privateDetails || '(no details given)',
329
+ '',
330
+ ].join('\n');
331
+ }
332
+ /**
333
+ * The id of the newest marked comment by `login`, from lines of
334
+ * "<id>\t<login>" (the CLI lists comments that start with TRIAGE_MARKER).
335
+ */
336
+ function ownCommentId(lines, login) {
337
+ let id = null;
338
+ for (const line of lines.split('\n')) {
339
+ const [cid, who] = line.split('\t');
340
+ if (/^\d+$/.test(cid ?? '') && who === login)
341
+ id = cid;
342
+ }
343
+ return id;
344
+ }