Skip to content

armgit / kanzo

Public Imported from GitHub
0

Self-hosted, sharable kanban for humans and agents. One 4.7 MB binary, 5 MB of RAM, 10 to 60 tokens per agent reply, starts in 3 ms, zero setup.

Link several repos to one project

emanuele-emcb04738ef03f
diff --git a/README.md b/README.md
index a94f5c6..f04fcac 100644
--- a/README.md
+++ b/README.md
@@ -43,7 +43,7 @@ codex mcp add kanzo -- kanzo mcp # Codex
Other MCP clients: run `kanzo mcp` (apps like Raycast need the full path, from `which kanzo`), or use the running board at `http://localhost:4242/mcp`.
-Then ask: *"take the next task from kanzo and do it."* The agent moves the card to `doing` and comments as it works. It finds the right project from the git remote of the repo it works in.
+Then ask: *"take the next task from kanzo and do it."* The agent moves the card to `doing` and comments as it works. It finds the right project from the git remote of the repo it works in; link more repos to a project from its ⋯ menu.
<picture>
<source media="(prefers-color-scheme: dark)" srcset="docs/img/task-dark.jpg">
diff --git a/src/app.js b/src/app.js
index 0f4b7fa..76eedea 100644
--- a/src/app.js
+++ b/src/app.js
@@ -311,10 +311,28 @@ function toggleProjectMenu(p, button) {
current ? icon("check") : null);
}));
drawSwatches();
+ // Linked repos, each with an unlink button, and a field to link another.
+ const repos = el("div", { class: "repos" });
+ const drawRepos = (list, focus) => {
+ const input = el("input", { class: "field", placeholder: "Link a repo: owner/repo", "aria-label": "Link a GitHub repo",
+ autocomplete: "off", spellcheck: "false" });
+ input.addEventListener("keydown", async (e) => {
+ if (e.key !== "Enter" || !input.value.trim()) return;
+ const q = await changeRepo(p.slug, "POST", input.value);
+ if (q) drawRepos(q.repos, true);
+ });
+ repos.replaceChildren(...list.map((r) => el("div", { class: "repo" }, el("span", { class: "name" }, r),
+ el("button", { class: "unlink", title: `Unlink ${r}`, "aria-label": `Unlink ${r}`,
+ onclick: async () => { const q = await changeRepo(p.slug, "DELETE", r); if (q) drawRepos(q.repos); } },
+ icon("close")))), input);
+ if (focus) input.focus();
+ };
+ drawRepos(p.repos);
const remove = el("button", { class: "danger", onclick: () => { closeMenu(); deleteProject(p); } },
icon("trash"), "Delete project");
const menu = el("div", { class: "menu", role: "menu", tabindex: "-1" },
- el("div", { class: "label" }, "Color"), swatches, el("div", { class: "sep" }), remove);
+ el("div", { class: "label" }, "Color"), swatches, el("div", { class: "label" }, "Repos"), repos,
+ el("div", { class: "sep" }), remove);
document.body.append(menu);
const r = button.getBoundingClientRect();
const below = r.bottom + 4 + menu.offsetHeight <= innerHeight;
@@ -324,6 +342,15 @@ function toggleProjectMenu(p, button) {
menu.focus();
}
+// Links (POST) or unlinks (DELETE) a repo; returns the project, or null after showing the error.
+async function changeRepo(slug, method, repo) {
+ try {
+ const p = await api(method, `/projects/${encodeURIComponent(slug)}/repos`, { repo });
+ loadBoard();
+ return p;
+ } catch (err) { toast(err.message); return null; }
+}
+
async function pickColor(slug, color) {
try {
await api("PATCH", `/projects/${encodeURIComponent(slug)}`, { color });
@@ -369,7 +396,7 @@ function renderHeader() {
header.replaceChildren(
el("h1", {}, p.name),
el("span", { class: "sub mono" }, p.slug),
- ...(p.repo ? [el("span", { class: "sub" }, el("a", { href: `https://github.com/${p.repo}`, target: "_blank", rel: "noopener" }, p.repo))] : []),
+ ...p.repos.map((r) => el("span", { class: "sub" }, el("a", { href: `https://github.com/${r}`, target: "_blank", rel: "noopener" }, r))),
);
}
diff --git a/src/export.rs b/src/export.rs
index c14f040..4f7c9dd 100644
--- a/src/export.rs
+++ b/src/export.rs
@@ -97,7 +97,8 @@ fn collect(store: &Store, only: Option<&str>) -> Result<Board> {
fn markdown(board: &Board) -> String {
let mut md = format!("# Kanzo board\n\nExported {}.\n", short_time(&board.exported_at));
for p in &board.projects {
- let repo = p.project.repo.as_deref().map(|r| format!(" ([{r}](https://github.com/{r}))")).unwrap_or_default();
+ let links: Vec<String> = p.project.repos.iter().map(|r| format!("[{r}](https://github.com/{r})")).collect();
+ let repo = if links.is_empty() { String::new() } else { format!(" ({})", links.join(", ")) };
let _ = write!(
md,
"\n## {} `{}`{repo}\n\n{} open of {} {}.\n",
diff --git a/src/index.html b/src/index.html
index ff0b6e9..828e267 100644
--- a/src/index.html
+++ b/src/index.html
@@ -87,6 +87,13 @@ aside {
.menu .swatch:hover, .menu .swatch:focus-visible { transform: scale(1.15); }
.menu .swatch .icon svg { width: 13px; height: 13px; stroke-width: 3; }
.menu .sep { height: 1px; background: var(--border); margin: 0 4px 6px; }
+.menu .repos { display: flex; flex-direction: column; gap: 2px; padding: 6px 6px 10px; }
+.menu .repo { display: flex; align-items: center; gap: 6px; padding: 2px 0 2px 4px; }
+.menu .repo .name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 13px; }
+.menu .repo .unlink { width: auto; padding: 4px; color: var(--faint); }
+.menu .repo .unlink:hover { color: var(--danger); background: var(--danger-bg); }
+.menu .repo .unlink .icon svg { width: 14px; height: 14px; }
+.menu .repos input { margin-top: 4px; padding: 6px 10px; border-radius: 10px; font-size: 13px; }
.menu button.danger:hover, .menu button.danger:focus-visible { background: var(--danger-bg); }
form.new-project { display: flex; flex-direction: column; gap: 6px; padding: 4px 2px 10px; }
form.new-project .row { display: flex; gap: 6px; margin-top: 2px; }
diff --git a/src/mcp.rs b/src/mcp.rs
index d59340b..3a9b494 100644
--- a/src/mcp.rs
+++ b/src/mcp.rs
@@ -88,7 +88,7 @@ impl Ctx {
let msg = match (self.repos.first(), known.is_empty()) {
(Some(repo), false) => format!(
"No project is linked to {repo} (the git remote of {cwd}). Pass `project` (one of: {known}), \
- or link this repo by calling create_project with repo \"{repo}\"."
+ link this repo to one with link_repo, or create a project for it with create_project and repo \"{repo}\"."
),
(Some(repo), true) => format!(
"No project is linked to {repo} (the git remote of {cwd}), and there are no projects yet. \
@@ -207,6 +207,14 @@ struct AddCommentArgs {
author: Option<String>,
}
+#[derive(Deserialize, JsonSchema)]
+struct LinkRepoArgs {
+ /// Project slug.
+ project: String,
+ /// GitHub repo as owner/repo.
+ repo: String,
+}
+
#[derive(Deserialize, JsonSchema)]
struct NextTaskArgs {
/// Project slug, or "all" for any project. Defaults to the project of the current repo.
@@ -253,12 +261,13 @@ impl Kanzo {
if projects.is_empty() {
return Ok("No projects yet. Create one with create_project.".into());
}
- let here = projects.iter().find(|p| p.repo.as_ref().is_some_and(|r| ctx.repos.contains(r)));
+ let here = projects.iter().find(|p| p.repos.iter().any(|r| ctx.repos.contains(r)));
Ok(projects
.iter()
.map(|p| {
let name = if p.name == p.slug { String::new() } else { format!(" \"{}\"", p.name) };
- let repo = p.repo.as_deref().map(|r| format!(" ({r})")).unwrap_or_default();
+ let repo =
+ if p.repos.is_empty() { String::new() } else { format!(" ({})", p.repos.join(", ")) };
let mark = if here.is_some_and(|h| h.id == p.id) { " <- current repo" } else { "" };
format!("{}{name}{repo}: {} open of {}{mark}", p.slug, p.open, p.total)
})
@@ -276,12 +285,22 @@ impl Kanzo {
Ok(self
.run(move |_, store| {
let p = store.create_project(&args.slug, args.name.as_deref().unwrap_or(""), args.repo.as_deref())?;
- let repo = p.repo.as_deref().map(|r| format!(", linked to {r}")).unwrap_or_default();
+ let repo = p.repos.first().map(|r| format!(", linked to {r}")).unwrap_or_default();
Ok(format!("Created project {} ({}){repo}.", p.slug, p.name))
})
.await)
}
+ #[tool(description = "Link another GitHub repo to a project, so agents working in it find the project.")]
+ async fn link_repo(&self, Parameters(args): Parameters<LinkRepoArgs>) -> Result<CallToolResult, ErrorData> {
+ Ok(self
+ .run(move |_, store| {
+ let p = store.link_repo(&args.project, &args.repo)?;
+ Ok(format!("Project {} is linked to {}.", p.slug, p.repos.join(", ")))
+ })
+ .await)
+ }
+
#[tool(description = "List tasks one per line, in board order. Leaves out done tasks unless `status` is given.")]
async fn list_tasks(&self, Parameters(args): Parameters<ListTasksArgs>) -> Result<CallToolResult, ErrorData> {
Ok(self
diff --git a/src/store.rs b/src/store.rs
index e9f0a77..baabf9e 100644
--- a/src/store.rs
+++ b/src/store.rs
@@ -19,6 +19,17 @@ const MIGRATIONS: &[&str] = &[
"ALTER TABLE projects ADD COLUMN color TEXT;",
// 3: a task's tags, comma-separated (see `clean_tags`).
"ALTER TABLE tasks ADD COLUMN tags TEXT NOT NULL DEFAULT '';",
+ // 4: any number of repos per project. Each repo belongs to one project. The old
+ // projects.repo column stays, empty: SQLite can only drop it by rebuilding the table.
+ "CREATE TABLE project_repos (
+ repo TEXT PRIMARY KEY,
+ project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE
+ );
+ CREATE INDEX project_repos_by_project ON project_repos(project_id);
+ INSERT INTO project_repos (repo, project_id) SELECT repo, id FROM projects WHERE repo IS NOT NULL;
+ UPDATE projects SET repo = NULL;
+ CREATE TRIGGER project_repos_insert AFTER INSERT ON project_repos BEGIN UPDATE meta SET value = value + 1 WHERE key = 'changes'; END;
+ CREATE TRIGGER project_repos_delete AFTER DELETE ON project_repos BEGIN UPDATE meta SET value = value + 1 WHERE key = 'changes'; END;",
];
/// The colours a project can be given; the board maps each name to a shade.
@@ -66,7 +77,8 @@ pub struct Project {
pub id: i64,
pub slug: String,
pub name: String,
- pub repo: Option<String>,
+ /// Linked GitHub repos as `owner/repo`, in the order they were linked.
+ pub repos: Vec<String>,
/// One of `PROJECT_COLORS`, or `None` when never picked.
pub color: Option<String>,
pub created_at: String,
@@ -225,7 +237,9 @@ impl Store {
// Projects
- const PROJECT_SELECT: &str = "SELECT p.id, p.slug, p.name, p.repo, p.color, p.created_at,
+ const PROJECT_SELECT: &str = "SELECT p.id, p.slug, p.name,
+ (SELECT group_concat(repo, ',' ORDER BY r.rowid) FROM project_repos r WHERE r.project_id = p.id),
+ p.color, p.created_at,
(SELECT count(*) FROM tasks t WHERE t.project_id = p.id AND t.status <> ?1),
(SELECT count(*) FROM tasks t WHERE t.project_id = p.id)
FROM projects p";
@@ -235,7 +249,7 @@ impl Store {
id: r.get(0)?,
slug: r.get(1)?,
name: r.get(2)?,
- repo: r.get(3)?,
+ repos: r.get::<_, Option<String>>(3)?.map(|s| s.split(',').map(String::from).collect()).unwrap_or_default(),
color: r.get(4)?,
created_at: r.get(5)?,
open: r.get(6)?,
@@ -261,7 +275,7 @@ impl Store {
pub fn project_by_repo(&self, repo: &str) -> Result<Option<Project>> {
match repo_from_url(repo) {
- Some(repo) => self.project_where("p.repo = ?2", &repo),
+ Some(repo) => self.project_where("p.id = (SELECT project_id FROM project_repos WHERE repo = ?2)", &repo),
None => Ok(None),
}
}
@@ -296,31 +310,72 @@ impl Store {
"" => slug.clone(),
n => n.to_string(),
};
- let repo = match repo.map(str::trim).filter(|r| !r.is_empty()) {
- None => None,
- Some(r) => Some(
- repo_from_url(r).ok_or_else(|| Error::Invalid(format!("repo {r:?} should look like owner/repo")))?,
- ),
- };
+ let repo = repo.map(str::trim).filter(|r| !r.is_empty()).map(clean_repo).transpose()?;
if self.project_by_slug(&slug)?.is_some() {
return Err(Error::Invalid(format!("project {slug} already exists")));
}
- if let Some(r) = &repo
- && let Some(other) = self.project_by_repo(r)?
- {
- return Err(Error::Invalid(format!("repo {r} is already linked to project {}", other.slug)));
+ if let Some(r) = &repo {
+ self.check_repo_free(r)?;
+ }
+ let created = self.write(|c| {
+ c.execute("INSERT INTO projects (slug, name) VALUES (?1, ?2)", params![slug, name])?;
+ if let Some(r) = &repo {
+ c.execute(
+ "INSERT INTO project_repos (repo, project_id) VALUES (?1, ?2)",
+ params![r, c.last_insert_rowid()],
+ )?;
+ }
+ Ok(())
+ });
+ match created {
+ // Someone created the same project or linked the repo between our checks and the insert.
+ Err(Error::Db(rusqlite::Error::SqliteFailure(e, _)))
+ if e.code == rusqlite::ErrorCode::ConstraintViolation =>
+ {
+ Err(Error::Invalid(format!("project {slug} or its repo already exists")))
+ }
+ other => other,
+ }?;
+ self.find_project(&slug)
+ }
+
+ /// Links another repo to a project. Each repo belongs to one project.
+ pub fn link_repo(&self, slug: &str, repo: &str) -> Result<Project> {
+ let project = self.find_project(slug)?;
+ let repo = clean_repo(repo)?;
+ if project.repos.contains(&repo) {
+ return Ok(project);
}
+ self.check_repo_free(&repo)?;
match self
.conn
- .execute("INSERT INTO projects (slug, name, repo) VALUES (?1, ?2, ?3)", params![slug, name, repo])
+ .execute("INSERT INTO project_repos (repo, project_id) VALUES (?1, ?2)", params![repo, project.id])
{
- // Someone created the same project between our check and the insert.
Err(rusqlite::Error::SqliteFailure(e, _)) if e.code == rusqlite::ErrorCode::ConstraintViolation => {
- return Err(Error::Invalid(format!("project {slug} or its repo already exists")));
+ return Err(Error::Invalid(format!("repo {repo} is already linked to another project")));
}
other => other?,
};
- self.find_project(&slug)
+ self.find_project(&project.slug)
+ }
+
+ pub fn unlink_repo(&self, slug: &str, repo: &str) -> Result<Project> {
+ let project = self.find_project(slug)?;
+ let repo = repo_from_url(repo).unwrap_or_else(|| repo.trim().to_ascii_lowercase());
+ let removed = self
+ .conn
+ .execute("DELETE FROM project_repos WHERE repo = ?1 AND project_id = ?2", params![repo, project.id])?;
+ if removed == 0 {
+ return Err(Error::NotFound(format!("repo {repo} is not linked to project {}", project.slug)));
+ }
+ self.find_project(&project.slug)
+ }
+
+ fn check_repo_free(&self, repo: &str) -> Result<()> {
+ match self.project_by_repo(repo)? {
+ Some(other) => Err(Error::Invalid(format!("repo {repo} is already linked to project {}", other.slug))),
+ None => Ok(()),
+ }
}
pub fn set_project_color(&self, slug: &str, color: &str) -> Result<Project> {
@@ -635,6 +690,10 @@ pub fn clean_tags(input: &str) -> Vec<String> {
tags
}
+fn clean_repo(repo: &str) -> Result<String> {
+ repo_from_url(repo).ok_or_else(|| Error::Invalid(format!("repo {:?} should look like owner/repo", repo.trim())))
+}
+
fn clean_title(title: &str) -> Result<String> {
let title = title.split_whitespace().collect::<Vec<_>>().join(" ");
if title.is_empty() {
@@ -710,7 +769,7 @@ mod tests {
fn projects() {
let (_dir, s) = store();
let p = s.create_project("API", "API server", Some("https://github.com/Me/Api.git")).unwrap();
- assert_eq!((p.slug.as_str(), p.repo.as_deref()), ("api", Some("me/api")));
+ assert_eq!((p.slug.as_str(), p.repos.as_slice()), ("api", ["me/api".to_string()].as_slice()));
assert_eq!(s.find_project("me/api").unwrap().id, p.id);
assert_eq!(s.project_by_repo("[email protected]:me/api.git").unwrap().unwrap().id, p.id);
assert!(s.create_project("api", "", None).unwrap_err().to_string().contains("already exists"));
@@ -723,6 +782,49 @@ mod tests {
assert!(s.find_project("nope").unwrap_err().to_string().contains("api, web"));
}
+ #[test]
+ fn many_repos_per_project() {
+ let (_dir, s) = store();
+ let api = s.create_project("api", "", Some("me/api")).unwrap();
+ s.create_project("web", "", None).unwrap();
+ assert_eq!(s.link_repo("api", "https://github.com/Me/API-docs.git").unwrap().repos, ["me/api", "me/api-docs"]);
+ assert_eq!(s.find_project("me/api-docs").unwrap().id, api.id);
+ assert_eq!(s.link_repo("api", "me/api").unwrap().repos.len(), 2, "linking twice changes nothing");
+ assert!(s.link_repo("web", "me/api-docs").unwrap_err().to_string().contains("already linked to project api"));
+ assert!(s.link_repo("api", "not a repo").is_err());
+ assert_eq!(s.unlink_repo("api", "me/api").unwrap().repos, ["me/api-docs"]);
+ assert!(s.project_by_repo("me/api").unwrap().is_none());
+ assert!(s.unlink_repo("api", "me/api").is_err());
+ // A deleted project frees its repos.
+ s.delete_project("api").unwrap();
+ assert_eq!(s.link_repo("web", "me/api-docs").unwrap().repos, ["me/api-docs"]);
+ }
+
+ #[test]
+ fn migration_moves_repos_to_their_own_table() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("kanzo.db");
+ {
+ // A board at schema version 3, from before projects could have several repos.
+ let c = Connection::open(&path).unwrap();
+ c.execute_batch("CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)").unwrap();
+ for sql in &MIGRATIONS[..3] {
+ c.execute_batch(sql).unwrap();
+ }
+ c.execute_batch(
+ "INSERT INTO meta VALUES ('schema_version', '3');
+ INSERT INTO projects (slug, name, repo) VALUES ('api', 'api', 'me/api'), ('web', 'web', NULL);",
+ )
+ .unwrap();
+ }
+ let statuses = ["todo", "doing", "review", "done"].map(String::from).to_vec();
+ let s = Store::open(&path, statuses, None).unwrap();
+ s.migrate().unwrap();
+ assert_eq!(s.find_project("api").unwrap().repos, ["me/api"]);
+ assert!(s.find_project("web").unwrap().repos.is_empty());
+ assert_eq!(s.find_project("me/api").unwrap().slug, "api");
+ }
+
#[test]
fn task_lifecycle() {
let (_dir, s) = store();
diff --git a/src/web.rs b/src/web.rs
index c25d8dd..6b57a37 100644
--- a/src/web.rs
+++ b/src/web.rs
@@ -123,6 +123,7 @@ fn router(home: Home, guard: Guard, shutdown: CancellationToken) -> Router {
.route("/api/board", get(board))
.route("/api/projects", post(create_project))
.route("/api/projects/{slug}", patch(update_project).delete(delete_project))
+ .route("/api/projects/{slug}/repos", post(link_repo).delete(unlink_repo))
.route("/api/tasks", post(create_task))
.route("/api/tasks/{id}", get(get_task).patch(update_task).delete(delete_task))
.route("/api/tasks/{id}/move", post(move_task))
@@ -307,6 +308,19 @@ async fn update_project(State(home): Shared, Path(slug): Path<String>, Json(p):
with_store(home, move |_, s| s.set_project_color(&slug, &p.color)).await
}
+#[derive(Deserialize)]
+struct RepoLink {
+ repo: String,
+}
+
+async fn link_repo(State(home): Shared, Path(slug): Path<String>, Json(r): Json<RepoLink>) -> Response {
+ with_store(home, move |_, s| s.link_repo(&slug, &r.repo)).await
+}
+
+async fn unlink_repo(State(home): Shared, Path(slug): Path<String>, Json(r): Json<RepoLink>) -> Response {
+ with_store(home, move |_, s| s.unlink_repo(&slug, &r.repo)).await
+}
+
async fn delete_project(State(home): Shared, Path(slug): Path<String>) -> Response {
with_store(home, move |_, s| s.delete_project(&slug)).await
}