kanzo 0.4.3

Self-hosted kanban for humans and agents. One 5.0 MB binary, starts in 3 ms, zero setup.
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
use std::fs::{self, File, OpenOptions, TryLockError};
use std::io;
use std::net::{IpAddr, Ipv4Addr};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};

use anyhow::{Context, Result, bail};
use serde::Deserialize;

use crate::store::{self, ImagesOf, Store};

pub const DEFAULT_PORT: u16 = 4242;

const CONFIG_TEMPLATE: &str = r#"# Kanzo settings.

# Port for the board at http://localhost:<port>.
port = 4242

# Address the board listens on. 127.0.0.1 keeps it on this machine. Use
# "0.0.0.0" to open it from other devices, for example when Kanzo runs on a
# Raspberry Pi with no screen. There are no logins: anyone who can reach the
# port can read and change the board, and use its MCP endpoint.
listen = "127.0.0.1"

# Also serve MCP over HTTP at http://localhost:<port>/mcp, for agents
# that cannot start `kanzo mcp` themselves.
mcp_http = true

# Names a reverse proxy on this machine passes the board on under, like
# "board.example.ts.net" for `tailscale serve`. Requests for them count as
# from another computer, so they can't open files or change sharing.
# hosts = ["board.example.ts.net"]

# The editor that file:/// links in tasks open in, as a full path. Without it,
# macOS uses your default text editor, and other systems can't open them.
# editor = "/usr/local/bin/cursor"
"#;

const GITIGNORE: &str = "\
# SQLite temporary files; kanzo sync makes sure kanzo.db is complete without them.
kanzo.db-journal
kanzo.db-wal
kanzo.db-shm
# Local to this machine.
kanzo.lock
*.bak
# macOS metadata (AppleDouble files appear on exFAT drives).
._*
.DS_Store
";

const LOCK_WAIT: Duration = Duration::from_secs(if cfg!(test) { 1 } else { 10 });

pub const NO_LOCKS: &str = "This folder doesn't support file locks: don't sync while agents are working.";

#[derive(Debug, Clone, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Config {
    pub port: u16,
    pub listen: IpAddr,
    /// Before 0.2 this set the columns. Still read, so older files keep working.
    #[serde(rename = "statuses")]
    _statuses: Option<toml::Value>,
    pub mcp_http: bool,
    pub editor: Option<PathBuf>,
    pub hosts: Vec<String>,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            port: DEFAULT_PORT,
            listen: IpAddr::V4(Ipv4Addr::LOCALHOST),
            _statuses: None,
            mcp_http: true,
            editor: None,
            hosts: Vec::new(),
        }
    }
}

#[derive(Debug, Clone)]
pub struct Home {
    pub dir: PathBuf,
    pub config: Config,
}

impl Home {
    pub fn resolve(flag: Option<PathBuf>) -> Result<PathBuf> {
        if let Some(dir) = flag {
            return Ok(dir);
        }
        if let Some(dir) = std::env::var_os("KANZO_HOME").filter(|v| !v.is_empty()) {
            return Ok(PathBuf::from(dir));
        }
        let home = dirs::home_dir().context("cannot find your home folder; set KANZO_HOME")?;
        Ok(home.join("kanzo"))
    }

    pub fn open(dir: PathBuf) -> Result<Self> {
        fs::create_dir_all(&dir).with_context(|| format!("cannot create {}", dir.display()))?;
        let dir = dir.canonicalize().unwrap_or(dir);
        write_if_missing(&dir.join(".gitignore"), GITIGNORE)?;

        let mut home = Self { dir, config: Config::default() };
        // During a pull, config.toml can be missing or another machine's, until kanzo sync puts it back.
        let lock = home.lock_shared()?;
        let path = home.dir.join("config.toml");
        // Holding the lock, this can only be left by a sync that died during a pull.
        let aside = home.config_aside();
        if aside.exists() {
            fs::rename(&aside, &path).with_context(|| format!("cannot restore {}", path.display()))?;
        }
        write_if_missing(&path, CONFIG_TEMPLATE)?;
        let text = fs::read_to_string(&path).with_context(|| format!("cannot read {}", path.display()))?;
        home.config = toml::from_str(&text).with_context(|| format!("{} is not valid", path.display()))?;
        drop(lock);

        home.store()?.migrate()?;
        Ok(home)
    }

