A Judge Advocate General (often shortened to JAG) within Starfleet was an officer who advised Starfleet on and administered courts martial, as well as overseeing other Starfleet legal matters and personnel. Legal counsel within Starfleet reported to the senior JAG officer as part of the department known as the Judge Advocate General's Office (or simply the Judge Advocate's Office). During the 2260s, the JAG Office was part of Starfleet's operations division. By the 2350s it had moved under the command division.
Phillipa Louvois was also a member of the Judge Advocate General's Office. In 2355, she presided over an investigation into the loss of the USS Stargazer. In 2365, as a captain, she was the commanding officer of the JAG office of Sector 23 on Starbase 173. One of Captain Louvois' first rulings in 2365 was that Lieutenant Commander Data was not the property of Starfleet. (TNG: "The Measure Of A Man")
As Starfleet's Judge Advocate General in 2373, Rear Admiral Bennett ruled on Richard Bashir's criminal actions when he pleaded guilty to the resequencing of his son Julian's DNA. (DS9: "Doctor Bashir, I Presume")
Non-Starfleet persons, including non-Federation citizens, could lodge formal complaints with the JAG that arose from actions taken by Starfleet personnel. This included challenging the validity of a health and safety inspection. (TNG: "Gambit, Part II")
When asked why Richard Bashir, a civilian, was prosecuted by Starfleet, Ronald D. Moore commented, "The Trek universe has established certain things and one of them is a legal system that is clearly different from our own in many ways. Having Picard represent Data in a hearing where he has a personal history with the presiding judge and where his own first officer is the adversarial counsel doesn't make a lot of sense to me either, but 'Measure of a Man' is still one of the very best TNG episodes... In 'Dr. Bashir' I had the JAG deal with the plea bargain because we've never seen any form of judicial forum in the UFP that isn't Starfleet related... Trek has said time and again that Starfleet is more than just a military entity and seems to have police and/or judicial functions, so the involvement of the JAG seemed plausible." (AOL chat, 1997)