paceflow 0.2.4

Local-first CLI that turns AI coding session history and git metadata into engineering analytics.
Documentation
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
use anyhow::{Result, anyhow, bail};
use std::io::{self, Write};

use crate::cli::{SyncArgs, SyncCommands, SyncPushArgs, SyncScheduleCommands, SyncStatusArgs};
use crate::db;
use crate::sync::{
    SavedSyncConfig, SyncApiClient, SyncConfigSource, delete_saved_sync_config,
    grouped_event_counts, last_sync_run_state, load_saved_sync_config, make_push_request,
    mark_synced_events, normalized_base_url, partition_eligible_sync_events, pending_sync_events,
    reset_local_sync_state, resolve_sync_scope, resolved_sync_config, save_sync_config,
    sync_env_fallback_keys,
};
use crate::sync_identity;
use crate::sync_schedule::{
    ScheduleInstallOutcome, ScheduleState, current_backend, install_or_update_schedule,
    run_scheduled_sync, schedule_status, uninstall_schedule,
};

const DEFAULT_SYNC_API_BASE_URL: &str = "http://localhost:8443";

pub fn run(args: SyncArgs) -> Result<()> {
    match args.command {
        SyncCommands::Config => run_config(),
        SyncCommands::Push(args) => run_push(args),
        SyncCommands::Status(args) => run_status(args),
        SyncCommands::Schedule(args) => run_schedule(args.command),
        SyncCommands::Reset => run_reset(),
    }
}

fn run_config() -> Result<()> {
    match load_saved_sync_config()? {
        Some(_) => prompt_existing_config_flow(),
        None => prompt_initial_config_flow(),
    }
}

fn run_push(args: SyncPushArgs) -> Result<()> {
    let config = resolved_sync_config()?
        .ok_or_else(|| anyhow!("Sync is not configured. Run `paceflow sync config` first."))?;
    let scope = resolve_sync_scope(args.repo.as_deref(), args.all_projects)?;
    let mut conn = db::open()?;
    let pending = pending_sync_events(&conn, &config.organization_id, &scope)?;

    if pending.is_empty() {
        println!(
            "No pending sync events for {} ({})",
            config
                .organization_name
                .as_deref()
                .unwrap_or("(unnamed organization)"),
            config.organization_id
        );
        return Ok(());
    }

    println!(
        "Uploading {} pending sync events to {} ({})",
        pending.len(),
        config
            .organization_name
            .as_deref()
            .unwrap_or("(unnamed organization)"),
        config.organization_id
    );
    print_event_counts("Pending", &grouped_event_counts(&pending));

    let runtime = new_runtime()?;
    let client = SyncApiClient::new(config.base_url.clone(), Some(config.token.clone()))?;
    let allowlist = runtime.block_on(client.repositories(&config.organization_id))?;
    let partitioned = partition_eligible_sync_events(pending, &allowlist);

    if !partitioned.skipped.is_empty() {
        println!(
            "Skipping {} pending sync events from {} repos not recognized by PaceFlow.",
            partitioned.skipped.len(),
            partitioned.skipped_repo_keys.len()
        );
    }

    if partitioned.eligible.is_empty() {
        println!(
            "No eligible org project sync events found. Skipped {} pending sync events from {} repos not recognized by PaceFlow.",
            partitioned.skipped.len(),
            partitioned.skipped_repo_keys.len()
        );
        return Ok(());
    }

    println!(
        "Uploading {} eligible org project sync events.",
        partitioned.eligible.len()
    );
    print_event_counts("Eligible", &grouped_event_counts(&partitioned.eligible));

    let batch_size = args.batch_size.max(1);
    let mut uploaded = 0usize;

    for chunk in partitioned.eligible.chunks(batch_size) {
        let request = make_push_request(chunk);
        let response = runtime.block_on(client.push_events(&config.organization_id, &request))?;
        if response.rejected > 0 || response.accepted != chunk.len() {
            bail!(
                "sync push was only partially accepted: accepted={} rejected={}",
                response.accepted,
                response.rejected
            );
        }
        mark_synced_events(
            &mut conn,
            &config.organization_id,
            chunk,
            &response.checkpoint,
        )?;
        uploaded += response.accepted;
    }

    println!("Uploaded {uploaded} sync events.");
    Ok(())
}

