rekon 0.0.11

Reconstruct where your time and compute went: account for agentic work on two axes and review a daily ledger instead of keeping a timesheet.
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
//! Command handlers and the glue between config, connectors, and the core pipeline.

use std::io;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result, bail};
use jiff::Zoned;
use jiff::civil::Date;
use tracing::info;

use rekon_core::config::Config;
use rekon_core::model::LedgerStatus;
use rekon_core::report::{Emitter, JsonEmitter, TextEmitter};
use rekon_core::store::{Store, open_store};

use crate::cli::{Cli, Command, Format};

/// Dispatch a parsed command.
pub fn run(cli: Cli) -> Result<()> {
    let config_path = cli.config.unwrap_or_else(default_config_path);
    match cli.command {
        Command::Init { force } => cmd_init(&config_path, force),
        Command::Reconstruct {
            date,
            repos,
            force,
            llm,
            dry_run,
        } => {
            let mut cfg = load_config(&config_path)?;
            if llm {
                let mut llm_cfg = cfg.attribution.llm.unwrap_or_default();
                llm_cfg.enabled = true;
                cfg.attribution.llm = Some(llm_cfg);
            }
            cmd_reconstruct(&cfg, date, &repos, force, dry_run)
        }
        Command::Review { date, format, edit } => {
            let cfg = load_config(&config_path)?;
            cmd_review(&cfg, date, format, edit)
        }
        Command::Approve { date } => {
            let cfg = load_config(&config_path)?;
            cmd_approve(&cfg, date)
        }
        Command::Unapprove { date } => {
            let cfg = load_config(&config_path)?;
            cmd_unapprove(&cfg, date)
        }
        Command::Publish {
            date,
            target,
            dry_run,
        } => {
            let cfg = load_config(&config_path)?;
            cmd_publish(&cfg, date, target, dry_run)
        }
        Command::Config => cmd_config(&config_path),
    }
}

fn cmd_init(path: &Path, force: bool) -> Result<()> {
    if path.exists() && !force {
        bail!(
            "{} already exists; pass --force to overwrite",
            path.display()
        );
    }
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    std::fs::write(path, Config::default().to_toml()?)?;
    println!("wrote {}", path.display());
    Ok(())
}

fn cmd_reconstruct(
    cfg: &Config,
    date: Option<Date>,
    repos: &[PathBuf],
    force: bool,
    dry_run: bool,
) -> Result<()> {
    let date = date.unwrap_or_else(today);
    let store = open_store(&cfg.store)?;

    // Don't discard an approved day by rebuilding over it. The server enforces the
    // same invariant (it returns 409); --force is the escape hatch.
    if !dry_run
        && !force
        && let Ok(existing) = store.load_ledger(date)
        && existing.status == LedgerStatus::Approved
    {
        bail!("{date} is approved; pass --force to rebuild and discard the approval");
    }

    let (ledger, events) = rekon_connectors::reconstruct_day(cfg, date, repos)?;
    if !dry_run {
        store.save_events(date, &events)?;
        store.save_ledger(&ledger)?;
    }

    let mut out = io::stdout().lock();
    TextEmitter.emit(&ledger, &mut out)?;
    Ok(())
}

fn cmd_review(cfg: &Config, date: Option<Date>, format: Format, edit: bool) -> Result<()> {
    let date = date.unwrap_or_else(today);
    let store = open_store(&cfg.store)?;
    let ledger = store.load_ledger(date).with_context(|| {
        format!("no ledger for {date}; run `rekon reconstruct --date {date}` first")
    })?;
    if edit {
        return review_edit(&*store, ledger);
    }
    let mut out = io::stdout().lock();
    match format {
        Format::Text => TextEmitter.emit(&ledger, &mut out)?,
        Format::Json => JsonEmitter { pretty: true }.emit(&ledger, &mut out)?,
    }
    Ok(())
}

// Write the draft to a temp file, open it in the editor, then apply the edits and
// approve. On any error the stored draft is left untouched.
fn review_edit(store: &dyn Store, ledger: rekon_core::Ledger) -> Result<()> {
    let path = std::env::temp_dir().join(format!("rekon-{}.toml", ledger.date));
    std::fs::write(&path, rekon_core::review::to_editable_toml(&ledger))?;

    launch_editor(&path)?;

    let edited = std::fs::read_to_string(&path)?;
    let updated =
        rekon_core::review::apply_edits(&ledger, &edited).context("applying your edits")?;
    store.save_ledger(&updated)?;
    let _ = std::fs::remove_file(&path);

    let mut out = io::stdout().lock();
    TextEmitter.emit(&updated, &mut out)?;
    eprintln!("approved {}", updated.date);
    Ok(())
}