    pub fn db_path(&self) -> PathBuf {
        self.dir.join("kanzo.db")
    }

    /// Where `kanzo sync` keeps this machine's config.toml during a pull; git ignores `*.bak`.
    pub fn config_aside(&self) -> PathBuf {
        self.dir.join("config.toml.bak")
    }

    /// Changes when the database file itself is replaced, as `kanzo sync` does
    /// when it pulls, so the board reloads even if the pulled change counter
    /// happens to equal the old one.
    pub fn db_identity(&self) -> u64 {
        #[cfg(unix)]
        {
            use std::os::unix::fs::MetadataExt;
            fs::metadata(self.db_path()).map(|m| m.ino()).unwrap_or(0)
        }
        // No inode on Windows; a replaced file has a new modified time. Not the creation
        // time: NTFS keeps it for a file replaced under the same name.
        #[cfg(not(unix))]
        {
            let modified = fs::metadata(self.db_path()).and_then(|m| m.modified()).ok();
            let since_epoch = modified.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok());
            since_epoch.map_or(0, |d| d.as_nanos() as u64)
        }
    }

    /// What changes with every write to the board: the file's identity and SQLite's change
    /// counter. Cheap enough to check every half second, without opening the board.
    pub fn db_stamp(&self) -> (u64, Option<[u8; 4]>) {
        (self.db_identity(), change_counter(&self.db_path()))
    }

    /// Callers keep it for one operation only, so a database replaced by `kanzo sync`
    /// is picked up on the next one. The shared lock lets sync wait for it to finish.
    pub fn store(&self) -> store::Result<Store> {
        Store::open(&self.db_path(), self.lock_shared()?)
    }

    fn lock_shared(&self) -> store::Result<Option<File>> {
        let lock = self.lock_file().map_err(|e| store::Error::Invalid(format!("{e:#}")))?;
        let deadline = Instant::now() + LOCK_WAIT;
        loop {
            match lock.try_lock_shared() {
                Ok(()) => return Ok(Some(lock)),
                Err(TryLockError::WouldBlock) if Instant::now() < deadline => {
                    std::thread::sleep(Duration::from_millis(25))
                }
                Err(TryLockError::WouldBlock) => {
                    return Err(store::Error::Busy("kanzo sync is updating the board; try again in a moment".into()));
                }
                Err(TryLockError::Error(e)) if unsupported(&e) => {
                    static WARN: std::sync::Once = std::sync::Once::new();
                    WARN.call_once(|| eprintln!("kanzo: {NO_LOCKS}"));
                    return Ok(None);
                }
                Err(TryLockError::Error(e)) => {
                    return Err(store::Error::Invalid(format!("cannot lock kanzo.lock: {e}")));
                }
            }
        }
    }

    pub fn open_file(&self, file: &Path) -> Result<(), String> {
        let mut cmd = editor_command(self.config.editor.as_deref(), file)?;
        let program = cmd.get_program().to_string_lossy().into_owned();
        let mut child = cmd
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()
            .map_err(|e| format!("cannot run {program}: {e}; set `editor` in config.toml to its full path"))?;
        // An editor's command can run for as long as the editor does: this isn't work for a database thread.
        std::thread::spawn(move || child.wait());
        Ok(())
    }

    pub fn images(&self) -> PathBuf {
        self.dir.join("images")
    }

    /// The same image can be attached in several places, and is stored once.
    pub fn deleting_images<T>(
        &self,
        store: &Store,
        of: ImagesOf,
        delete: impl FnOnce() -> store::Result<T>,
    ) -> store::Result<T> {
        let files = store.image_files(of)?;
        let deleted = delete()?;
        for file in store.unused_images(files)? {
            let _ = fs::remove_file(self.images().join(file));
        }
        Ok(deleted)
    }

    pub fn lock_exclusive(&self) -> Result<Option<File>> {
        let lock = self.lock_file()?;
        match lock.lock() {
            Ok(()) => Ok(Some(lock)),
            Err(e) if unsupported(&e) => Ok(None),
            Err(e) => Err(e).context("cannot lock kanzo.lock"),
        }
    }

    fn lock_file(&self) -> Result<File> {
        let path = self.dir.join("kanzo.lock");
        OpenOptions::new()
            .create(true)
            .truncate(false)
            .write(true)
            .open(&path)
            .with_context(|| format!("cannot open {}", path.display()))
    }
}

