@andorra-labs/code 0.1.9 → 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/dist/src/agent-execution.js +20 -0
  2. package/dist/src/app-server/protocol.d.ts +108 -1
  3. package/dist/src/app-server/protocol.js +8 -1
  4. package/dist/src/app-server.d.ts +25 -0
  5. package/dist/src/app-server.js +156 -11
  6. package/dist/src/auth/index.d.ts +1 -1
  7. package/dist/src/auth/index.js +1 -1
  8. package/dist/src/auth/store.d.ts +17 -1
  9. package/dist/src/auth/store.js +25 -2
  10. package/dist/src/browser-ui/app.js +19 -19
  11. package/dist/src/browser-ui/index.html +7 -7
  12. package/dist/src/cli.js +10 -5
  13. package/dist/src/commands.d.ts +1 -1
  14. package/dist/src/commands.js +1 -1
  15. package/dist/src/completion-gates.js +1 -1
  16. package/dist/src/completion.d.ts +1 -1
  17. package/dist/src/completion.js +1 -1
  18. package/dist/src/decision/checks.js +1 -1
  19. package/dist/src/file-diff.d.ts +105 -0
  20. package/dist/src/file-diff.js +244 -0
  21. package/dist/src/graph-manager-chat.js +15 -15
  22. package/dist/src/graph-server.js +9 -9
  23. package/dist/src/graph-ui/app.js +123 -118
  24. package/dist/src/graph-ui/embed.js +9 -9
  25. package/dist/src/graph-ui/icons.js +1 -0
  26. package/dist/src/graph-ui/index.html +3 -3
  27. package/dist/src/graph-ui/manager-state.js +3 -3
  28. package/dist/src/graph-ui/manager.js +14 -14
  29. package/dist/src/graph-ui/skill-picker.js +6 -6
  30. package/dist/src/graph-ui/studio-canvas.js +15 -15
  31. package/dist/src/graph-ui/studio.js +40 -40
  32. package/dist/src/graph-ui/style.css +3 -1
  33. package/dist/src/graph-ui/theme.js +2 -2
  34. package/dist/src/graphs.d.ts +7 -1
  35. package/dist/src/graphs.js +12 -2
  36. package/dist/src/mcp.d.ts +75 -0
  37. package/dist/src/mcp.js +240 -8
  38. package/dist/src/membership-errors.js +1 -1
  39. package/dist/src/provider-keys.d.ts +5 -1
  40. package/dist/src/provider-keys.js +7 -3
  41. package/dist/src/provider-settings.d.ts +4 -1
  42. package/dist/src/provider-settings.js +46 -5
  43. package/dist/src/qa/guidance.js +6 -19
  44. package/dist/src/qa/index.d.ts +0 -2
  45. package/dist/src/qa/index.js +0 -2
  46. package/dist/src/qa/profile/QaProfile.d.ts +5 -1
  47. package/dist/src/qa/profile/QaProfile.js +6 -2
  48. package/dist/src/qa/tools.d.ts +19 -1
  49. package/dist/src/qa/tools.js +20 -145
  50. package/dist/src/react-runtime.js +13 -2
  51. package/dist/src/remote/engine-pool.js +18 -6
  52. package/dist/src/screen-selection.d.ts +38 -0
  53. package/dist/src/screen-selection.js +103 -0
  54. package/dist/src/session-changes.d.ts +117 -0
  55. package/dist/src/session-changes.js +796 -0
  56. package/dist/src/stall-recovery.d.ts +11 -0
  57. package/dist/src/stall-recovery.js +12 -0
  58. package/dist/src/telemetry/schema.d.ts +1 -1
  59. package/dist/src/telemetry/schema.js +1 -2
  60. package/dist/src/terminal-ui.d.ts +64 -20
  61. package/dist/src/terminal-ui.js +310 -80
  62. package/dist/src/tool-diff-stats.d.ts +9 -0
  63. package/dist/src/tool-diff-stats.js +20 -0
  64. package/dist/src/tool-names.d.ts +1 -1
  65. package/dist/src/tool-result-filter.js +1 -1
  66. package/dist/src/tools.js +26 -2
  67. package/dist/src/transcript.d.ts +11 -0
  68. package/dist/src/transcript.js +14 -2
  69. package/dist/src/types.d.ts +6 -0
  70. package/docs/guides/desktop-app.md +1 -1
  71. package/docs/guides/tui.md +9 -9
  72. package/package.json +1 -1
  73. package/dist/src/qa/api/http-runner.d.ts +0 -3
  74. package/dist/src/qa/api/http-runner.js +0 -47
  75. package/dist/src/qa/git/ChangeDetector.d.ts +0 -26
  76. package/dist/src/qa/git/ChangeDetector.js +0 -177
  77. package/dist/src/qa/git/DiffReviewer.d.ts +0 -28
  78. package/dist/src/qa/git/DiffReviewer.js +0 -115
  79. package/dist/src/qa/orchestrator/ChangeClassifier.d.ts +0 -14
  80. package/dist/src/qa/orchestrator/ChangeClassifier.js +0 -28
  81. package/dist/src/qa/orchestrator/MergeGate.d.ts +0 -14
  82. package/dist/src/qa/orchestrator/MergeGate.js +0 -40
  83. package/dist/src/qa/orchestrator/QaOrchestrator.d.ts +0 -79
  84. package/dist/src/qa/orchestrator/QaOrchestrator.js +0 -373
  85. package/dist/src/qa/runners/CommandRunner.d.ts +0 -22
  86. package/dist/src/qa/runners/CommandRunner.js +0 -96
  87. package/dist/src/qa/runners/TestRunner.d.ts +0 -21
  88. package/dist/src/qa/runners/TestRunner.js +0 -66
  89. package/dist/src/qa/runtime/RuntimeSmoke.d.ts +0 -11
  90. package/dist/src/qa/runtime/RuntimeSmoke.js +0 -78
  91. package/dist/src/qa/runtime-detect.d.ts +0 -10
  92. package/dist/src/qa/runtime-detect.js +0 -72
  93. package/dist/src/qa/security/DependencyScanner.d.ts +0 -19
  94. package/dist/src/qa/security/DependencyScanner.js +0 -167
  95. package/dist/src/qa/security/SecretScanner.d.ts +0 -3
  96. package/dist/src/qa/security/SecretScanner.js +0 -55
