Misfiring?
My Legacy was doing the same thing, especially when the car had been sitting overnight or when it was raining. It was throwing misfire codes once in a while, but not always. The coilpack tends to crack over time from the heat of the engine, and water gets in there. I replaced the coilpack, plugs, and wires, and it runs 100x better now.