1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
//! `quorum` — the Phase 1A CLI.
mod commands;
mod exit;
mod hooks;
mod render;
mod tui;
use clap::{Parser, Subcommand};
use exit::{CliError, Exit};
use quorum_lippa_client::keyring::Storage;
use std::path::PathBuf;
use std::process::ExitCode;
const DEFAULT_BASE_URL: &str = "https://app.lippa.ai";
#[derive(Parser, Debug)]
#[command(
name = "quorum",
version = concat!(env!("CARGO_PKG_VERSION"), " (", env!("GIT_SHORT_SHA"), ")"),
about = "Quorum: multi-model code reviewer"
)]
struct Cli {
#[command(subcommand)]
cmd: Cmd,
}
#[derive(Subcommand, Debug)]
enum Cmd {
Auth(AuthArgs),
Link(LinkArgs),
Review(ReviewArgs),
Install(HookArgs),
Uninstall(HookArgs),
/// Phase 1C — inspect dismissal-promotion state. Stage 3 ships the
/// read surface (`list`, `show`, `history`); `promote` / `demote` /
/// `prune` land in Stage 4.
Convention(ConventionArgs),
}
#[derive(clap::Args, Debug)]
struct ConventionArgs {
/// Operate against `<path>/.quorum/` instead of `$CWD/.quorum/`.
/// Used by tests for hermetic isolation; production callers omit.
#[arg(long, value_name = "PATH", global = true)]
quorum_dir: Option<PathBuf>,
#[command(subcommand)]
cmd: ConventionCmd,
}
#[derive(Subcommand, Debug)]
enum ConventionCmd {
/// List dismissals by promotion state.
List {
/// Filter by state: `candidate`, `local_only`, or
/// `promoted_convention`. Omit for all states.
#[arg(long, value_name = "STATE")]
state: Option<String>,
/// Print orphan reports (managed blocks in conventions.md with no
/// SQLite row; SQLite rows whose managed block is missing from
/// conventions.md). Stage 3 read-only diagnostic.
#[arg(long)]
orphans: bool,
/// Emit a JSON array suitable for piping into `jq`.
#[arg(long)]
json: bool,
},
/// Show one dismissal's title, body, state, and transition log.
Show {
/// Hex prefix (≥ 8 chars) or full 64-hex finding_identity_hash.
hash: String,
},
/// Print the `state_transitions` audit log for one dismissal.
History {
/// Hex prefix (≥ 8 chars) or full 64-hex finding_identity_hash.
hash: String,
},
/// Promote a local_only dismissal to a written convention (T2).
/// Writes a managed block to `.quorum/conventions.md` and flips the
/// SQLite state. File-first-rename, then SQLite COMMIT (spec §3.2 T2).
Promote {
/// Hex prefix (≥ 8 chars) or full 64-hex finding_identity_hash.
hash: String,
/// Inline convention body. Mutually exclusive with `--from-editor`.
/// Without either flag, the managed block carries only the
/// title-derived header line (no body paragraph) per §4.4.
#[arg(long, value_name = "STRING", conflicts_with = "from_editor")]
text: Option<String>,
/// Spawn `$EDITOR` to author the convention body. Tests set
/// `QUORUM_TEST_EDITOR_BODY` to supply the body hermetically.
#[arg(long)]
from_editor: bool,
},
/// Demote a promoted_convention back to local_only (T3). Removes the
/// managed block from `.quorum/conventions.md` and flips SQLite state.
Demote {
/// Hex prefix (≥ 8 chars) or full 64-hex finding_identity_hash.
hash: String,
},
/// Prune candidate dismissals older than `[memory] candidate_expire_days`
/// (T4). Promoted/local_only rows are never touched.
Prune {
/// List the candidates that would be pruned; no DELETE.
#[arg(long)]
dry_run: bool,
/// Skip the Y/N confirmation prompt.
#[arg(long)]
yes: bool,
},
}
#[derive(clap::Args, Debug)]
struct HookArgs {
/// Hook kind: `pre-commit` or `pre-push`.
#[arg(long, value_name = "KIND")]
hook: String,
}
#[derive(clap::Args, Debug)]
struct AuthArgs {
#[command(subcommand)]
cmd: AuthCmd,
}
#[derive(Subcommand, Debug)]
enum AuthCmd {
Login {
#[arg(long)]
url: Option<String>,
#[arg(long)]
no_keyring: bool,
/// Consume `QUORUM_LIPPA_EMAIL` + `QUORUM_LIPPA_PASSWORD` from
/// the environment instead of prompting on the TTY. Suitable
/// for CI bootstrap; cookie persists to keyring (or to the
/// `--no-keyring` file fallback) per Phase 1A policy.
#[arg(long)]
non_interactive: bool,
},
Logout {
#[arg(long)]
url: Option<String>,
#[arg(long)]
no_keyring: bool,
},
Status {
#[arg(long)]
url: Option<String>,
#[arg(long)]
no_keyring: bool,
/// Print the raw session cookie value to stdout. Asks for
/// confirmation on stderr first; pass `-y` to skip the
/// prompt. Non-TTY without `-y` exits 2.
#[arg(long)]
show_session: bool,
/// Skip the `--show-session` confirm prompt. No-op without
/// `--show-session`.
#[arg(short = 'y', long = "yes")]
yes: bool,
},
}
#[derive(clap::Args, Debug)]
struct LinkArgs {
#[arg(long, conflicts_with_all = ["show"])]
project: Option<String>,
#[arg(long)]
url: Option<String>,
#[arg(long, default_value_t = false)]
no_remote_url: bool,
#[arg(long)]
show: bool,
}
#[derive(clap::Args, Debug)]
struct ReviewArgs {
#[arg(long)]
json: bool,
#[arg(long)]
no_keyring: bool,
/// Review a commit range instead of the staged diff.
/// Accepts any `git rev-parse`-compatible expression, e.g.
/// `HEAD~3..HEAD`, `main..feature`, `<base-sha>..<head-sha>`.
#[arg(long, value_name = "REF-EXPR")]
range: Option<String>,
/// Dismissals from this session do not expire (`expires_at = NULL`).
/// Default expiry is 365 days.
#[arg(long)]
no_expire: bool,
/// Launch the interactive findings/dismiss TUI after the review
/// converges. Requires a TTY; non-TTY exits 2 before bundle assembly.
#[arg(long)]
tui: bool,
/// Run in hook mode (`pre-commit` or `pre-push`). Suppresses
/// markdown stdout; emits one-line stderr per high-severity
/// finding; under `pre-push` reads ref tuples from stdin.
/// Internally consumed by the shell templates emitted by
/// `quorum install --hook=<type>`.
#[arg(long, value_name = "KIND")]
hook_mode: Option<String>,
}
#[tokio::main(flavor = "current_thread")]
async fn main() -> ExitCode {
tracing_subscriber::fmt()
.with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
.with_target(false)
.compact()
.init();
let cli = Cli::parse();
let res = dispatch(cli).await;
match res {
Ok(exit) => exit.code(),
Err(e) => {
eprintln!("{e}");
e.exit().code()
}
}
}
async fn dispatch(cli: Cli) -> Result<Exit, CliError> {
match cli.cmd {
Cmd::Auth(args) => match args.cmd {
AuthCmd::Login {
url,
no_keyring,
non_interactive,
} => {
let url = url.unwrap_or_else(|| DEFAULT_BASE_URL.to_string());
let storage = storage_for(no_keyring)?;
if non_interactive {
// Skips the TTY check entirely (AC 90). Env-var
// capture happens inside login_non_interactive,
// both values Secret-wrapped at read; the
// password is dropped immediately after
// login_with_cookie returns (AC 128).
commands::auth::login_non_interactive(&url, &storage).await?;
} else {
let tty = is_tty();
commands::auth::login(&url, &storage, tty).await?;
}
Ok(Exit::Ok)
}
AuthCmd::Logout { url, no_keyring } => {
let url = url.unwrap_or_else(|| DEFAULT_BASE_URL.to_string());
let storage = storage_for(no_keyring)?;
commands::auth::logout(&url, &storage).await?;
Ok(Exit::Ok)
}
AuthCmd::Status {
url,
no_keyring,
show_session,
yes,
} => {
let url = url.unwrap_or_else(|| DEFAULT_BASE_URL.to_string());
let storage = storage_for(no_keyring)?;
if show_session {
commands::auth::status_show_session(&url, &storage, is_tty(), yes)?;
} else {
commands::auth::status(&url, &storage).await?;
}
Ok(Exit::Ok)
}
},
Cmd::Link(args) => {
let repo_root = std::env::current_dir().map_err(|e| CliError::Io(e.to_string()))?;
if args.show {
commands::link::link_show(&repo_root)?;
Ok(Exit::Ok)
} else {
let project = args
.project
.ok_or_else(|| CliError::Config("missing --project".into()))?;
let url = args.url.unwrap_or_else(|| DEFAULT_BASE_URL.to_string());
commands::link::link_write(&repo_root, project, url, !args.no_remote_url)?;
Ok(Exit::Ok)
}
}
Cmd::Review(args) => {
let repo_root = std::env::current_dir().map_err(|e| CliError::Io(e.to_string()))?;
let storage = if args.no_keyring {
Some(fallback_storage()?)
} else {
None
};
// TTY check happens BEFORE bundle assembly and any network
// round-trip (v1.0 §4.4 P17, AC 65). Non-TTY `--tui` fails
// in milliseconds with exit 2.
if args.tui && !is_tty() {
return Err(CliError::Config(
"--tui requires an interactive terminal; omit --tui for stdout markdown".into(),
));
}
// Hook-mode routes to dedicated dispatchers — pre-push
// reads stdin and loops per tuple; pre-commit is a thin
// shim over the standard review pipeline with output
// suppressed and stderr findings.
if let Some(mode) = args.hook_mode {
return match mode.as_str() {
"pre-commit" => {
commands::hook_mode::run_pre_commit(&repo_root, args.json, storage).await
}
"pre-push" => {
commands::hook_mode::run_pre_push(&repo_root, std::io::stdin(), storage)
.await
}
other => Err(CliError::Config(format!(
"unknown --hook-mode value: {other:?}; expected pre-commit or pre-push"
))),
};
}
let diff_source = match args.range {
Some(spec) => {
let (base, head) = parse_range_spec(&spec)?;
quorum_core::git::DiffSource::CommitRange { base, head }
}
None => quorum_core::git::DiffSource::StagedIndex,
};
commands::review::run(
&repo_root,
commands::review::ReviewOptions {
json_to_stdout: args.json,
no_keyring_storage: storage,
diff_source,
no_expire: args.no_expire,
tui: args.tui,
hook_mode: commands::review::HookMode::None,
archive_filename_override: None,
},
)
.await
}
Cmd::Install(args) => {
let repo_root = std::env::current_dir().map_err(|e| CliError::Io(e.to_string()))?;
commands::hooks::install(&repo_root, &args.hook)
}
Cmd::Uninstall(args) => {
let repo_root = std::env::current_dir().map_err(|e| CliError::Io(e.to_string()))?;
commands::hooks::uninstall(&repo_root, &args.hook)
}
Cmd::Convention(args) => dispatch_convention(args),
}
}
fn dispatch_convention(args: ConventionArgs) -> Result<Exit, CliError> {
match args.cmd {
ConventionCmd::List {
state,
orphans,
json,
} => {
let state = parse_promotion_state(state.as_deref())?;
commands::convention::list(args.quorum_dir.as_ref(), state, orphans, json)
}
ConventionCmd::Show { hash } => commands::convention::show(args.quorum_dir.as_ref(), &hash),
ConventionCmd::History { hash } => {
commands::convention::history(args.quorum_dir.as_ref(), &hash)
}
ConventionCmd::Promote {
hash,
text,
from_editor,
} => {
let body = match (text, from_editor) {
(Some(s), false) => commands::convention::BodySource::Text(s),
(None, true) => commands::convention::BodySource::FromEditor,
(None, false) => commands::convention::BodySource::TitleOnly,
(Some(_), true) => {
// clap's `conflicts_with` should reject this, but
// defense-in-depth.
return Err(CliError::Config(
"--text and --from-editor are mutually exclusive".into(),
));
}
};
commands::convention::promote(args.quorum_dir.as_ref(), &hash, body)
}
ConventionCmd::Demote { hash } => {
commands::convention::demote(args.quorum_dir.as_ref(), &hash)
}
ConventionCmd::Prune { dry_run, yes } => {
commands::convention::prune(args.quorum_dir.as_ref(), dry_run, yes)
}
}
}
fn parse_promotion_state(s: Option<&str>) -> Result<Option<quorum_core::PromotionState>, CliError> {
match s {
None => Ok(None),
Some(raw) => quorum_core::PromotionState::from_db_str(raw)
.map(Some)
.ok_or_else(|| {
CliError::Config(format!(
"unknown --state value '{raw}'; expected one of \
candidate, local_only, promoted_convention"
))
}),
}
}
/// Parse a `--range` argument. Accepts the canonical `base..head` form;
/// rejects single-ref or `base...head` (symmetric-difference) for now —
/// the bundle pipeline reviews `head` content against `base` tree only.
fn parse_range_spec(spec: &str) -> Result<(String, String), CliError> {
if let Some((base, head)) = spec.split_once("..") {
if base.is_empty() || head.is_empty() {
return Err(CliError::Config(format!(
"--range expects `<base>..<head>`; got `{spec}`"
)));
}
if head.starts_with('.') {
// matched `...` — symmetric-difference form
return Err(CliError::Config(
"--range does not support `...` (symmetric-difference); use `base..head`".into(),
));
}
Ok((base.to_string(), head.to_string()))
} else {
Err(CliError::Config(format!(
"--range expects `<base>..<head>`; got `{spec}`"
)))
}
}
fn storage_for(no_keyring: bool) -> Result<Storage, CliError> {
if no_keyring {
Ok(fallback_storage()?)
} else {
Ok(Storage::OsKeyring)
}
}
fn fallback_storage() -> Result<Storage, CliError> {
let base = config_dir().ok_or_else(|| CliError::Io("could not resolve config dir".into()))?;
let dir = base.join("quorum").join("sessions");
Ok(Storage::File(dir))
}
fn config_dir() -> Option<PathBuf> {
// Windows: %APPDATA%\quorum\sessions
// Unix: $XDG_CONFIG_HOME or ~/.config
if let Some(appdata) = std::env::var_os("APPDATA") {
return Some(PathBuf::from(appdata));
}
if let Some(xdg) = std::env::var_os("XDG_CONFIG_HOME") {
return Some(PathBuf::from(xdg));
}
if let Some(home) = std::env::var_os("HOME") {
return Some(PathBuf::from(home).join(".config"));
}
None
}
fn is_tty() -> bool {
use std::io::IsTerminal;
std::io::stdin().is_terminal()
}