/// Anyone who can comment can write a file link, so opening one must never run anything. Only an
/// editor, then, not a generic opener: `open` with no flags runs a `.command` file, `xdg-open` a
/// `.desktop` file, and Windows `start` a program.
fn editor_command(editor: Option<&Path>, file: &Path) -> Result<Command, String> {
    if !file.is_absolute() || !file.is_file() {
        return Err(format!("{} is not a file on this computer", file.display()));
    }
    let mut cmd = match editor {
        Some(editor) => Command::new(editor),
        None if cfg!(target_os = "macos") => {
            let mut open = Command::new("open");
            open.arg("-t");
            open
        }
        None => return Err("set `editor` in config.toml to open files, as the full path of your editor".into()),
    };
    cmd.arg(file);
    Ok(cmd)
}

/// Some filesystems (exFAT, network shares) have no file locks: Kanzo goes on without.
fn unsupported(e: &io::Error) -> bool {
    #[cfg(unix)]
    if matches!(e.raw_os_error(), Some(libc::ENOTSUP | libc::ENOLCK)) {
        return true;
    }
    e.kind() == io::ErrorKind::Unsupported
}

fn write_if_missing(path: &Path, contents: &str) -> Result<()> {
    if !path.exists() {
        fs::write(path, contents).with_context(|| format!("cannot write {}", path.display()))?;
    }
    Ok(())
}

pub fn output(cmd: &mut Command) -> Result<String> {
    let line: Vec<_> = std::iter::once(cmd.get_program()).chain(cmd.get_args()).map(|a| a.to_string_lossy()).collect();
    let line = line.join(" ");
    let out = cmd
        .output()
        .with_context(|| format!("cannot run {}; is it installed?", line.split(' ').next().unwrap_or_default()))?;
    if !out.status.success() {
        bail!("{line} failed: {}", String::from_utf8_lossy(&out.stderr).trim());
    }
    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
}

pub fn hostname() -> String {
    let name = |cmd: &mut Command| output(cmd).ok().filter(|n| !n.is_empty());
    name(Command::new("scutil").args(["--get", "ComputerName"]))
        .or_else(|| name(&mut Command::new("hostname")))
        .unwrap_or_else(|| "unknown".into())
}

pub fn write_whole(path: &Path, bytes: &[u8]) -> io::Result<()> {
    if let Some(dir) = path.parent() {
        fs::create_dir_all(dir)?;
    }
    // A half-written file never takes the real name.
    let partial = path.with_extension("part");
    fs::write(&partial, bytes)?;
    fs::rename(&partial, path)
}