@@ -1,96 +0,0 @@
1
- import { mkdir, writeFile } from 'node:fs/promises';
2
- import path from 'node:path';
3
- import { executeShell } from '../../shell.js';
4
- export const QA_MAX_TIMEOUT_MS = 900_000;
5
- const IMPORTANT_LINES = 15;
6
- const IMPORTANT_LINE_WIDTH = 300;
7
- /** Extract actionable error lines from mixed stdout/stderr without shipping whole logs to the model. */
8
- export function extractImportantOutput(text) {
9
- const important = [];
10
- for (const line of text.split('\n')) {
11
- const trimmed = line.trim();
12
- if (!trimmed || trimmed.length > 2_000)
13
- continue;
14
- if (/\berror\b|Error:|FAILED|FAIL\b|✕|not ok|\bpanic\b|Traceback|assert|exit code/i.test(trimmed)) {
15
- important.push(trimmed.slice(0, IMPORTANT_LINE_WIDTH));
16
- if (important.length >= IMPORTANT_LINES)
17
- break;
18
- }
19
- }
20
- return important;
21
- }
22
- /** Parse common toolchain failure formats (tsc, eslint stylish, jest/vitest, pytest) into issues. */
23
- export function parseToolOutput(text) {
24
- const issues = [];
25
- for (const line of text.split('\n')) {
26
- const tsc = /^\s*(.+?)\((\d+),(\d+)\): error TS\d+: (.*)$/.exec(line) ?? /^(.+?):(\d+):(\d+) - error TS\d+: (.*)$/.exec(line);
27
- if (tsc) {
28
- issues.push({ file: tsc[1].trim(), line: Number(tsc[2]), column: Number(tsc[3]), severity: 'error', message: tsc[4].trim(), code: 'typecheck' });
29
- continue;
30
- }
31
- const stylish = /^\s+\d+:\d+\s+(error|warning)\s+(.+?)(?:\s{2,}([\w@/-]+))?\s*$/.exec(line);
32
- if (stylish) {
33
- issues.push({ severity: stylish[1] === 'error' ? 'error' : 'warning', message: stylish[2].trim(), code: stylish[3]?.trim() || 'lint' });
34
- continue;
35
- }
36
- const golang = /^.+?:\d+:\d+: (.*(?:expected|undefined|declared|imported))/.exec(line);
37
- if (golang) {
38
- issues.push({ severity: 'error', message: golang[1].trim(), code: 'lint' });
39
- continue;
40
- }
41
- const testFail = /^\s*(?:FAIL|✕|×|not ok|FAILED)\s+(\S.*?)\s*(?:\(\d+ms\))?\s*$/.exec(line);
42
- if (testFail) {
43
- const fileMatch = /^(\S+\.[a-z]+)(?:\s*[>»-]\s*(.*))?$/.exec(testFail[1].trim());
44
- issues.push({ file: fileMatch?.[1], severity: 'error', message: fileMatch?.[2] ? `test failed: ${fileMatch[2].trim()}` : 'test file failed', code: 'test-failure' });
45
- }
46
- }
47
- return issues.slice(0, 25);
48
- }
49
- function firstFailureLine(text) {
50
- return text.split('\n').map(line => line.trim()).filter(line => /\berror\b|Error:|FAILED|FAIL\b|✕|not ok|Traceback|assert/i.test(line))[0];
51
- }
52
- /**
53
- * Run one QA command through the structured shell and normalize the outcome:
54
- * exit 0 passed, nonzero/timeout failed, spawn failure blocked. Full output is
55
- * written to the QA run log directory and only bounded error lines are returned.
56
- */
57
- export async function runCommandCheck(options) {
58
- const timeout = Math.min(Math.max(options.command.timeoutMs ?? options.defaultTimeoutMs, 1_000), QA_MAX_TIMEOUT_MS);
59
- let result;
60
- try {
61
- result = await executeShell(options.command.command, options.workspace, timeout, options.signal);
62
- }
63
- catch (error) {
64
- const message = error instanceof Error ? error.message : String(error);
65
- if (/aborted/i.test(message))
66
- throw error;
67
- return { id: options.id, category: options.category, status: 'blocked', durationMs: 0, summary: `could not start "${options.command.command}": ${message.split('\n')[0]}` };
68
- }
69
- const combined = `${result.stdout}${result.stderr ? `\n${result.stderr}` : ''}`;
70
- const logDir = options.logDir;
71
- await mkdir(logDir, { recursive: true });
72
- const logPath = path.join(logDir, `${options.id}.log`);
73
- await writeFile(logPath, `$ ${options.command.command}\n${combined}`, 'utf8');
74
- const logRef = path.relative(options.workspace, logPath).split(path.sep).join('/');
75
- const durationMs = result.durationMs;
76
- if (result.timedOut) {
77
- return {
78
- id: options.id, category: options.category, status: 'failed', durationMs,
79
- summary: `timed out after ${Math.round(timeout / 1000)}s`, logRef,
80
- importantOutput: extractImportantOutput(combined),
81
- };
82
- }
83
- if (result.exitCode !== 0) {
84
- const failures = parseToolOutput(combined);
85
- const important = extractImportantOutput(combined);
86
- const firstLine = firstFailureLine(combined);
87
- return {
88
- id: options.id, category: options.category, status: 'failed', durationMs,
89
- summary: `"${options.command.command}" exited ${result.exitCode ?? result.exitSignal}${firstLine ? `: ${firstLine.slice(0, 200)}` : ''}`,
90
- errors: failures.length ? failures : undefined,
91
- importantOutput: important.length ? important : undefined,
92
- logRef,
93
- };
94
- }
95
- return { id: options.id, category: options.category, status: 'passed', durationMs, summary: `"${options.command.command}" passed`, logRef };
96
- }
@@ -1,21 +0,0 @@
1
- import type { QaProfile } from '../types.js';
2
- export type QaTestMode = 'related' | 'file' | 'pattern' | 'all';
3
- export interface TestCommandRequest {
4
- mode: QaTestMode;
5
- files?: string[];
6
- pattern?: string;
7
- }
8
- export interface TestCommandOutcome {
9
- /** Absent when the mode cannot run (no unit command, missing arguments). */
10
- command?: string;
11
- timeoutMs?: number;
12
- note?: string;
13
- /** Human-readable reason the requested scope could not run as asked. */
14
- blocked?: string;
15
- }
16
- /**
17
- * Translate a targeted test request into a concrete command. Modes that the
18
- * detected runner cannot scope fall back to the full suite with an explicit
19
- * degradation note; only a missing unit command blocks the check.
20
- */
21
- export declare function buildTestCommand(profile: QaProfile, request: TestCommandRequest): TestCommandOutcome;
@@ -1,66 +0,0 @@
1
- function quote(value) {
2
- return `"${value.replace(/[\\"]/g, '\\$&')}"`;
3
- }
4
- function joinFiles(files) {
5
- return files.map(quote).join(' ');
6
- }
7
- function isPackageManagerWrapper(command) {
8
- return /^(npm|pnpm|yarn|bun)(\s+run)?\s/.test(command);
9
- }
10
- function appendArgs(unit, args) {
11
- return isPackageManagerWrapper(unit) ? `${unit} -- ${args}` : `${unit} ${args}`;
12
- }
13
- function substitute(template, placeholder, value) {
14
- return template.split(`{${placeholder}}`).join(value);
15
- }
16
- /**
17
- * Translate a targeted test request into a concrete command. Modes that the
18
- * detected runner cannot scope fall back to the full suite with an explicit
19
- * degradation note; only a missing unit command blocks the check.
20
- */
21
- export function buildTestCommand(profile, request) {
22
- const unit = profile.qa.unit;
23
- if (!unit)
24
- return { blocked: 'no unit test command configured or detected for this project' };
25
- const runner = profile.test?.runner ?? 'other';
26
- const base = { timeoutMs: unit.timeoutMs };
27
- switch (request.mode) {
28
- case 'all':
29
- return { command: unit.command, ...base };
30
- case 'related': {
31
- if (!request.files?.length)
32
- return { blocked: 'related mode requires files' };
33
- const files = joinFiles(request.files);
34
- if (profile.test?.relatedCommand)
35
- return { command: substitute(profile.test.relatedCommand, 'files', files), ...base };
36
- if (runner === 'jest')
37
- return { command: appendArgs(unit.command, `--findRelatedTests ${files} --passWithNoTests`), ...base };
38
- if (runner === 'vitest')
39
- return { command: `npx vitest related ${files}`, ...base };
40
- return { command: unit.command, note: `runner "${runner}" cannot select related tests; ran the full unit suite`, ...base };
41
- }
42
- case 'file': {
43
- if (!request.files?.length)
44
- return { blocked: 'file mode requires files' };
45
- const files = joinFiles(request.files);
46
- if (runner === 'jest' || runner === 'vitest' || runner === 'node' || runner === 'pytest') {
47
- return { command: appendArgs(unit.command, files), ...base };
48
- }
49
- return { command: unit.command, note: `runner "${runner}" cannot target individual files; ran the full unit suite`, ...base };
50
- }
51
- case 'pattern': {
52
- if (!request.pattern)
53
- return { blocked: 'pattern mode requires a pattern' };
54
- const pattern = quote(request.pattern);
55
- if (profile.test?.patternCommand)
56
- return { command: substitute(profile.test.patternCommand, 'pattern', pattern), ...base };
57
- switch (runner) {
58
- case 'jest': return { command: appendArgs(unit.command, `-t ${pattern}`), ...base };
59
- case 'vitest': return { command: `npx vitest run -t ${pattern}`, ...base };
60
- case 'node': return { command: appendArgs(unit.command, `--test-name-pattern ${pattern}`), ...base };
61
- case 'pytest': return { command: appendArgs(unit.command, `-k ${pattern}`), ...base };
62
- default: return { command: unit.command, note: `runner "${runner}" cannot filter by pattern; ran the full unit suite`, ...base };
63
- }
64
- }
65
- }
66
- }
@@ -1,11 +0,0 @@
1
- import type { QaCheckResult, QaProfile } from '../types.js';
2
- /**
3
- * Boot the configured startup command, wait for its health URL (or a short
4
- * grace window), scan the log for crash signatures, then always stop it.
5
- */
6
- export declare function runRuntimeSmoke(options: {
7
- workspace: string;
8
- profile: QaProfile;
9
- logDir: string;
10
- signal: AbortSignal;
11
- }): Promise<QaCheckResult>;
@@ -1,78 +0,0 @@
1
- import { getQaProcessManager } from './ProcessManager.js';
2
- const DEFAULT_STARTUP_TIMEOUT_MS = 30_000;
3
- const CRASH_PATTERNS = [
4
- { pattern: /uncaughtException|unhandledRejection/i, message: 'uncaught exception during startup' },
5
- { pattern: /Cannot find module|MODULE_NOT_FOUND/, message: 'module resolution failure during startup' },
6
- { pattern: /EADDRINUSE/, message: 'startup port already in use' },
7
- { pattern: /Traceback \(most recent call last\)/, message: 'Python traceback during startup' },
8
- { pattern: /\b(TypeError|ReferenceError|SyntaxError):/, message: 'runtime error during startup' },
9
- { pattern: /\bFATAL\b/, message: 'fatal startup error' },
10
- ];
11
- /**
12
- * Boot the configured startup command, wait for its health URL (or a short
13
- * grace window), scan the log for crash signatures, then always stop it.
14
- */
15
- export async function runRuntimeSmoke(options) {
16
- const startup = options.profile.startup;
17
- if (!startup) {
18
- return { id: 'runtime_smoke', category: 'runtime', status: 'skipped', durationMs: 0, summary: 'no startup command configured (.andorra/qa.yaml qa.startup.command)' };
19
- }
20
- const manager = getQaProcessManager(options.workspace);
21
- const startedAt = Date.now();
22
- const timeout = startup.timeoutMs ?? DEFAULT_STARTUP_TIMEOUT_MS;
23
- try {
24
- await manager.start({ id: 'startup', command: startup.command, logDir: options.logDir });
25
- let readiness = { ready: true };
26
- if (startup.healthUrl) {
27
- readiness = await manager.waitForUrl(startup.healthUrl, timeout, options.signal, 'startup');
28
- }
29
- else {
30
- await new Promise(resolve => {
31
- const timer = setTimeout(resolve, Math.min(timeout, 5_000));
32
- options.signal.addEventListener('abort', () => { clearTimeout(timer); resolve(); }, { once: true });
33
- });
34
- const info = manager.get('startup');
35
- if (!info?.running)
36
- readiness = { ready: false, reason: `startup process exited (${info?.exitCode ?? info?.exitSignal ?? 'unknown'}) before readiness` };
37
- }
38
- const log = manager.logs('startup', 32_768);
39
- const crashes = [];
40
- for (const line of log.split('\n')) {
41
- for (const rule of CRASH_PATTERNS) {
42
- if (rule.pattern.test(line)) {
43
- crashes.push({ severity: 'error', message: `${rule.message}: ${line.trim().slice(0, 300)}`, code: 'runtime-crash' });
44
- break;
45
- }
46
- }
47
- if (crashes.length >= 10)
48
- break;
49
- }
50
- const durationMs = Date.now() - startedAt;
51
- if (!readiness.ready) {
52
- return {
53
- id: 'runtime_smoke', category: 'runtime', status: 'failed', durationMs,
54
- summary: `startup never became healthy: ${readiness.reason}`,
55
- errors: crashes.length ? crashes : undefined,
56
- importantOutput: log.split('\n').filter(l => l.trim()).slice(-15).map(l => l.slice(0, 300)),
57
- };
58
- }
59
- if (crashes.length) {
60
- return {
61
- id: 'runtime_smoke', category: 'runtime', status: 'failed', durationMs,
62
- summary: `startup logged fatal errors (${crashes.length})`,
63
- errors: crashes,
64
- importantOutput: crashes.map(issue => issue.message),
65
- };
66
- }
67
- return { id: 'runtime_smoke', category: 'runtime', status: 'passed', durationMs, summary: `startup ran cleanly${startup.healthUrl ? ` and answered ${startup.healthUrl}` : ''}` };
68
- }
69
- catch (error) {
70
- const message = error instanceof Error ? error.message : String(error);
71
- if (/aborted/i.test(message))
72
- throw error;
73
- return { id: 'runtime_smoke', category: 'runtime', status: 'blocked', durationMs: Date.now() - startedAt, summary: `startup could not launch: ${message.split('\n')[0]}` };
74
- }
75
- finally {
76
- await manager.stop('startup').catch(() => { });
77
- }
78
- }
@@ -1,10 +0,0 @@
1
- import type { RuntimeCapabilities, ShellEnvironment } from './types.js';
2
- /**
3
- * Detect the host shell for QA execution (plan §2.2). Interpreter presence is
4
- * probed rather than assumed; the default kind still decides command syntax.
5
- */
6
- export declare function detectShellEnvironment(): ShellEnvironment;
7
- /** Probe once per process; a missing tool answers instantly, a present one within 2s. */
8
- export declare function detectRuntimeCapabilities(force?: boolean): Promise<RuntimeCapabilities>;
9
- /** Compact per-tool lines for the agent context: only availability plus one-line versions. */
10
- export declare function describeRuntimeCapabilities(capabilities?: RuntimeCapabilities): Promise<string>;
@@ -1,72 +0,0 @@
1
- import { execFile } from 'node:child_process';
2
- import { promisify } from 'node:util';
3
- import { existsSync } from 'node:fs';
4
- import path from 'node:path';
5
- import { defaultShellKind, shellInvocation } from '../shell.js';
6
- const executeFile = promisify(execFile);
7
- const PROBE_TIMEOUT_MS = 2_000;
8
- /** Probe arguments per tool; most accept --version, a few have their own spelling. */
9
- const PROBES = {
10
- node: ['--version'], npm: ['--version'], npx: ['--version'], pnpm: ['--version'], yarn: ['--version'], bun: ['--version'],
11
- python: ['--version'], python3: ['--version'], pip: ['--version'], pytest: ['--version'], uv: ['--version'],
12
- git: ['--version'], gh: ['--version'], cargo: ['--version'], rustc: ['--version'], go: ['version'],
13
- dotnet: ['--version'], java: ['-version'], mvn: ['-version'], gradle: ['--version'],
14
- docker: ['--version'], 'docker-compose': ['--version'],
15
- };
16
- async function probe(tool, args) {
17
- try {
18
- // Most tools print the version on stdout; java -version uses stderr. Either counts.
19
- const { stdout, stderr } = await executeFile(tool, args, { windowsHide: true, timeout: PROBE_TIMEOUT_MS, maxBuffer: 64 * 1024, encoding: 'utf8' });
20
- const line = (stdout || stderr).split(/\r?\n/).map(part => part.trim()).find(Boolean) ?? '';
21
- return { available: true, version: line.slice(0, 120) };
22
- }
23
- catch {
24
- return { available: false };
25
- }
26
- }
27
- function platform() {
28
- return process.platform === 'win32' ? 'windows' : process.platform === 'darwin' ? 'macos' : 'linux';
29
- }
30
- /**
31
- * Detect the host shell for QA execution (plan §2.2). Interpreter presence is
32
- * probed rather than assumed; the default kind still decides command syntax.
33
- */
34
- export function detectShellEnvironment() {
35
- const kind = defaultShellKind;
36
- const executable = (() => {
37
- // An interpreter may be unavailable (e.g. Git Bash absent on Windows); report the
38
- // kind rather than failing detection for a host that can still run other probes.
39
- try {
40
- const resolved = shellInvocation('exit 0', kind).executable;
41
- return existsSync(resolved) || !path.isAbsolute(resolved) ? resolved : `${resolved} (not found)`;
42
- }
43
- catch {
44
- return kind;
45
- }
46
- })();
47
- const prefixes = { powershell: ['-Command'], bash: ['-c'], posix: ['-c'] };
48
- return { platform: platform(), executable, argsPrefix: prefixes[kind] };
49
- }
50
- let cached;
51
- /** Probe once per process; a missing tool answers instantly, a present one within 2s. */
52
- export function detectRuntimeCapabilities(force = false) {
53
- if (!cached || force)
54
- cached = (async () => {
55
- const entries = await Promise.all(Object.entries(PROBES).map(async ([tool, args]) => [tool, await probe(tool, args)]));
56
- return { shell: detectShellEnvironment(), tools: Object.fromEntries(entries) };
57
- })();
58
- return cached;
59
- }
60
- /** Compact per-tool lines for the agent context: only availability plus one-line versions. */
61
- export async function describeRuntimeCapabilities(capabilities) {
62
- const caps = capabilities ?? await detectRuntimeCapabilities();
63
- const order = ['node', 'npm', 'pnpm', 'yarn', 'bun', 'python', 'pytest', 'uv', 'git', 'gh', 'cargo', 'go', 'dotnet', 'java', 'mvn', 'gradle', 'docker', 'docker-compose'];
64
- const lines = [`Shell: ${caps.shell.platform} ${path.basename(caps.shell.executable)}`];
65
- for (const tool of order) {
66
- const entry = caps.tools[tool];
67
- if (!entry)
68
- continue;
69
- lines.push(`${tool}: ${entry.available ? entry.version ?? 'available' : 'unavailable'}`);
70
- }
71
- return lines.join('\n');
72
- }
@@ -1,19 +0,0 @@
1
- import type { QaIssue, QaSeverityCascade } from '../types.js';
2
- export interface DependencyAuditOutcome {
3
- status: 'passed' | 'failed' | 'blocked';
4
- summary: string;
5
- issues: QaIssue[];
6
- importantOutput: string[];
7
- durationMs: number;
8
- }
9
- /**
10
- * `npm/pnpm/yarn audit` with tolerant JSON parsing. The check fails when any
11
- * advisory severity is in `failOn`; unsupported ecosystems report blocked
12
- * rather than silently passing.
13
- */
14
- export declare function runDependencyAudit(options: {
15
- workspace: string;
16
- packageManager?: string;
17
- failOn: QaSeverityCascade[];
18
- signal: AbortSignal;
19
- }): Promise<DependencyAuditOutcome>;
@@ -1,167 +0,0 @@
1
- import { executeShell } from '../../shell.js';
2
- const AUDIT_TIMEOUT_MS = 120_000;
3
- const NO_VULNS_COUNTS = { critical: 0, high: 0, moderate: 0, low: 0, info: 0 };
4
- function asRecord(value) {
5
- return value && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
6
- }
7
- function severityOf(value) {
8
- return typeof value === 'string' ? value.toLowerCase() : 'unknown';
9
- }
10
- function metadataCounts(metadata) {
11
- const counts = asRecord(asRecord(metadata)?.vulnerabilities);
12
- if (!counts)
13
- return {};
14
- const result = {};
15
- for (const [key, value] of Object.entries(counts))
16
- if (typeof value === 'number')
17
- result[key.toLowerCase()] = value;
18
- return result;
19
- }
20
- /** Tolerant parse of `npm audit --json` (report v1 and v2) and `pnpm audit --json`. */
21
- function parseAuditJson(stdout) {
22
- const start = stdout.indexOf('{');
23
- if (start < 0)
24
- return undefined;
25
- let root;
26
- try {
27
- root = JSON.parse(stdout.slice(start));
28
- }
29
- catch {
30
- return undefined;
31
- }
32
- const data = asRecord(root);
33
- if (!data)
34
- return undefined;
35
- const vulnerabilities = [];
36
- const named = asRecord(data.vulnerabilities);
37
- if (named) {
38
- for (const [pkg, entry] of Object.entries(named)) {
39
- const record = asRecord(entry);
40
- if (!record)
41
- continue;
42
- let title;
43
- if (Array.isArray(record.via)) {
44
- for (const via of record.via) {
45
- const advisory = asRecord(via);
46
- if (advisory && typeof advisory.title === 'string') {
47
- title = advisory.title;
48
- break;
49
- }
50
- }
51
- }
52
- vulnerabilities.push({ name: pkg, severity: severityOf(record.severity), title });
53
- }
54
- }
55
- const advisories = asRecord(data.advisories);
56
- if (advisories) {
57
- for (const entry of Object.values(advisories)) {
58
- const advisory = asRecord(entry);
59
- if (!advisory)
60
- continue;
61
- vulnerabilities.push({
62
- name: typeof advisory.module_name === 'string' ? advisory.module_name : 'unknown',
63
- severity: severityOf(advisory.severity),
64
- title: typeof advisory.title === 'string' ? advisory.title : undefined,
65
- });
66
- }
67
- }
68
- const counts = metadataCounts(data.metadata);
69
- if (!vulnerabilities.length && !Object.keys(counts).length)
70
- return undefined;
71
- return { vulnerabilities, counts };
72
- }
73
- /** Newer pnpm emits newline-delimited JSON findings; older pnpm and yarn emit newline-delimited events. */
74
- function parseAuditJsonLines(stdout) {
75
- const vulnerabilities = [];
76
- let counts = {};
77
- let sawAny = false;
78
- for (const line of stdout.split('\n')) {
79
- const trimmed = line.trim();
80
- if (!trimmed.startsWith('{'))
81
- continue;
82
- let event;
83
- try {
84
- event = JSON.parse(trimmed);
85
- }
86
- catch {
87
- continue;
88
- }
89
- const record = asRecord(event);
90
- if (!record)
91
- continue;
92
- sawAny = true;
93
- const advisory = asRecord(record.advisory);
94
- if (advisory) {
95
- vulnerabilities.push({
96
- name: typeof advisory.module_name === 'string' ? advisory.module_name : 'unknown',
97
- severity: severityOf(advisory.severity),
98
- title: typeof advisory.title === 'string' ? advisory.title : undefined,
99
- });
100
- }
101
- const finding = asRecord(record.finding);
102
- const findingSeverity = finding ? asRecord(finding.severity) : undefined;
103
- if (findingSeverity) {
104
- const [severity] = Object.keys(findingSeverity);
105
- if (severity)
106
- vulnerabilities.push({ name: String(record.package ?? 'unknown'), severity: severityOf(severity) });
107
- }
108
- const lineCounts = metadataCounts(record.metadata);
109
- if (Object.keys(lineCounts).length)
110
- counts = lineCounts;
111
- }
112
- if (!sawAny)
113
- return undefined;
114
- return { vulnerabilities, counts };
115
- }
116
- function mergedCounts(report) {
117
- if (Object.keys(report.counts).length)
118
- return report.counts;
119
- const counts = { ...NO_VULNS_COUNTS };
120
- for (const vuln of report.vulnerabilities)
121
- counts[vuln.severity] = (counts[vuln.severity] ?? 0) + 1;
122
- return counts;
123
- }
124
- function formatCounts(counts) {
125
- const parts = ['critical', 'high', 'moderate', 'low', 'info']
126
- .filter(key => (counts[key] ?? 0) > 0)
127
- .map(key => `${counts[key]} ${key}`);
128
- return parts.length ? parts.join(', ') : 'no advisories';
129
- }
130
- /**
131
- * `npm/pnpm/yarn audit` with tolerant JSON parsing. The check fails when any
132
- * advisory severity is in `failOn`; unsupported ecosystems report blocked
133
- * rather than silently passing.
134
- */
135
- export async function runDependencyAudit(options) {
136
- const manager = options.packageManager ?? 'npm';
137
- if (!['npm', 'pnpm', 'yarn'].includes(manager)) {
138
- return { status: 'blocked', summary: `no built-in dependency audit for package manager "${manager}"`, issues: [], importantOutput: [], durationMs: 0 };
139
- }
140
- const started = Date.now();
141
- let result;
142
- try {
143
- result = await executeShell(`${manager} audit --json`, options.workspace, AUDIT_TIMEOUT_MS, options.signal);
144
- }
145
- catch (error) {
146
- const message = error instanceof Error ? error.message : String(error);
147
- return { status: 'blocked', summary: `dependency audit could not run: ${message.split('\n')[0]}`, issues: [], importantOutput: [], durationMs: Date.now() - started };
148
- }
149
- const durationMs = Date.now() - started;
150
- const report = parseAuditJson(result.stdout) ?? parseAuditJsonLines(result.stdout);
151
- if (!report) {
152
- const firstLine = (result.stderr || result.stdout || `exit ${result.exitCode ?? result.exitSignal}`).split('\n').find(line => line.trim()) ?? 'no output';
153
- return { status: 'blocked', summary: `${manager} audit produced no parseable report: ${firstLine.slice(0, 200)}`, issues: [], importantOutput: [], durationMs };
154
- }
155
- const counts = mergedCounts(report);
156
- const failing = report.vulnerabilities.filter(vuln => options.failOn.includes(vuln.severity));
157
- const failingByCount = options.failOn.some(severity => (counts[severity] ?? 0) > 0);
158
- const summary = `${manager} audit: ${formatCounts(counts)}`;
159
- const importantOutput = report.vulnerabilities.slice(0, 10).map(vuln => `${vuln.severity}: ${vuln.name}${vuln.title ? ` - ${vuln.title}` : ''}`);
160
- const issues = report.vulnerabilities.slice(0, 25).map(vuln => ({
161
- severity: options.failOn.includes(vuln.severity) ? 'error' : 'warning',
162
- message: `${vuln.severity} vulnerability in ${vuln.name}${vuln.title ? `: ${vuln.title}` : ''}`,
163
- code: 'dependency-vulnerability',
164
- }));
165
- const failed = failing.length > 0 || failingByCount;
166
- return { status: failed ? 'failed' : 'passed', summary, issues, importantOutput, durationMs };
167
- }
@@ -1,3 +0,0 @@
1
- import type { QaIssue } from '../types.js';
2
- /** Scan diff-added lines for credential-shaped strings. Issues carry redacted values. */
3
- export declare function scanAddedLinesForSecrets(diff: string): QaIssue[];
@@ -1,55 +0,0 @@
1
- import { addedLines } from '../git/DiffReviewer.js';
2
- const SECRET_RULES = [
3
- { name: 'aws-access-key', pattern: /\b((?:AKIA|ASIA)[0-9A-Z]{16})\b/ },
4
- { name: 'github-token', pattern: /\b(gh[pousr]_[A-Za-z0-9]{30,255})\b/ },
5
- { name: 'openai-key', pattern: /\b(sk-[A-Za-z0-9_-]{20,})\b/ },
6
- { name: 'slack-token', pattern: /\b(xox[baprs]-[A-Za-z0-9-]{10,})\b/ },
7
- { name: 'google-api-key', pattern: /\b(AIza[0-9A-Za-z_-]{35})\b/ },
8
- { name: 'private-key', pattern: /(-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP )?PRIVATE KEY(?: BLOCK)?-----)/ },
9
- { name: 'jwt', pattern: /\b(eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,})\b/ },
10
- {
11
- name: 'credential-assignment',
12
- pattern: /\b(?:password|passwd|pwd|secret|api[_-]?key|apikey|access[_-]?token|auth[_-]?token|client[_-]?secret)\b["']?\s*[:=]\s*["']([^"'\n]{8,})["']/i,
13
- valueGroup: 1,
14
- },
15
- {
16
- name: 'connection-string-password',
17
- pattern: /\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|amqps?|mssql):\/\/[^\s/:@]+:([^@\s/]{4,})@/i,
18
- valueGroup: 1,
19
- },
20
- ];
21
- /** Template/placeholder shapes that are credentials in name only. */
22
- const PLACEHOLDER = /\$\{|\{\{|<[a-z0-9_.-]+>|\.\.\.|xxxx|your[-_]|changeme|placeholder|example/i;
23
- function redact(value) {
24
- const visible = value.slice(0, 4);
25
- return visible + '*'.repeat(Math.min(Math.max(value.length - visible.length, 4), 24));
26
- }
27
- /** Scan diff-added lines for credential-shaped strings. Issues carry redacted values. */
28
- export function scanAddedLinesForSecrets(diff) {
29
- const issues = [];
30
- if (!diff)
31
- return issues;
32
- for (const line of addedLines(diff)) {
33
- if (!line.text)
34
- continue;
35
- for (const rule of SECRET_RULES) {
36
- const match = rule.pattern.exec(line.text);
37
- if (!match)
38
- continue;
39
- const value = (rule.valueGroup !== undefined ? match[rule.valueGroup] : match[1]) ?? match[0];
40
- if (PLACEHOLDER.test(value))
41
- continue;
42
- issues.push({
43
- file: line.file,
44
- line: line.line,
45
- severity: 'error',
46
- message: `possible secret (${rule.name}): ${redact(value)}`,
47
- code: 'secret',
48
- });
49
- break;
50
- }
51
- if (issues.length >= 50)
52
- break;
53
- }
54
- return issues;
55
- }