fn launch_editor(path: &Path) -> Result<()> {
    let editor = std::env::var("VISUAL")
        .or_else(|_| std::env::var("EDITOR"))
        .unwrap_or_else(|_| "vi".to_string());
    // Split so "$EDITOR" values like "code --wait" work; the file is the last arg.
    let mut parts = editor.split_whitespace();
    let program = parts.next().unwrap_or("vi");
    let mut command = std::process::Command::new(program);
    for arg in parts {
        command.arg(arg);
    }
    command.arg(path);
    let status = command
        .status()
        .with_context(|| format!("launching editor `{editor}`"))?;
    if !status.success() {
        anyhow::bail!("editor exited with a non-zero status; the day was not changed");
    }
    Ok(())
}

fn cmd_approve(cfg: &Config, date: Option<Date>) -> Result<()> {
    let date = date.unwrap_or_else(today);
    let store = open_store(&cfg.store)?;
    let mut ledger = store
        .load_ledger(date)
        .with_context(|| format!("no ledger for {date}"))?;
    ledger.status = LedgerStatus::Approved;
    store.save_ledger(&ledger)?;
    println!("approved {date}");
    Ok(())
}

fn cmd_unapprove(cfg: &Config, date: Option<Date>) -> Result<()> {
    let date = date.unwrap_or_else(today);
    let store = open_store(&cfg.store)?;
    let mut ledger = store
        .load_ledger(date)
        .with_context(|| format!("no ledger for {date}"))?;
    ledger.status = LedgerStatus::Draft;
    store.save_ledger(&ledger)?;
    println!("unapproved {date}");
    Ok(())
}

fn cmd_publish(
    cfg: &Config,
    date: Option<Date>,
    target: Option<String>,
    dry_run: bool,
) -> Result<()> {
    let date = date.unwrap_or_else(today);
    let store = open_store(&cfg.store)?;
    let ledger = store
        .load_ledger(date)
        .with_context(|| format!("no ledger for {date}"))?;

    if ledger.status != LedgerStatus::Approved {
        bail!("ledger for {date} is not approved; run `rekon approve --date {date}` first");
    }

    let mut publishers: Vec<Box<dyn rekon_core::publisher::Publisher>> = Vec::new();
    let target_lower = target.map(|t| t.to_ascii_lowercase());

    if let Some(gh) = &cfg.publishers.github
        && gh.enabled
        && target_lower.as_deref().is_none_or(|t| t == "github")
    {
        publishers.push(Box::new(rekon_connectors::GitHubPublisher::from_config(gh)));
    }
    if let Some(gl) = &cfg.publishers.gitlab
        && gl.enabled
        && target_lower.as_deref().is_none_or(|t| t == "gitlab")
    {
        publishers.push(Box::new(rekon_connectors::GitLabPublisher::from_config(gl)));
    }

    if publishers.is_empty() {
        bail!("no enabled publishers matched; configure [publishers] in your config");
    }

    if dry_run {
        println!("Dry run for {date}:");
        let entries = rekon_core::publisher::publishable_entries(&ledger);
        println!("  Publishable items ({}):", entries.len());
        for e in entries {
            let piece_str = e
                .piece
                .as_deref()
                .map(|p| format!("[{p}] "))
                .unwrap_or_default();
            let issue_str = e
                .issue
                .as_ref()
                .map(|i| format!(" -> {}", i.name))
                .unwrap_or_default();
            println!("    - {}{}{}", piece_str, e.work.label, issue_str);
        }
        return Ok(());
    }

    let previous_receipts = store.load_receipts(date).unwrap_or_default();
    for pub_inst in publishers {
        let receipt = pub_inst
            .publish_with_history(&ledger, &previous_receipts)
            .with_context(|| format!("publishing to {}", pub_inst.name()))?;
        store.save_receipt(date, &receipt)?;
        println!("published {date} to {}:", receipt.destination);
        for item in &receipt.items {
            let issue_str = item
                .issue
                .as_ref()
                .map(|i| format!(" ({})", i.name))
                .unwrap_or_default();
            println!("  - {}{}: {}", item.work_label, issue_str, item.status);
        }
    }

    Ok(())
}

fn cmd_config(path: &Path) -> Result<()> {
    println!("config: {}", path.display());
    let cfg = load_config(path)?;
    println!("store:  {}", cfg.store.dir.display());
    Ok(())
}

fn load_config(path: &Path) -> Result<Config> {
    if path.exists() {
        Config::load(path).with_context(|| format!("loading config {}", path.display()))
    } else {
        info!(path = %path.display(), "no config file; using defaults");
        Ok(Config::default())
    }
}

fn today() -> Date {
    Zoned::now().date()
}

