mirror of
https://github.com/runbear-io/beardrive.git
synced 2026-08-25 08:08:08 +02:00
* feat(templates): start a project from a structure, not an empty folder A new project was an empty folder with a .bdriveignore in it, so every agent session invented its own layout and the folder rotted into a pile. Both surfaces now offer the same three starting points — from a template, from scratch, from an existing folder (which is just a non-empty folder, and is never restructured). internal/templates holds the shipped set as literal go:embed'ed files: `docs` (docs/, decisions/) and `para` (projects/, areas/, resources/, archives/). cmd/bdrive is one binary for the CLI and the hub, so both read the identical set — no gallery, no drift. The AGENTS.md in each is the deliverable: where a new note goes, when something is archived, what a good filename looks like. Every directory holds a real file, because BearDrive syncs paths and an empty directory would never reach a teammate. The hub seeds at creation through the existing Upload+Commit path, journaled under its own device, and records the choice on the project record — so a user who picked PARA in a browser sees PARA in the browser, and a later init cannot seed a second copy. `bdrive init --template <name>` goes through the same endpoint, with a local-seed fallback for a hub too old to know the field, and seeds in place when re-run in an already-initialized folder (the agent's post-init path). Seeding never overwrites an existing path, which is what makes a double-seed a no-op rather than a divergence. Refusals cost nothing: an unknown name and --template with --only are both rejected before any network call or write. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * test(cli): joining a project that already has a template is refused by name The one acceptance case with no test behind it: connecting to an existing project with --template must say what the project was actually created from, and must not write the other skeleton on the way out. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(templates): name the docs template in plain English, not an acronym "Plain docs + ADRs" was the recommended, first, preselected-adjacent option in a picker that non-engineers see — and it's the label people accept without reading further, so half of it not parsing is the worst place for jargon. The title also disagreed with its own blurb: "ADRs" over "docs/, decisions/", two words for the same folder one line apart. Now "Docs + decision records", which says the same thing to everyone and matches the folder names. The term itself moves into decisions/0001-record-decisions.md, where the reader is already inside the structure and the file can teach it in passing. One line in the registry drives both the web dialog and the CLI menu; the rest is prose echoing it. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * feat(templates): add the LLM wiki template The third starting point from the issue title, unblocked: the spec parked it because shipping an approximation under someone's name needed a source, and there is now one — Karpathy's LLM Wiki gist. Worth noting the issue's own one-line description of it ("few large, append-heavy topic pages") does not match the source, which is the opposite: many interlinked pages, where a single ingest touches 10-15 of them. The pattern is three layers and three operations, not a folder shape. sources/ is yours and immutable; wiki/ is the agent's and it owns every page; AGENTS.md is the schema layer — which is exactly the file this template system already treats as the deliverable, so the fit is direct. index.md and log.md ship as the two navigation files the pattern turns on. Three of the things the gist tells you to go set up, BearDrive already is: version history and collaboration (per-file history, bdrive log), an Obsidian- style reader for [[wikilinks]] (the hub viewer), and a surface for the lint pass (the dashboard is literally reads x staleness). Two rules in the AGENTS.md are load-bearing and deliberate. A page write that has not updated the index is an incomplete write — a stale index is worse than a missing page, because it is read first and believed. And with no sources yet, build nothing: the structure grows out of the material rather than ahead of it. Shipped second, not first: docs stays the recommendation because a default is the option chosen by people not reading closely, and this pattern degrades badly when half-followed. Promoting it later is one line in the registry. The shipped-template test now checks the "what happens when something stops being true" question through a set of alternatives — PARA archives, a wiki supersedes and revises — since the vocabulary honestly differs by structure. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * feat(web): "I already have a folder" as a starting point The third way to start from the spec — adopt what you already have — had no presence in the browser. Templates and "empty" were the only visible answers, so someone with a folder of notes either hesitated or picked a template and got four directories merged into their material. The constraint that shapes it: the browser cannot reach your disk, so this cannot change what is created. It creates the same empty project "Empty project" does; what it changes is the next screen. Create therefore stays enabled — disabling it would leave the dialog a dead end AND produce no project id, which is the one thing the paste prompt actually needs. Landing on the project home with the intent, three things differ: the guide says "in the folder you already have", a note states plainly that connecting never moves, renames or overwrites anything, and the paste prompt tells the agent a folder already exists. That last one is the part that isn't cosmetic — without it an agent reads an empty project and proposes creating shared/, the one recommendation that is wrong here. It still asks which folder: that is the runbook's hard gate and nothing here weakens it. The intent rides in the URL (?connect=existing) rather than onto the project record, the same way ?v= pins a file version. It belongs to whoever is connecting right now — a teammate who connects next week has their own answer and would be told the wrong thing by a persisted flag. Five rows made the dialog tall enough to push Create off a short viewport, so .modal scrolls internally. A hairline divider between the seeding and non-seeding rows was tried and removed: --border is 7% white, which at 1px in a gap renders as literally nothing. The gap is the cue that reads. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * feat(web): with no projects, open the create dialog and give the page a way in A signed-in account with no projects landed on a page whose only path forward was pasting a prompt into a coding agent. Now the create dialog opens itself — with nothing to browse there is nothing else on that page to do — and the page behind it leads with "Start a project" and a button, so closing the dialog is not a dead end. The dialog moves up to HubApp because three things ask for it now: the sidebar's +, the empty state's button, and the auto-open. ProjectNav keeps only an onNew callback; one owner beats three copies of the create handler. Two guards on the auto-open. It fires once per mount, keyed off a ref rather than the empty state, or closing it would immediately reopen it. And it never fires on a read-only hub, which refuses creation server-side with a 403 — opening a dialog that cannot succeed is worse than the page it covers. The agent paste-prompt stays, demoted to "Or let your agent do it": it is still the right path for someone who wants the folder connected in the same breath, and it is the only path on a hub where this account cannot create. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
362 lines
10 KiB
Go
362 lines
10 KiB
Go
package webapp
|
|
|
|
import (
|
|
"fmt"
|
|
"regexp"
|
|
"sort"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
"unicode/utf8"
|
|
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
// Project is one synced project hosted by this server. Its storage lives
|
|
// under <root>/<id>/ in the object store; the id is permanent, the name is a
|
|
// renameable label.
|
|
type Project struct {
|
|
ID string `json:"id"`
|
|
Name string `json:"name"`
|
|
Org string `json:"org,omitempty"` // owning organization
|
|
Created time.Time `json:"created"`
|
|
Description string `json:"description,omitempty"` // optional one-line subtitle
|
|
Icon string `json:"icon,omitempty"` // optional lucide icon name
|
|
// Creator is the account that first created the project; it gets an
|
|
// explicit admin grant at creation. Empty on projects that predate
|
|
// per-project permissions — those are governed by org owners.
|
|
Creator string `json:"creator,omitempty"`
|
|
// Template is the starting structure the project was created from
|
|
// (internal/templates), empty for an empty project. Set once, at
|
|
// creation, by whoever seeded it — it is what stops a second surface
|
|
// seeding a second copy.
|
|
Template string `json:"template,omitempty"`
|
|
// Default is the level every org member gets without an explicit grant.
|
|
// Empty means write: the historical behavior, so no row needs migrating.
|
|
Default string `json:"default,omitempty"`
|
|
// Perms are the explicit grants, lowercase email → level.
|
|
Perms map[string]string `json:"perms,omitempty"`
|
|
}
|
|
|
|
// level is the project's effective default level for org members.
|
|
func (p Project) level() string {
|
|
if p.Default == "" {
|
|
return PermWrite
|
|
}
|
|
return p.Default
|
|
}
|
|
|
|
// projectIDRe is the authority on what a project id may look like: a UUID
|
|
// (what new projects get) or the legacy `p-xxxxxxxx` form hubs minted before
|
|
// — ids are permanent, so the old shape stays valid forever. Client-side
|
|
// parsers (remote/http.go, the share command) only check the loose shape and
|
|
// let the hub decide.
|
|
var projectIDRe = regexp.MustCompile(`^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|p-[0-9a-f]{8})$`)
|
|
|
|
// iconRe validates the *shape* of an icon name only. The list of icons a
|
|
// project may pick from lives in the frontend (shell.tsx's PROJECT_ICONS) —
|
|
// the server stores whatever kebab-case name it's given and the UI falls back
|
|
// to a placeholder for anything it doesn't know, so adding an icon never
|
|
// needs a server change.
|
|
var iconRe = regexp.MustCompile(`^[a-z0-9-]{1,32}$`)
|
|
|
|
const (
|
|
maxNameLen = 120
|
|
maxDescLen = 280
|
|
)
|
|
|
|
// ProjectDB is the server's project registry: an in-memory index over a
|
|
// MetaStore ProjectRepo. Reads are served from memory; every change is
|
|
// persisted as one record through the repo (file or SQL).
|
|
type ProjectDB struct {
|
|
repo ProjectRepo
|
|
|
|
mu sync.Mutex
|
|
byID map[string]Project
|
|
}
|
|
|
|
// NewProjectDB builds the registry over a repo, loading its current contents.
|
|
func NewProjectDB(repo ProjectRepo) (*ProjectDB, error) {
|
|
db := &ProjectDB{repo: repo, byID: make(map[string]Project)}
|
|
list, err := repo.Load()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for _, p := range list {
|
|
db.byID[p.ID] = p
|
|
}
|
|
return db, nil
|
|
}
|
|
|
|
// OpenProjectDB loads the file-backed registry at path (a missing file is an
|
|
// empty registry) — the zero-dependency default.
|
|
func OpenProjectDB(path string) (*ProjectDB, error) {
|
|
return NewProjectDB(newFileProjectRepo(path))
|
|
}
|
|
|
|
// list returns projects sorted by name. Callers hold mu.
|
|
func (db *ProjectDB) list() []Project {
|
|
out := make([]Project, 0, len(db.byID))
|
|
for _, p := range db.byID {
|
|
out = append(out, p)
|
|
}
|
|
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
|
|
return out
|
|
}
|
|
|
|
func (db *ProjectDB) List() []Project {
|
|
db.mu.Lock()
|
|
defer db.mu.Unlock()
|
|
return db.list()
|
|
}
|
|
|
|
func (db *ProjectDB) Get(id string) (Project, bool) {
|
|
db.mu.Lock()
|
|
defer db.mu.Unlock()
|
|
p, ok := db.byID[id]
|
|
return p, ok
|
|
}
|
|
|
|
// GetOrCreate returns the project with the given name in the org, creating
|
|
// it (with a fresh id) if none exists. Names are matched exactly, scoped to
|
|
// the org: two organizations can each have a "wiki".
|
|
func (db *ProjectDB) GetOrCreate(name, org string) (Project, bool, error) {
|
|
name = trimName(name)
|
|
if name == "" {
|
|
return Project{}, false, fmt.Errorf("project name must not be empty")
|
|
}
|
|
db.mu.Lock()
|
|
defer db.mu.Unlock()
|
|
for _, p := range db.byID {
|
|
if p.Name == name && p.Org == org {
|
|
return p, false, nil
|
|
}
|
|
}
|
|
p := Project{ID: uuid.NewString(), Name: name, Org: org, Created: time.Now().UTC()}
|
|
db.byID[p.ID] = p
|
|
if err := db.repo.Put(p); err != nil {
|
|
delete(db.byID, p.ID)
|
|
return Project{}, false, err
|
|
}
|
|
return p, true, nil
|
|
}
|
|
|
|
// Update changes a project's editable metadata. Each field is a pointer so
|
|
// that "absent" (nil, leave alone) is distinguishable from "present and
|
|
// empty" (clear it) — the whole point of a partial update. One lock, one
|
|
// repo write, whatever the caller changed.
|
|
func (db *ProjectDB) Update(id string, name, description, icon *string) error {
|
|
var newName, newDesc, newIcon string
|
|
if name != nil {
|
|
newName = trimText(*name, maxNameLen+1)
|
|
if newName == "" {
|
|
return fmt.Errorf("project name must not be empty")
|
|
}
|
|
if utf8.RuneCountInString(newName) > maxNameLen {
|
|
return fmt.Errorf("project name must be at most %d characters", maxNameLen)
|
|
}
|
|
}
|
|
if description != nil {
|
|
newDesc = trimText(*description, maxDescLen+1)
|
|
if utf8.RuneCountInString(newDesc) > maxDescLen {
|
|
return fmt.Errorf("project description must be at most %d characters", maxDescLen)
|
|
}
|
|
}
|
|
if icon != nil {
|
|
newIcon = strings.TrimSpace(*icon)
|
|
if newIcon != "" && !iconRe.MatchString(newIcon) {
|
|
return fmt.Errorf("invalid icon name %q", newIcon)
|
|
}
|
|
}
|
|
|
|
db.mu.Lock()
|
|
defer db.mu.Unlock()
|
|
p, ok := db.byID[id]
|
|
if !ok {
|
|
return fmt.Errorf("no such project %q", id)
|
|
}
|
|
if name != nil {
|
|
for _, other := range db.byID {
|
|
if other.ID != id && other.Name == newName && other.Org == p.Org {
|
|
return fmt.Errorf("a project named %q already exists in this organization", newName)
|
|
}
|
|
}
|
|
p.Name = newName
|
|
}
|
|
if description != nil {
|
|
p.Description = newDesc
|
|
}
|
|
if icon != nil {
|
|
p.Icon = newIcon
|
|
}
|
|
db.byID[id] = p
|
|
return db.repo.Put(p)
|
|
}
|
|
|
|
// Rename changes a project's display name (its id and storage are permanent).
|
|
func (db *ProjectDB) Rename(id, name string) error {
|
|
return db.Update(id, &name, nil, nil)
|
|
}
|
|
|
|
// Delete removes a project from the registry. Its storage prefix (blobs,
|
|
// journals) is left in the object store — the id is retired, not scrubbed —
|
|
// so the caller decides whether to reclaim that space out of band.
|
|
func (db *ProjectDB) Delete(id string) error {
|
|
db.mu.Lock()
|
|
defer db.mu.Unlock()
|
|
if _, ok := db.byID[id]; !ok {
|
|
return fmt.Errorf("no such project %q", id)
|
|
}
|
|
delete(db.byID, id)
|
|
return db.repo.Delete(id)
|
|
}
|
|
|
|
// SetCreator records who created a project (and is its first admin).
|
|
func (db *ProjectDB) SetCreator(id, email string) error {
|
|
db.mu.Lock()
|
|
defer db.mu.Unlock()
|
|
p, ok := db.byID[id]
|
|
if !ok {
|
|
return fmt.Errorf("no such project %q", id)
|
|
}
|
|
p.Creator = normEmail(email)
|
|
db.byID[id] = p
|
|
return db.repo.Put(p)
|
|
}
|
|
|
|
// SetTemplate records the starting structure a project was seeded from.
|
|
func (db *ProjectDB) SetTemplate(id, name string) error {
|
|
db.mu.Lock()
|
|
defer db.mu.Unlock()
|
|
p, ok := db.byID[id]
|
|
if !ok {
|
|
return fmt.Errorf("no such project %q", id)
|
|
}
|
|
p.Template = name
|
|
db.byID[id] = p
|
|
return db.repo.Put(p)
|
|
}
|
|
|
|
// SetDefault sets the level org members get without an explicit grant.
|
|
func (db *ProjectDB) SetDefault(id, level string) error {
|
|
if !validLevel(level) || level == PermAdmin {
|
|
return fmt.Errorf("invalid default level %q", level)
|
|
}
|
|
db.mu.Lock()
|
|
defer db.mu.Unlock()
|
|
p, ok := db.byID[id]
|
|
if !ok {
|
|
return fmt.Errorf("no such project %q", id)
|
|
}
|
|
p.Default = level
|
|
db.byID[id] = p
|
|
return db.repo.Put(p)
|
|
}
|
|
|
|
// SetPerm grants one account an explicit level on the project. Demoting the
|
|
// last explicit admin is refused, the same shape as OrgDB's last-owner rule:
|
|
// a project must keep someone who can administer it (org owners aside, who
|
|
// are implicitly admin and never appear in this list).
|
|
func (db *ProjectDB) SetPerm(id, email, level string) error {
|
|
if !validLevel(level) {
|
|
return fmt.Errorf("invalid level %q", level)
|
|
}
|
|
e := normEmail(email)
|
|
if e == "" {
|
|
return fmt.Errorf("email must not be empty")
|
|
}
|
|
db.mu.Lock()
|
|
defer db.mu.Unlock()
|
|
p, ok := db.byID[id]
|
|
if !ok {
|
|
return fmt.Errorf("no such project %q", id)
|
|
}
|
|
if level != PermAdmin && p.Perms[e] == PermAdmin && adminCount(p) <= 1 {
|
|
return fmt.Errorf("cannot demote the last project admin")
|
|
}
|
|
perms := make(map[string]string, len(p.Perms)+1)
|
|
for k, v := range p.Perms {
|
|
perms[k] = v
|
|
}
|
|
perms[e] = level
|
|
p.Perms = perms
|
|
db.byID[id] = p
|
|
return db.repo.Put(p)
|
|
}
|
|
|
|
// ClearPerm drops an explicit grant, reverting the account to the default.
|
|
func (db *ProjectDB) ClearPerm(id, email string) error {
|
|
e := normEmail(email)
|
|
db.mu.Lock()
|
|
defer db.mu.Unlock()
|
|
p, ok := db.byID[id]
|
|
if !ok {
|
|
return fmt.Errorf("no such project %q", id)
|
|
}
|
|
if _, has := p.Perms[e]; !has {
|
|
return fmt.Errorf("%s has no permission set on this project", email)
|
|
}
|
|
if p.Perms[e] == PermAdmin && adminCount(p) <= 1 {
|
|
return fmt.Errorf("cannot remove the last project admin")
|
|
}
|
|
perms := make(map[string]string, len(p.Perms))
|
|
for k, v := range p.Perms {
|
|
if k != e {
|
|
perms[k] = v
|
|
}
|
|
}
|
|
p.Perms = perms
|
|
db.byID[id] = p
|
|
return db.repo.Put(p)
|
|
}
|
|
|
|
// adminCount counts explicit admin grants on a project.
|
|
func adminCount(p Project) int {
|
|
n := 0
|
|
for _, l := range p.Perms {
|
|
if l == PermAdmin {
|
|
n++
|
|
}
|
|
}
|
|
return n
|
|
}
|
|
|
|
// SetOrg moves a project into an org (used by the startup migration).
|
|
func (db *ProjectDB) SetOrg(id, org string) error {
|
|
db.mu.Lock()
|
|
defer db.mu.Unlock()
|
|
p, ok := db.byID[id]
|
|
if !ok {
|
|
return fmt.Errorf("no such project %q", id)
|
|
}
|
|
p.Org = org
|
|
db.byID[id] = p
|
|
return db.repo.Put(p)
|
|
}
|
|
|
|
// trimName normalizes a name on the *creation* path, where an over-long name
|
|
// is silently truncated rather than rejected (bdrive init must not fail on a
|
|
// long folder name). Update is stricter — see maxNameLen.
|
|
func trimName(s string) string { return trimText(s, 128) }
|
|
|
|
// trimText strips line breaks and outer spaces, then truncates to max runes.
|
|
func trimText(s string, max int) string {
|
|
out := make([]rune, 0, len(s))
|
|
for _, r := range s {
|
|
if r == '\n' || r == '\r' || r == '\t' {
|
|
continue
|
|
}
|
|
out = append(out, r)
|
|
}
|
|
for len(out) > 0 && out[0] == ' ' {
|
|
out = out[1:]
|
|
}
|
|
for len(out) > 0 && out[len(out)-1] == ' ' {
|
|
out = out[:len(out)-1]
|
|
}
|
|
if len(out) > max {
|
|
out = out[:max]
|
|
}
|
|
return string(out)
|
|
}
|