/// SQLite's file change counter, 4 bytes at offset 24 of kanzo.db. With Kanzo's rollback journal
/// and normal locking, every commit from any process bumps it; in WAL mode or with exclusive
/// locking it wouldn't, and a reader waiting on changes would hear of them only when its wait
/// ends. It's read on the caller's thread: 28 bytes of a file the system has cached cost less
/// than handing them to a helper thread. None if it can't be read, as while kanzo sync swaps the
/// file: then the board is read to find out.
pub(crate) fn change_counter(db: &Path) -> Option<[u8; 4]> {
    use std::io::Read;
    let mut head = [0; 28];
    File::open(db).ok()?.read_exact(&mut head).ok()?;
    Some([head[24], head[25], head[26], head[27]])
}

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

    #[test]
    fn first_open_creates_files() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("data");
        let home = Home::open(dir.clone()).unwrap();
        assert!(dir.join("config.toml").exists());
        assert!(dir.join(".gitignore").exists());
        assert!(dir.join("kanzo.db").exists());
        assert_eq!(home.config.port, DEFAULT_PORT);
        assert!(home.config.mcp_http);
        assert!(home.config.listen.is_loopback());
    }

    #[test]
    fn statuses_from_before_0_2_are_ignored() {
        let tmp = tempfile::tempdir().unwrap();
        fs::write(tmp.path().join("config.toml"), "statuses = [\"todo\", \"doing\", \"done\"]\n").unwrap();
        let home = Home::open(tmp.path().to_path_buf()).unwrap();
        assert_eq!(home.store().unwrap().statuses(), ["todo", "doing", "review", "done"]);
    }

    #[test]
    fn waits_for_sync_then_reports_busy() {
        let tmp = tempfile::tempdir().unwrap();
        let home = Home::open(tmp.path().to_path_buf()).unwrap();
        let lock = home.lock_exclusive().unwrap();
        assert!(matches!(home.store(), Err(store::Error::Busy(_))));

        let waiting = std::thread::spawn({
            let home = home.clone();
            move || home.store().map(|s| s.statuses().len())
        });
        std::thread::sleep(Duration::from_millis(200));
        assert!(!waiting.is_finished());
        drop(lock);
        assert_eq!(waiting.join().unwrap().unwrap(), 4);
    }

    #[test]
    fn a_file_link_opens_in_an_editor_and_only_a_file() {
        let tmp = tempfile::tempdir().unwrap();
        let file = tmp.path().join("run.command");
        fs::write(&file, "").unwrap();
        let args = |cmd: &Command| cmd.get_args().map(|a| a.to_owned()).collect::<Vec<_>>();

        let cmd = editor_command(Some(Path::new("/bin/cursor")), &file).unwrap();
        assert_eq!(cmd.get_program(), "/bin/cursor");
        assert_eq!(args(&cmd), [file.as_os_str()]);
        if cfg!(target_os = "macos") {
            let cmd = editor_command(None, &file).unwrap();
            assert_eq!(cmd.get_program(), "open");
            assert_eq!(args(&cmd), [std::ffi::OsStr::new("-t"), file.as_os_str()]);
        } else {
            assert!(editor_command(None, &file).is_err_and(|e| e.contains("editor")));
        }

        let editor = Some(Path::new("/bin/cursor"));
        for bad in [Path::new("run.command"), tmp.path(), &tmp.path().join("missing")] {
            assert!(editor_command(editor, bad).is_err(), "{}", bad.display());
        }
    }

    #[test]
    fn open_waits_for_a_pull_to_put_config_toml_back() {
        let tmp = tempfile::tempdir().unwrap();
        let home = Home::open(tmp.path().to_path_buf()).unwrap();
        let config = home.dir.join("config.toml");
        let lock = home.lock_exclusive().unwrap();
        fs::write(&config, "listen = \"0.0.0.0\"\n").unwrap();

        let opening = std::thread::spawn({
            let dir = home.dir.clone();
            move || Home::open(dir)
        });
        std::thread::sleep(Duration::from_millis(200));
        assert!(!opening.is_finished());
        fs::write(&config, "listen = \"127.0.0.1\"\n").unwrap();
        drop(lock);
        assert!(opening.join().unwrap().unwrap().config.listen.is_loopback());
    }

    #[test]
    fn open_restores_a_config_toml_left_aside_by_a_crash() {
        let tmp = tempfile::tempdir().unwrap();
        fs::write(tmp.path().join("config.toml.bak"), "listen = \"0.0.0.0\"\n").unwrap();
        // What git had pulled when the sync died.
        fs::write(tmp.path().join("config.toml"), "port = 4300\n").unwrap();

        let home = Home::open(tmp.path().to_path_buf()).unwrap();
        assert!(!home.config.listen.is_loopback());
        assert_eq!(home.config.port, DEFAULT_PORT);
        assert!(!home.config_aside().exists());
    }

    #[test]
    fn no_lock_only_when_unsupported() {
        assert!(unsupported(&io::Error::from(io::ErrorKind::Unsupported)));
        #[cfg(unix)]
        assert!(unsupported(&io::Error::from_raw_os_error(libc::ENOLCK)));
        assert!(!unsupported(&io::Error::from(io::ErrorKind::PermissionDenied)));
    }
}