fn default_config_path() -> PathBuf {
    match std::env::var_os("HOME") {
        Some(home) => PathBuf::from(home).join(".config/rekon/rekon.toml"),
        None => PathBuf::from("rekon.toml"),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rekon_core::config::{Config, GitHubPublisherConfig, PublishersConfig};
    use rekon_core::model::{Cost, Ledger, LedgerEntry, LedgerStatus, WorkItem};
    use tempfile::tempdir;

    fn test_ledger(date: Date, status: LedgerStatus) -> Ledger {
        Ledger {
            date,
            status,
            entries: vec![LedgerEntry {
                work: WorkItem {
                    label: "feat: add feature".into(),
                    reference: None,
                },
                attention_secs: 3600,
                compute: Cost::default(),
                compute_secs: 0,
                evidence: vec![],
                confidence: 1.0,
                piece: None,
                issue: None,
                excluded: false,
                llm: None,
            }],
            pieces: vec![],
            generated_at: jiff::Timestamp::now(),
        }
    }

    #[test]
    fn init_creates_file_and_fails_without_force() {
        let dir = tempdir().unwrap();
        let config_file = dir.path().join("sub/rekon.toml");

        assert!(cmd_init(&config_file, false).is_ok());
        assert!(config_file.exists());

        // Fails when existing without force
        assert!(cmd_init(&config_file, false).is_err());

        // Succeeds with force
        assert!(cmd_init(&config_file, true).is_ok());
    }

    #[test]
    fn approve_and_unapprove_toggle_status() {
        let dir = tempdir().unwrap();
        let mut cfg = Config::default();
        cfg.store.dir = dir.path().to_path_buf();

        let date = jiff::civil::date(2026, 11, 21);
        let store = open_store(&cfg.store).unwrap();
        store
            .save_ledger(&test_ledger(date, LedgerStatus::Draft))
            .unwrap();

        assert!(cmd_approve(&cfg, Some(date)).is_ok());
        assert_eq!(
            store.load_ledger(date).unwrap().status,
            LedgerStatus::Approved
        );

        assert!(cmd_unapprove(&cfg, Some(date)).is_ok());
        assert_eq!(store.load_ledger(date).unwrap().status, LedgerStatus::Draft);
    }

    #[test]
    fn publish_enforces_approved_ledger_and_publisher() {
        let dir = tempdir().unwrap();
        let mut cfg = Config::default();
        cfg.store.dir = dir.path().to_path_buf();

        let date = jiff::civil::date(2026, 11, 21);
        let store = open_store(&cfg.store).unwrap();

        // 1. Missing ledger fails
        assert!(cmd_publish(&cfg, Some(date), None, false).is_err());

        // 2. Draft ledger fails
        store
            .save_ledger(&test_ledger(date, LedgerStatus::Draft))
            .unwrap();
        let err = cmd_publish(&cfg, Some(date), None, false).unwrap_err();
        assert!(err.to_string().contains("is not approved"));

        // 3. Approved ledger but no publishers configured fails
        store
            .save_ledger(&test_ledger(date, LedgerStatus::Approved))
            .unwrap();
        let err = cmd_publish(&cfg, Some(date), None, false).unwrap_err();
        assert!(err.to_string().contains("no enabled publishers matched"));

        // 4. Approved ledger with unknown target fails
        cfg.publishers = PublishersConfig {
            github: Some(GitHubPublisherConfig {
                enabled: true,
                token: None,
                url: None,
                token_env: None,
                project_owner: None,
                project_number: None,
                post_comments: false,
                attention_field: None,
                compute_field: None,
            }),
            gitlab: None,
        };
        let err = cmd_publish(&cfg, Some(date), Some("gitlab".into()), false).unwrap_err();
        assert!(err.to_string().contains("no enabled publishers matched"));

        // 5. Dry run succeeds
        assert!(cmd_publish(&cfg, Some(date), Some("github".into()), true).is_ok());
    }

    #[test]
    fn config_command_succeeds() {
        let dir = tempdir().unwrap();
        let config_file = dir.path().join("rekon.toml");
        assert!(cmd_config(&config_file).is_ok());
    }

    #[test]
    fn load_config_defaults_and_file() {
        let dir = tempdir().unwrap();
        let config_file = dir.path().join("rekon.toml");
        // Nonexistent file returns defaults
        let default_cfg = load_config(&config_file).unwrap();
        assert_eq!(default_cfg.store.dir, Config::default().store.dir);

        // Saved valid config file
        cmd_init(&config_file, false).unwrap();
        let loaded = load_config(&config_file).unwrap();
        assert_eq!(loaded.store.dir, Config::default().store.dir);
    }
}