fn run_schedule(command: SyncScheduleCommands) -> Result<()> {
    match command {
        SyncScheduleCommands::Install => {
            let mut backend = current_backend();
            match install_or_update_schedule(backend.as_mut())? {
                ScheduleInstallOutcome::Installed => {
                    println!("Installed Paceflow periodic sync schedule.")
                }
                ScheduleInstallOutcome::Updated => {
                    println!("Updated Paceflow periodic sync schedule.")
                }
                ScheduleInstallOutcome::AlreadyInstalled => {
                    println!("Paceflow periodic sync schedule is already installed.")
                }
            }
            Ok(())
        }
        SyncScheduleCommands::Status => {
            let backend = current_backend();
            let status = schedule_status(backend.as_ref())?;
            match status.state {
                ScheduleState::Missing => println!(
                    "Paceflow periodic sync schedule is not installed ({:?}).",
                    status.backend
                ),
                ScheduleState::Installed(_) => println!(
                    "Paceflow periodic sync schedule is installed ({:?}).",
                    status.backend
                ),
                ScheduleState::NonPaceflowArtifact => println!(
                    "A non-Paceflow schedule exists where the periodic sync schedule would be installed ({:?}).",
                    status.backend
                ),
            }
            Ok(())
        }
        SyncScheduleCommands::Uninstall => {
            let mut backend = current_backend();
            if uninstall_schedule(backend.as_mut())? {
                println!("Removed Paceflow periodic sync schedule.");
            } else {
                println!("Paceflow periodic sync schedule is not installed.");
            }
            Ok(())
        }
        SyncScheduleCommands::Run => run_scheduled_sync(),
    }
}

fn run_status(args: SyncStatusArgs) -> Result<()> {
    let Some(config) = resolved_sync_config()? else {
        println!("Sync is not configured. Run `paceflow sync config` first.");
        return Ok(());
    };

    let scope = resolve_sync_scope(args.repo.as_deref(), args.all_projects)?;
    let conn = db::open()?;
    let pending = pending_sync_events(&conn, &config.organization_id, &scope)?;
    let counts = grouped_event_counts(&pending);

    println!("Sync Configuration");
    println!(
        "Base URL: {} ({})",
        config.base_url,
        format_source(config.base_url_source)
    );
    println!(
        "Organization: {} ({}) ({})",
        config
            .organization_name
            .as_deref()
            .unwrap_or("(unnamed organization)"),
        config.organization_id,
        format_source(config.organization_id_source)
    );
    println!("Token: configured ({})", format_source(config.token_source));

    if let Some(run_state) = last_sync_run_state(&conn, &config.organization_id)? {
        println!(
            "Last Successful Push: {}",
            run_state.last_successful_push_at
        );
        println!(
            "Last Server Checkpoint: {}",
            run_state.last_server_checkpoint.as_deref().unwrap_or("-")
        );
    }

    print_event_counts("Local Pending", &counts);

    let runtime = new_runtime()?;
    let client = SyncApiClient::new(config.base_url.clone(), Some(config.token.clone()))?;
    match runtime.block_on(client.repositories(&config.organization_id)) {
        Ok(allowlist) => {
            let partitioned = partition_eligible_sync_events(pending.clone(), &allowlist);
            println!("\nOrg Project Eligibility");
            println!("Recognized Repositories: {}", allowlist.repositories.len());
            println!("Eligible Pending Events: {}", partitioned.eligible.len());
            println!("Skipped Pending Events: {}", partitioned.skipped.len());
            println!(
                "Skipped Repositories: {}",
                partitioned.skipped_repo_keys.len()
            );
        }
        Err(err) => {
            println!("\nOrg Project Eligibility");
            println!("Warning: could not load recognized repositories: {err}");
        }
    }

    match runtime.block_on(client.status(&config.organization_id)) {
        Ok(remote) => {
            println!("\nRemote Status");
            println!(
                "Organization: {} ({})",
                remote
                    .organization_name
                    .as_deref()
                    .unwrap_or("(unnamed organization)"),
                remote.organization_id
            );
            println!("Stored Events: {}", remote.total_events);
            println!(
                "Last Event At: {}",
                remote.last_event_at.as_deref().unwrap_or("-")
            );
        }
        Err(err) => {
            let message = err.to_string();
            if message.contains("401") || message.contains("403") {
                return Err(err);
            }
            println!("\nRemote Status");
            println!("Unavailable: {message}");
        }
    }

    Ok(())
}

fn run_reset() -> Result<()> {
    let deleted = delete_saved_sync_config()?;
    let conn = db::open()?;
    reset_local_sync_state(&conn)?;
    if deleted {
        println!("Deleted saved sync configuration and cleared local sync state.");
    } else {
        println!("Cleared local sync state. No saved sync configuration was present.");
    }
    Ok(())
}

fn prompt_initial_config_flow() -> Result<()> {
    let config = prompt_sync_configuration()?;
    let path = save_sync_config(&config)?;
    println!("Saved sync configuration to {}", path.display());
    print_env_override_notice();
    Ok(())
}

