@imdeadpool/guardex 8.4.0 → 8.4.2
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/CONTRIBUTING.md +13 -4
- package/README.md +223 -1
- package/THIRD-PARTY-NOTICES.md +29 -0
- package/bin/multiagent-safety.js +9 -12
- package/package.json +4 -2
- package/skills/gitguardex/SKILL.md +28 -0
- package/skills/pr-lens/SKILL.md +87 -0
- package/src/abide.js +534 -0
- package/src/agents/activity.js +23 -4
- package/src/agents/inspect.js +15 -6
- package/src/agents/launch.js +6 -1
- package/src/agents/process-lease.js +84 -0
- package/src/agents/sessions.js +96 -16
- package/src/agents/start.js +18 -9
- package/src/agents/status.js +35 -14
- package/src/agents/supervise.js +87 -0
- package/src/budget/index.js +6 -1
- package/src/cli/args.js +71 -77
- package/src/cli/commands/agents.js +38 -10
- package/src/cli/commands/branch.js +116 -103
- package/src/cli/commands/claude.js +604 -50
- package/src/cli/commands/codex.js +359 -0
- package/src/cli/commands/context.js +52 -0
- package/src/cli/commands/mcp.js +5 -1
- package/src/cli/commands/pr.js +138 -3
- package/src/cli/commands/review.js +3 -1
- package/src/cli/commands/setup.js +25 -0
- package/src/cli/commands/status.js +128 -60
- package/src/cli/commands/storage.js +24 -0
- package/src/cli/commands/usage.js +48 -0
- package/src/cli/commands/watch.js +157 -47
- package/src/cli/commands/worktree-copy-ignored.js +38 -0
- package/src/cli/commands/worktree-estimate.js +69 -0
- package/src/cli/commands/worktree-hooks.js +62 -0
- package/src/cli/commands/worktree-navigation.js +71 -0
- package/src/cli/commands/worktree-provision.js +92 -0
- package/src/cli/main.js +229 -110
- package/src/cli/shared/gate-flags.js +131 -0
- package/src/cli/shared/scaffolding.js +31 -3
- package/src/cli/shared-locks.js +3 -1
- package/src/cockpit/pane-actions.js +43 -7
- package/src/context.js +373 -17
- package/src/doctor/index.js +29 -35
- package/src/finish/events.js +254 -0
- package/src/finish/index.js +322 -62
- package/src/finish/post-branch-finish-cleanup.js +316 -22
- package/src/finish/preflight.js +44 -1
- package/src/finish/progress.js +36 -0
- package/src/finish/review-gate.js +317 -127
- package/src/finish/review-receipt.js +156 -0
- package/src/finish/with-claims-lock.py +29 -0
- package/src/git/index.js +179 -42
- package/src/hooks/index.js +68 -3
- package/src/mcp/collect.js +61 -5
- package/src/mcp/server.js +4 -0
- package/src/output/index.js +167 -1
- package/src/pr-lens-publish.js +93 -0
- package/src/pr-lens.js +184 -0
- package/src/pr-respond.js +860 -0
- package/src/pr-review.js +519 -159
- package/src/pr.js +73 -14
- package/src/provider-binary.js +21 -0
- package/src/review-diff-context.js +90 -0
- package/src/review-fix.js +23 -17
- package/src/scaffold/agent-worktree-prep.js +14 -12
- package/src/scaffold/dependency-store.js +234 -0
- package/src/scaffold/index.js +13 -1
- package/src/scaffold/provision-approvals.js +83 -0
- package/src/scaffold/provision-config.js +169 -40
- package/src/shared-git-state.js +11 -1
- package/src/speckit/index.js +12 -1
- package/src/storage/run-artifacts.js +185 -0
- package/src/toolchain/index.js +322 -2
- package/src/worktree-copy-ignored.js +200 -0
- package/src/worktree-hook-worker.js +29 -0
- package/src/worktree-hooks.js +333 -0
- package/src/worktree-navigation.js +248 -0
- package/src/worktree-picker.js +89 -0
- package/src/worktree-quota.js +100 -0
- package/src/worktree-start.js +100 -0
- package/templates/AGENTS.multiagent-safety.md +8 -0
- package/templates/AGENTS.multiagent-safety.min.md +3 -1
- package/templates/codex/skills/gitguardex/SKILL.md +28 -0
- package/templates/codex/skills/opensrc/SKILL.md +24 -0
- package/templates/githooks/post-merge +16 -2
- package/templates/scripts/agent-autofinish-watch.sh +17 -18
- package/templates/scripts/agent-branch-finish.sh +180 -19
- package/templates/scripts/agent-branch-merge.sh +7 -32
- package/templates/scripts/agent-branch-start.sh +202 -43
- package/templates/scripts/agent-claude-stop-finish.sh +4 -27
- package/templates/scripts/agent-file-locks.py +257 -29
- package/templates/scripts/agent-preflight.sh +3 -0
- package/templates/scripts/agent-worktree-prune.sh +975 -63
- package/templates/scripts/codex-agent.sh +55 -5
- package/templates/scripts/lib/guardex-base-branch.sh +207 -0
- package/templates/scripts/openspec/init-change-workspace.sh +10 -18
- package/templates/scripts/review-bot-watch.sh +171 -4
package/src/mcp/server.js
CHANGED
|
@@ -77,6 +77,7 @@ const TOOLS = [
|
|
|
77
77
|
description: 'Files intended for editing.',
|
|
78
78
|
},
|
|
79
79
|
include_prs: { type: 'boolean', description: 'Fetch PRs. Default false.' },
|
|
80
|
+
max_bytes: { type: 'integer', minimum: 1, maximum: 1048576, description: 'Optional JSON text byte budget. Mandatory safety data never truncated.' },
|
|
80
81
|
},
|
|
81
82
|
},
|
|
82
83
|
},
|
|
@@ -140,6 +141,9 @@ function callTool(name, args = {}) {
|
|
|
140
141
|
return collect.whoOwns(args.file, { repoPath: args.repo });
|
|
141
142
|
case 'my_context': {
|
|
142
143
|
const includePrs = args.include_prs === true;
|
|
144
|
+
if (args.max_bytes !== undefined) {
|
|
145
|
+
return collect.editContext({ files: args.files || [], includePrs, maxBytes: args.max_bytes });
|
|
146
|
+
}
|
|
143
147
|
if (Array.isArray(args.files) && args.files.length > 0) {
|
|
144
148
|
return collect.editContext({ files: args.files, includePrs });
|
|
145
149
|
}
|
package/src/output/index.js
CHANGED
|
@@ -9,6 +9,7 @@ const {
|
|
|
9
9
|
GUARDEX_REPO_TOGGLE_ENV,
|
|
10
10
|
CLI_COMMAND_DESCRIPTIONS,
|
|
11
11
|
CLI_COMMAND_GROUPS,
|
|
12
|
+
CLI_COMMAND_HELP,
|
|
12
13
|
CLI_QUICKSTART_STEPS,
|
|
13
14
|
AGENT_BOT_DESCRIPTIONS,
|
|
14
15
|
DOCTOR_AUTO_FINISH_DETAIL_LIMIT,
|
|
@@ -243,6 +244,164 @@ function groupedCommandCatalogLines(indent = ' ', options = {}) {
|
|
|
243
244
|
return lines;
|
|
244
245
|
}
|
|
245
246
|
|
|
247
|
+
// ---------------------------------------------------------------------------
|
|
248
|
+
// Machine- and agent-facing help.
|
|
249
|
+
//
|
|
250
|
+
// `gx --help --json` emits the whole catalog as one JSON object so a caller
|
|
251
|
+
// can enumerate commands, subcommands and flags without scraping prose — and
|
|
252
|
+
// so a renamed or added command shows up without anybody updating a scraper.
|
|
253
|
+
// ---------------------------------------------------------------------------
|
|
254
|
+
// CLI_COMMAND_HELP is a plain object, so a bare lookup resolves prototype
|
|
255
|
+
// keys: `CLI_COMMAND_HELP['constructor']` is a function, and rendering it
|
|
256
|
+
// produced help for a command that does not exist.
|
|
257
|
+
function helpEntry(command) {
|
|
258
|
+
return Object.hasOwn(CLI_COMMAND_HELP, command) ? CLI_COMMAND_HELP[command] : undefined;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function commandCatalogJson() {
|
|
262
|
+
const invoked = getInvokedCliName();
|
|
263
|
+
const entryFor = (name) => {
|
|
264
|
+
const key = String(name).split(/\s+/)[0];
|
|
265
|
+
const help = helpEntry(key) || {};
|
|
266
|
+
if (help.nativeHelp) {
|
|
267
|
+
return {
|
|
268
|
+
nativeHelp: true,
|
|
269
|
+
helpCommand: `${invoked} ${key} --help`,
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
return {
|
|
273
|
+
nativeHelp: false,
|
|
274
|
+
usage: help.usage ? help.usage.replace(/^gx\b/, invoked) : `${invoked} ${key} [options]`,
|
|
275
|
+
summary: help.summary || null,
|
|
276
|
+
subcommands: (help.subcommands || []).map(([n, d]) => ({ name: n, description: d })),
|
|
277
|
+
flags: (help.flags || []).map(([f, d]) => ({ flag: f, description: d })),
|
|
278
|
+
examples: (help.examples || []).map((e) => e.replace(/^gx\b/, invoked)),
|
|
279
|
+
notes: help.notes || [],
|
|
280
|
+
};
|
|
281
|
+
};
|
|
282
|
+
return {
|
|
283
|
+
cli: invoked,
|
|
284
|
+
version: packageJson.version,
|
|
285
|
+
runtime: runtimeVersion(),
|
|
286
|
+
groups: CLI_COMMAND_GROUPS.map((group) => ({
|
|
287
|
+
label: group.label,
|
|
288
|
+
description: group.description || null,
|
|
289
|
+
commands: group.commands.map(([name, description]) => {
|
|
290
|
+
const key = String(name).split(/\s+/)[0];
|
|
291
|
+
return { name: key, description, ...entryFor(name) };
|
|
292
|
+
}),
|
|
293
|
+
})),
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
// Per-command help for every command that does not print its own usage, so
|
|
298
|
+
// `--help` ALWAYS answers and ALWAYS exits 0. Shape follows the house style
|
|
299
|
+
// `gx cleanup --help` already set: USAGE, prose, then the sections that apply.
|
|
300
|
+
function commandHelpLines(command, options = {}) {
|
|
301
|
+
const invoked = options.invokedBasename || getInvokedCliName();
|
|
302
|
+
const localize = (text) => String(text).replace(/\bgx\b/g, invoked);
|
|
303
|
+
const help = helpEntry(command);
|
|
304
|
+
const lines = [];
|
|
305
|
+
|
|
306
|
+
let catalogDescription = null;
|
|
307
|
+
let groupLabel = null;
|
|
308
|
+
for (const group of CLI_COMMAND_GROUPS) {
|
|
309
|
+
for (const [name, description] of group.commands) {
|
|
310
|
+
if (String(name).split(/\s+/)[0] === command) {
|
|
311
|
+
catalogDescription = description;
|
|
312
|
+
groupLabel = group.label;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
lines.push(`USAGE: ${localize(help && help.usage ? help.usage : `gx ${command} [options]`)}`);
|
|
318
|
+
const summary = (help && help.summary) || catalogDescription;
|
|
319
|
+
if (summary) {
|
|
320
|
+
lines.push('');
|
|
321
|
+
for (const line of wrapHelpText(localize(summary), 76)) lines.push(` ${line}`);
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
const pad = (rows) => {
|
|
325
|
+
const width = Math.max(0, ...rows.map(([left]) => left.length));
|
|
326
|
+
const out = [];
|
|
327
|
+
for (const [left, right] of rows) {
|
|
328
|
+
const gap = width + 2;
|
|
329
|
+
if (left.length > 30) {
|
|
330
|
+
out.push(` ${left}`);
|
|
331
|
+
for (const line of wrapHelpText(localize(right), 74 - gap)) {
|
|
332
|
+
out.push(` ${' '.repeat(gap)}${line}`);
|
|
333
|
+
}
|
|
334
|
+
continue;
|
|
335
|
+
}
|
|
336
|
+
const wrapped = wrapHelpText(localize(right), 74 - gap);
|
|
337
|
+
out.push(` ${left.padEnd(width)} ${wrapped[0] || ''}`.trimEnd());
|
|
338
|
+
for (const line of wrapped.slice(1)) out.push(` ${' '.repeat(gap)}${line}`);
|
|
339
|
+
}
|
|
340
|
+
return out;
|
|
341
|
+
};
|
|
342
|
+
|
|
343
|
+
if (help && help.subcommands && help.subcommands.length) {
|
|
344
|
+
lines.push('');
|
|
345
|
+
lines.push('SUBCOMMANDS');
|
|
346
|
+
for (const line of pad(help.subcommands)) lines.push(line);
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
if (help && help.flags && help.flags.length) {
|
|
350
|
+
lines.push('');
|
|
351
|
+
lines.push('OPTIONS');
|
|
352
|
+
for (const line of pad(help.flags)) lines.push(line);
|
|
353
|
+
lines.push('');
|
|
354
|
+
lines.push(' Not every accepted flag is listed — these are the ones worth knowing');
|
|
355
|
+
lines.push(' first. Anything unlisted is still parsed.');
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
if (help && help.examples && help.examples.length) {
|
|
359
|
+
lines.push('');
|
|
360
|
+
lines.push('EXAMPLES');
|
|
361
|
+
for (const example of help.examples) lines.push(` ${localize(example)}`);
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
if (help && help.notes && help.notes.length) {
|
|
365
|
+
lines.push('');
|
|
366
|
+
lines.push('NOTES');
|
|
367
|
+
for (const note of help.notes) {
|
|
368
|
+
const wrapped = wrapHelpText(localize(note), 72);
|
|
369
|
+
lines.push(` - ${wrapped[0] || ''}`);
|
|
370
|
+
for (const line of wrapped.slice(1)) lines.push(` ${line}`);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
lines.push('');
|
|
375
|
+
if (groupLabel) lines.push(` Group: ${groupLabel}`);
|
|
376
|
+
lines.push(` ${invoked} --help every command, grouped`);
|
|
377
|
+
lines.push(` ${invoked} --help --json the same catalog as JSON`);
|
|
378
|
+
return lines;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
// Word wrap for help bodies. Long unbreakable tokens (paths, flags) are left
|
|
382
|
+
// alone rather than hyphenated, so a wrapped line can exceed `width`.
|
|
383
|
+
function wrapHelpText(text, width) {
|
|
384
|
+
const limit = Math.max(24, Number(width) || 72);
|
|
385
|
+
const words = String(text).split(/\s+/).filter(Boolean);
|
|
386
|
+
if (!words.length) return [''];
|
|
387
|
+
const out = [];
|
|
388
|
+
let line = '';
|
|
389
|
+
for (const word of words) {
|
|
390
|
+
if (!line) {
|
|
391
|
+
line = word;
|
|
392
|
+
continue;
|
|
393
|
+
}
|
|
394
|
+
if (line.length + 1 + word.length <= limit) {
|
|
395
|
+
line += ` ${word}`;
|
|
396
|
+
continue;
|
|
397
|
+
}
|
|
398
|
+
out.push(line);
|
|
399
|
+
line = word;
|
|
400
|
+
}
|
|
401
|
+
if (line) out.push(line);
|
|
402
|
+
return out;
|
|
403
|
+
}
|
|
404
|
+
|
|
246
405
|
function quickstartLines(indent = ' ') {
|
|
247
406
|
return CLI_QUICKSTART_STEPS.map((step, index) => `${indent}${index + 1}. ${step}`);
|
|
248
407
|
}
|
|
@@ -378,7 +537,10 @@ function usage(options = {}) {
|
|
|
378
537
|
.join('\n');
|
|
379
538
|
console.log(`USAGE: ${invoked} <command> [options]
|
|
380
539
|
COMMANDS
|
|
381
|
-
${groupedCommandLinesTerse}
|
|
540
|
+
${groupedCommandLinesTerse}
|
|
541
|
+
HELP
|
|
542
|
+
${invoked} <command> --help one command: usage, subcommands, main flags
|
|
543
|
+
${invoked} --help --json the whole catalog as JSON, in one call`);
|
|
382
544
|
if (outsideGitRepo) {
|
|
383
545
|
console.log(
|
|
384
546
|
`[${TOOL_NAME}] No git repository detected. Re-run from a repo root or pass --target <path>.`,
|
|
@@ -420,6 +582,8 @@ NOTES
|
|
|
420
582
|
- Target another repo: ${invoked} <cmd> --target <repo-path>.
|
|
421
583
|
- On protected main, setup/install/fix/doctor auto-sandbox via agent branch + PR flow.
|
|
422
584
|
- Run '${invoked} cleanup' to prune merged agent branches/worktrees.
|
|
585
|
+
- Per-command help: ${invoked} <command> --help (or ${invoked} help <command>).
|
|
586
|
+
- Machine-readable catalog: ${invoked} --help --json.
|
|
423
587
|
- Legacy aliases: ${LEGACY_NAMES.join(', ')}.`);
|
|
424
588
|
|
|
425
589
|
if (outsideGitRepo) {
|
|
@@ -845,6 +1009,8 @@ function printCompressible(text, options = {}) {
|
|
|
845
1009
|
}
|
|
846
1010
|
|
|
847
1011
|
module.exports = {
|
|
1012
|
+
commandCatalogJson,
|
|
1013
|
+
commandHelpLines,
|
|
848
1014
|
runtimeVersion,
|
|
849
1015
|
supportsAnsiColors,
|
|
850
1016
|
isTerseMode,
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
const _ctx = require('./context');
|
|
2
|
+
const { readPrLensMetadata } = require('./pr-lens');
|
|
3
|
+
|
|
4
|
+
const MARKER = '<!-- gitguardex:pr-lens-artifact -->';
|
|
5
|
+
|
|
6
|
+
// Publish an already-uploaded artifact, never upload source or SVGs to a public
|
|
7
|
+
// host. Authentication and private-repo access remain GitHub's responsibility.
|
|
8
|
+
function publishPrLensArtifact(pr, artifactUrl, repoRoot, runner) {
|
|
9
|
+
const metadata = readPrLensMetadata(pr, repoRoot, runner);
|
|
10
|
+
const { repo, head, pullRequest } = metadata.provenance;
|
|
11
|
+
const url = new URL(artifactUrl);
|
|
12
|
+
const match = url.pathname.match(
|
|
13
|
+
/^\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)\/actions\/runs\/([1-9]\d*)\/artifacts\/([1-9]\d*)$/
|
|
14
|
+
);
|
|
15
|
+
if (
|
|
16
|
+
url.protocol !== 'https:' ||
|
|
17
|
+
url.host !== repo.host ||
|
|
18
|
+
url.username ||
|
|
19
|
+
url.password ||
|
|
20
|
+
url.search ||
|
|
21
|
+
url.hash ||
|
|
22
|
+
!match ||
|
|
23
|
+
`${match[1]}/${match[2]}`.toLowerCase() !== `${repo.owner}/${repo.name}`.toLowerCase()
|
|
24
|
+
) {
|
|
25
|
+
throw new Error(
|
|
26
|
+
'PR Lens publication requires a GitHub Actions artifact URL from this PR repository'
|
|
27
|
+
);
|
|
28
|
+
}
|
|
29
|
+
const api = (endpoint, extra = [], body) => {
|
|
30
|
+
const result = runner(
|
|
31
|
+
_ctx.GH_BIN,
|
|
32
|
+
['api', '--hostname', repo.host, endpoint, ...extra, ...(body ? ['--input', '-'] : [])],
|
|
33
|
+
{ cwd: repoRoot, timeout: 30_000, ...(body ? { input: JSON.stringify(body) } : {}) }
|
|
34
|
+
);
|
|
35
|
+
if (result.error || result.status !== 0)
|
|
36
|
+
throw new Error(`PR Lens publication API failed: ${endpoint}`);
|
|
37
|
+
return JSON.parse(result.stdout);
|
|
38
|
+
};
|
|
39
|
+
const prefix = `repos/${repo.owner}/${repo.name}`;
|
|
40
|
+
const artifact = api(`${prefix}/actions/artifacts/${match[4]}`);
|
|
41
|
+
if (
|
|
42
|
+
String(artifact.id) !== match[4] ||
|
|
43
|
+
artifact.expired !== false ||
|
|
44
|
+
String(artifact.workflow_run?.id) !== match[3] ||
|
|
45
|
+
artifact.workflow_run?.head_sha !== head.sha
|
|
46
|
+
) {
|
|
47
|
+
throw new Error(
|
|
48
|
+
'PR Lens artifact is expired or does not belong to the current PR head and workflow run'
|
|
49
|
+
);
|
|
50
|
+
}
|
|
51
|
+
// Require a verified user identity; do not trust a marker copied by another
|
|
52
|
+
// author. Tokens without a user identity fail closed rather than guessing.
|
|
53
|
+
const viewer = api('user');
|
|
54
|
+
if (!Number.isSafeInteger(viewer.id) || viewer.id <= 0)
|
|
55
|
+
throw new Error('PR Lens cannot verify the comment author');
|
|
56
|
+
const pages = api(`${prefix}/issues/${pr}/comments?per_page=100`, ['--paginate', '--slurp']);
|
|
57
|
+
if (!Array.isArray(pages) || !pages.every(Array.isArray))
|
|
58
|
+
throw new Error('PR Lens could not list comments');
|
|
59
|
+
const existing = pages
|
|
60
|
+
.flat()
|
|
61
|
+
.find(
|
|
62
|
+
(comment) =>
|
|
63
|
+
comment.user?.id === viewer.id &&
|
|
64
|
+
typeof comment.body === 'string' &&
|
|
65
|
+
comment.body.startsWith(`${MARKER}\n`) &&
|
|
66
|
+
Number.isSafeInteger(comment.id) &&
|
|
67
|
+
comment.id > 0
|
|
68
|
+
);
|
|
69
|
+
if (JSON.stringify(readPrLensMetadata(pr, repoRoot, runner)) !== JSON.stringify(metadata)) {
|
|
70
|
+
throw new Error('PR changed before publishing its PR Lens artifact');
|
|
71
|
+
}
|
|
72
|
+
const body = [
|
|
73
|
+
MARKER,
|
|
74
|
+
'### PR Lens diagrams',
|
|
75
|
+
'',
|
|
76
|
+
`[Download the diagram artifact](${url.href})`,
|
|
77
|
+
'',
|
|
78
|
+
`PR #${pr} · commit \`${head.sha}\``,
|
|
79
|
+
'',
|
|
80
|
+
'Access follows repository permissions; the artifact expires according to its retention policy.',
|
|
81
|
+
'This link is not a code-review or merge verdict.'
|
|
82
|
+
].join('\n');
|
|
83
|
+
const result = api(
|
|
84
|
+
existing ? `${prefix}/issues/comments/${existing.id}` : `${prefix}/issues/${pr}/comments`,
|
|
85
|
+
['--method', existing ? 'PATCH' : 'POST'],
|
|
86
|
+
{ body }
|
|
87
|
+
);
|
|
88
|
+
if (!Number.isSafeInteger(result.id) || result.id <= 0)
|
|
89
|
+
throw new Error('PR Lens comment response has no ID');
|
|
90
|
+
return `${pullRequest.url}#issuecomment-${result.id}`;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
module.exports = { publishPrLensArtifact };
|
package/src/pr-lens.js
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
const fs = require('node:fs');
|
|
2
|
+
const path = require('node:path');
|
|
3
|
+
const { GH_BIN } = require('./context');
|
|
4
|
+
const { createRun, writeRunFile, completeRun } = require('./storage/run-artifacts');
|
|
5
|
+
|
|
6
|
+
// PR Lens 0.6.1 / graph schema 0.2.0. Keep inference in our existing tool-free
|
|
7
|
+
// reviewer; only validation and rendering run in the external CLI (no model API).
|
|
8
|
+
const GRAPH_PROMPT = [
|
|
9
|
+
'Also return a "graph" object alongside "findings" for PR Lens schema 0.2.0.',
|
|
10
|
+
'Graph shape: {"title":"Short change title","summary":"What changes",',
|
|
11
|
+
'"lenses":["architecture"],"lanes":[{"id":"app","label":"Application"}],',
|
|
12
|
+
'"nodes":[{"id":"module","label":"Module","kind":"module","delta":"modified",',
|
|
13
|
+
'"lane":"app","files":[{"path":"src/module.js"}]}],"edges":[],"flows":[]}.',
|
|
14
|
+
'Replace the example with entities evidenced by this diff; never invent unseen architecture.',
|
|
15
|
+
'Do not emit provenance, stats, schemaVersion or kind at graph level; the runner supplies them.',
|
|
16
|
+
'Use 1-16 lanes, 1-256 nodes and up to 512 edges. IDs: [A-Za-z0-9][A-Za-z0-9._:/-]*, max 128 chars.',
|
|
17
|
+
'Node kind: service|app|module|function|route|job|queue|datastore|cache|external|ui|config|test|package|other.',
|
|
18
|
+
'Delta on nodes, edges, flows and messages: added|modified|removed|unchanged.',
|
|
19
|
+
'Edges: {id,from,to,kind,label}; kind: call|http|rpc|event|queue|data|dependency|render|other.',
|
|
20
|
+
'Edges also require delta; from/to must reference declared nodes, lane must reference a declared lane.',
|
|
21
|
+
'When the diff establishes an ordered sequence, add "data-flow" to lenses and a flow:',
|
|
22
|
+
'{"id":"flow","title":"Sequence","delta":"modified","participants":[{"node":"a"},{"node":"b"}],',
|
|
23
|
+
'"messages":[{"id":"step","from":"a","to":"b","label":"call","kind":"sync","delta":"modified"}]}.',
|
|
24
|
+
'Each flow has 2-12 participants and 1-64 messages in execution order; endpoints must be participants.',
|
|
25
|
+
'Message kind: sync|async|return|self (self requires identical endpoints, others require different ones).',
|
|
26
|
+
'Keep labels <=120 characters and summaries <=2000; omit unsupported optional fields.'
|
|
27
|
+
].join('\n');
|
|
28
|
+
|
|
29
|
+
function prLensEnabled(option, env = process.env) {
|
|
30
|
+
return option ?? /^(1|true|yes|on)$/i.test(String(env.GUARDEX_REVIEW_PR_LENS || '').trim());
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function prLensCommand(repoRoot, env = process.env) {
|
|
34
|
+
const bin = String(env.GUARDEX_PR_LENS_BIN || 'pr-lens').trim();
|
|
35
|
+
return bin.includes('/') || bin.includes('\\') ? path.resolve(repoRoot, bin) : bin;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function runLens(bin, args, cwd, timeout, runner) {
|
|
39
|
+
const result = runner(bin, args, { cwd, timeout });
|
|
40
|
+
if (result.error || result.status !== 0) {
|
|
41
|
+
const error = new Error(
|
|
42
|
+
`PR Lens ${args[0]} failed: ${result.error?.message || result.stderr || 'non-zero exit'}. ` +
|
|
43
|
+
'Install @coldtea/pr-lens-cli@0.6.1 (Node >=20.11) or set GUARDEX_PR_LENS_BIN.'
|
|
44
|
+
);
|
|
45
|
+
// validate also reports INVALID_DOCUMENT after file I/O failures. Only
|
|
46
|
+
// schema failures (all diagnostic codes match) are repairable by a model.
|
|
47
|
+
const codes = [...String(result.stderr || '').matchAll(/^✗ .* \[([A-Z_]+)\]$/gm)].map(
|
|
48
|
+
(match) => match[1]
|
|
49
|
+
);
|
|
50
|
+
if (
|
|
51
|
+
args[0] === 'validate' &&
|
|
52
|
+
!result.error &&
|
|
53
|
+
result.status === 1 &&
|
|
54
|
+
codes.length > 0 &&
|
|
55
|
+
codes.every((code) => code === 'INVALID_DOCUMENT')
|
|
56
|
+
) {
|
|
57
|
+
error.code = 'PR_LENS_INVALID_DOCUMENT';
|
|
58
|
+
error.validationErrors = String(result.stderr).slice(0, 8000);
|
|
59
|
+
}
|
|
60
|
+
throw error;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function readPrLensMetadata(pr, repoRoot, runner) {
|
|
65
|
+
const result = runner(
|
|
66
|
+
GH_BIN,
|
|
67
|
+
[
|
|
68
|
+
'pr',
|
|
69
|
+
'view',
|
|
70
|
+
String(pr),
|
|
71
|
+
'--json',
|
|
72
|
+
'number,url,baseRefOid,headRefOid,additions,deletions,changedFiles'
|
|
73
|
+
],
|
|
74
|
+
{ cwd: repoRoot, timeout: 30_000 }
|
|
75
|
+
);
|
|
76
|
+
if (result.error || result.status !== 0) throw new Error('PR Lens could not read PR metadata');
|
|
77
|
+
const data = JSON.parse(result.stdout);
|
|
78
|
+
const url = new URL(data.url);
|
|
79
|
+
const match = url.pathname.match(/^\/([^/]+)\/([^/]+)\/pull\/(\d+)$/);
|
|
80
|
+
if (
|
|
81
|
+
url.protocol !== 'https:' ||
|
|
82
|
+
!match ||
|
|
83
|
+
String(data.number) !== String(pr) ||
|
|
84
|
+
match[3] !== String(pr) ||
|
|
85
|
+
!/^[a-f0-9]{40}$/.test(data.baseRefOid) ||
|
|
86
|
+
!/^[a-f0-9]{40}$/.test(data.headRefOid) ||
|
|
87
|
+
![data.additions, data.deletions, data.changedFiles].every(
|
|
88
|
+
(n) => Number.isSafeInteger(n) && n >= 0
|
|
89
|
+
)
|
|
90
|
+
) {
|
|
91
|
+
throw new Error('PR Lens received invalid PR metadata');
|
|
92
|
+
}
|
|
93
|
+
return {
|
|
94
|
+
provenance: {
|
|
95
|
+
repo: { owner: match[1], name: match[2], host: url.host },
|
|
96
|
+
base: { sha: data.baseRefOid },
|
|
97
|
+
head: { sha: data.headRefOid },
|
|
98
|
+
pullRequest: { number: data.number, url: data.url }
|
|
99
|
+
},
|
|
100
|
+
stats: { filesChanged: data.changedFiles, additions: data.additions, deletions: data.deletions }
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function preparePrLens(pr, repoRoot, timeout, runner) {
|
|
105
|
+
const bin = prLensCommand(repoRoot);
|
|
106
|
+
runLens(bin, ['--help'], repoRoot, Math.min(timeout, 30_000), runner);
|
|
107
|
+
return { bin, metadata: readPrLensMetadata(pr, repoRoot, runner) };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function renderPrLens(graph, context, pr, repoRoot, timeout, runner, repair) {
|
|
111
|
+
if (!graph || typeof graph !== 'object' || Array.isArray(graph)) {
|
|
112
|
+
throw new Error('PR Lens graph missing from review response; rerun or use --no-pr-lens');
|
|
113
|
+
}
|
|
114
|
+
const current = readPrLensMetadata(pr, repoRoot, runner);
|
|
115
|
+
if (JSON.stringify(current) !== JSON.stringify(context.metadata)) {
|
|
116
|
+
throw new Error('PR changed during PR Lens review; rerun against the current diff');
|
|
117
|
+
}
|
|
118
|
+
const artifactRun = createRun(repoRoot);
|
|
119
|
+
const graphPath = writeRunFile(
|
|
120
|
+
artifactRun,
|
|
121
|
+
'results',
|
|
122
|
+
'graph.json',
|
|
123
|
+
JSON.stringify({
|
|
124
|
+
...graph,
|
|
125
|
+
schemaVersion: '0.2.0',
|
|
126
|
+
kind: 'graph',
|
|
127
|
+
...context.metadata
|
|
128
|
+
})
|
|
129
|
+
);
|
|
130
|
+
const directory = path.dirname(graphPath);
|
|
131
|
+
// Explicit output and no-config avoid modifying .gitignore or loading config
|
|
132
|
+
// from the reviewed checkout. Never call analyze or canvas (external uploads).
|
|
133
|
+
try {
|
|
134
|
+
runLens(context.bin, ['validate', graphPath], directory, timeout, runner);
|
|
135
|
+
} catch (error) {
|
|
136
|
+
if (error.code !== 'PR_LENS_INVALID_DOCUMENT' || !repair) throw error;
|
|
137
|
+
const repaired = repair(graph, error.validationErrors);
|
|
138
|
+
if (!repaired || typeof repaired !== 'object' || Array.isArray(repaired)) {
|
|
139
|
+
throw new Error('PR Lens repair returned no graph');
|
|
140
|
+
}
|
|
141
|
+
fs.writeFileSync(
|
|
142
|
+
graphPath,
|
|
143
|
+
JSON.stringify({
|
|
144
|
+
...repaired,
|
|
145
|
+
schemaVersion: '0.2.0',
|
|
146
|
+
kind: 'graph',
|
|
147
|
+
...context.metadata
|
|
148
|
+
})
|
|
149
|
+
);
|
|
150
|
+
runLens(context.bin, ['validate', graphPath], directory, timeout, runner);
|
|
151
|
+
if (
|
|
152
|
+
JSON.stringify(readPrLensMetadata(pr, repoRoot, runner)) !== JSON.stringify(context.metadata)
|
|
153
|
+
) {
|
|
154
|
+
throw new Error('PR changed during PR Lens repair; rerun against the current diff');
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
runLens(
|
|
158
|
+
context.bin,
|
|
159
|
+
['render', graphPath, '--out', directory, '--no-config'],
|
|
160
|
+
directory,
|
|
161
|
+
timeout,
|
|
162
|
+
runner
|
|
163
|
+
);
|
|
164
|
+
const manifestPath = path.join(directory, 'manifest.json');
|
|
165
|
+
const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
|
|
166
|
+
if (!Array.isArray(manifest.assets) || manifest.assets.length === 0) {
|
|
167
|
+
throw new Error('PR Lens produced no diagrams');
|
|
168
|
+
}
|
|
169
|
+
const diagrams = manifest.assets.map((asset) => {
|
|
170
|
+
if (
|
|
171
|
+
typeof asset.path !== 'string' ||
|
|
172
|
+
path.basename(asset.path) !== asset.path ||
|
|
173
|
+
!asset.path.endsWith('.svg') ||
|
|
174
|
+
!fs.lstatSync(path.join(directory, asset.path)).isFile()
|
|
175
|
+
) {
|
|
176
|
+
throw new Error('PR Lens produced an invalid diagram path');
|
|
177
|
+
}
|
|
178
|
+
return path.join(directory, asset.path);
|
|
179
|
+
});
|
|
180
|
+
completeRun(artifactRun);
|
|
181
|
+
return { graphPath, manifestPath, diagrams };
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
module.exports = { GRAPH_PROMPT, prLensEnabled, preparePrLens, renderPrLens, readPrLensMetadata };
|