fn prompt_existing_config_flow() -> Result<()> {
    println!("A saved sync configuration already exists.");
    print_env_override_notice();
    print!("Type `update` to replace it or `delete` to remove it: ");
    io::stdout().flush()?;
    let choice = read_line()?;
    match choice.as_str() {
        "update" | "u" => prompt_initial_config_flow(),
        "delete" | "d" => {
            delete_saved_sync_config()?;
            println!("Deleted saved sync configuration.");
            Ok(())
        }
        _ => bail!("Expected `update` or `delete`"),
    }
}

fn prompt_sync_configuration() -> Result<SavedSyncConfig> {
    let base_url = prompt_sync_api_base_url()?;
    let organization_id =
        parse_organization_setup_input(&prompt_line("PaceFlow organization ID or setup URL: ")?)?;
    let email = prompt_line("PaceFlow person email: ")?;

    let runtime = new_runtime()?;
    let unauthenticated = SyncApiClient::new(base_url.clone(), None)?;
    runtime.block_on(unauthenticated.request_person_link(&organization_id, &email))?;
    println!("Sent a PaceFlow CLI sync verification code to {email}.");
    let code = prompt_line("Verification code: ")?;
    let linked = runtime.block_on(unauthenticated.verify_person_link(
        &organization_id,
        &email,
        &code,
        &sync_identity::device_id(),
    ))?;

    Ok(SavedSyncConfig {
        base_url,
        organization_id: linked.organization_id,
        organization_name: linked.organization_name,
        member_email: Some(linked.member_email),
        token: linked.token,
    })
}

fn prompt_sync_api_base_url() -> Result<String> {
    print!("PaceFlow API base URL [{DEFAULT_SYNC_API_BASE_URL}]: ");
    io::stdout().flush()?;
    normalize_prompted_sync_api_base_url(&read_line()?)
}

fn normalize_prompted_sync_api_base_url(raw: &str) -> Result<String> {
    let value = raw.trim();
    if value.is_empty() {
        return normalized_base_url(DEFAULT_SYNC_API_BASE_URL);
    }
    normalized_base_url(value)
}

fn parse_organization_setup_input(raw: &str) -> Result<String> {
    let value = raw.trim();
    if value.is_empty() {
        bail!("PaceFlow organization ID cannot be empty");
    }
    if let Some((_, tail)) = value.split_once("/organizations/") {
        return tail
            .split(['/', '?', '#'])
            .next()
            .filter(|part| !part.trim().is_empty())
            .map(|part| part.trim().to_string())
            .ok_or_else(|| anyhow!("Could not read organization ID from setup URL"));
    }
    Ok(value.to_string())
}

fn print_env_override_notice() {
    let active = sync_env_fallback_keys()
        .iter()
        .copied()
        .filter(|key| std::env::var(key).ok().is_some())
        .collect::<Vec<_>>();
    if active.is_empty() {
        return;
    }

    println!(
        "{} is currently set but will be ignored because a saved sync configuration is now present. \
         Unset it (or run `paceflow sync reset`) if you intended to use the environment value.",
        active.join(", ")
    );
}

fn print_event_counts(label: &str, counts: &std::collections::BTreeMap<String, usize>) {
    println!("{label} Events");
    if counts.is_empty() {
        println!("  none");
        return;
    }
    for (event_type, count) in counts {
        println!("  {event_type}: {count}");
    }
}

fn format_source(source: SyncConfigSource) -> &'static str {
    match source {
        SyncConfigSource::Environment => "env",
        SyncConfigSource::Saved => "saved",
    }
}

fn prompt_line(prompt: &str) -> Result<String> {
    print!("{prompt}");
    io::stdout().flush()?;
    let value = read_line()?;
    if value.is_empty() {
        bail!("Input cannot be empty");
    }
    Ok(value)
}

fn read_line() -> Result<String> {
    let mut input = String::new();
    io::stdin().read_line(&mut input)?;
    Ok(input.trim().to_string())
}

fn new_runtime() -> Result<tokio::runtime::Runtime> {
    tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .map_err(Into::into)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn empty_sync_api_base_url_uses_local_backend_default() -> Result<()> {
        assert_eq!(
            normalize_prompted_sync_api_base_url("")?,
            DEFAULT_SYNC_API_BASE_URL
        );
        assert_eq!(
            normalize_prompted_sync_api_base_url("   ")?,
            DEFAULT_SYNC_API_BASE_URL
        );
        Ok(())
    }

    #[test]
    fn sync_api_base_url_still_accepts_explicit_url() -> Result<()> {
        assert_eq!(
            normalize_prompted_sync_api_base_url("http://localhost:3000/")?,
            "http://localhost:3000"
        );
        Ok(())
    }

    #[test]
    fn sync_api_base_url_rejects_non_url_values() {
        let err = normalize_prompted_sync_api_base_url("localhost:8443")
            .expect_err("missing scheme should fail");
        assert!(err.to_string().contains("http:// or https://"));
    }
}