forge
Explore
Log in

Don't you dare go Hollow

One tag per card, a page per person, one schema, one mail

Browse files at this commit

de54fefad0b720acbf1b8cdf24431ae16c102d69Ahmet Kaan GümüşParent: e49a1d2
  • feat
    • one tag per card, a page per person, one schema, one mail
Show full message
✨ feat(izlek): one tag per card, a page per person, one schema, one mail

Four things that turned out to be one commit, because the schema underneath
them stopped being a chain.

The assignment rule mailed the wrong people. "Notify the assignees" was read
as "notify everyone on the card whenever anyone is assigned", so three
assignments were nine mails. An activity line that is *about* somebody now
carries that person's id, and the audience for such a line is that person
alone — read from the stored subject rather than from the display name in
the detail, so a restart resolves the audience the first pass resolved and
two people may share a name.

Tags: a card belongs to exactly one. Every board is born with a `General`
tag that cannot be deleted and cannot be a second default, deleting a tag
moves its cards there, and `task.tag_id` is `NOT NULL` — there is no
tagless state to write a view around. Admins order them on /tags.

Every member has a page at /people/{id}: their photo, their address, what
they hold open, what they finished, what they opened and what they said.
A stranger's id is a 404 rather than a 403, because a workspace does not
confirm who is in it to somebody who is not.

The migration chain is gone. `0001_init.sql` is now the whole declared
schema, and a database is compared against it by fingerprint at boot: if it
does not match, the store keeps a backup and rebuilds it onto the declared
shape before it will serve — `izlek reconcile` is the same code with a flag.
The rebuild carries data across by a hand-written column map rather than by
guessing from a diff, which is how every task ends up on its *own* board's
default tag. It was run against the live database before this landed: 1
workspace, 4 users, 6 tasks, 59 activity rows, a 1 MB attachment and three
photos, all byte-identical afterwards with `foreign_key_check` clean.

And mail waits. A workspace has a quiet window (`mail_batch_minutes`,
default 5, 0 for the old behaviour): an owed mail is born due when the
window closes, and each further event about the same card pushes that
person's pending rows out again. What goes out is one envelope per card per
reader, stating where the card ended up — column, deadline, assignees —
rather than one mail per trigger. Create a card, fix its column, assign it,
set a deadline: four rules, four triggers, one mail. The push is clipped at
four windows from the oldest mail in the batch, so a card somebody edits all
afternoon still goes out. Invites and notices are never folded into a batch;
they carry their own subject and body. A batch the server refuses spends one
attempt for the whole envelope and is retried as one envelope, because the
claim is still the only way to mail a row.

Tests: his workflow is one mail and a wrong column put right is one mail
naming only the right column; the debounce, the ceiling and the zero window
each have their own case; the alteration is carried across by reconcile in
both directions — a database that never had the column gets the default, one
whose admin already chose a number keeps it.

28 changed files +5672 -586

.gitignoremodified+1 -0
@@ -8,3 +8,4 @@ izlek.key
88 /config/izlek.toml
99 CLAUDE.md
1010 /crates/izlek-web/assets
11+*.db.backup-*
crates/izlek-core/migrations/0001_init.sqlmodified+61 -9
@@ -1,18 +1,16 @@
11 -- Izlek's schema, whole, in one file.
22 --
3--- Plain versioned SQL applied at boot: Turso has no migration runner of its
4--- own, and keeping the schema as SQL is what makes the store trait swappable.
3+-- One plain SQL file, applied at boot to an empty database: Turso has no
4+-- migration runner of its own, and keeping the schema as SQL is what makes
5+-- the store trait swappable.
56 -- Timestamps are RFC 3339 text in UTC. Ids are ULIDs as text — sortable by
67 -- creation, and Crockford-uppercase already, which is what lets a task key
78 -- borrow its tail.
89 --
9--- This file is the whole schema, not the first link of a chain. Nothing has
10--- been released, so a change to a table is made here, in the table, and the
11--- database it describes is recreated — twenty migrations were collapsed into
12--- this file once for that reason, and a twenty-first would start the same rot
13--- over. The reasoning the old migrations carried is kept, on the tables it
14--- explains. The day Izlek runs somewhere with data worth keeping, the next
15--- change becomes 0002 and this note goes away.
10+-- This file is the whole schema, and it is edited in place: a change to a
11+-- table is made here, in the table, never appended as an ALTER. An existing
12+-- database is brought up to it by `izlek reconcile`, not by the store, so a
13+-- change to a table lands in two places — here, and in that tool's copy map.
1614
1715 CREATE TABLE workspace (
1816 id TEXT PRIMARY KEY,
@@ -25,6 +23,12 @@ CREATE TABLE workspace (
2523 photo_limit_bytes INTEGER NOT NULL DEFAULT 2097152,
2624 -- JSON array of allowed extensions. An empty array means every type.
2725 allowed_file_types TEXT NOT NULL DEFAULT '[]',
26+ -- How long a notification waits for the rest of its workflow. One normal
27+ -- sequence — open a card, fix the column, assign it, set a deadline — is
28+ -- four writes and was four mails; held for a few quiet minutes it is one
29+ -- mail saying where the card ended up. Zero sends each one the moment it
30+ -- is owed, which is what this did before the column existed.
31+ mail_batch_minutes INTEGER NOT NULL DEFAULT 5,
2832 -- The single sender every mail in the workspace goes through, written by
2933 -- the admin in Settings rather than by whoever has a shell on the box: a
3034 -- three-person team has those be different people, and the second one is
@@ -51,6 +55,19 @@ CREATE TABLE workspace (
5155 smtp_test_at TEXT,
5256 smtp_test_ms INTEGER,
5357 smtp_test_error TEXT,
58+ -- Whether the mail server let us in, which is a different fact from
59+ -- whether a mail was delivered. `smtp_test_*` above records a real
60+ -- message going out to a real inbox; these record a handshake —
61+ -- connect, negotiate TLS, say hello, authenticate, hang up. It proves
62+ -- the host, the port, the encryption and the credentials, and proves
63+ -- nothing about whether the from-address is one this account may send
64+ -- as — a server that accepts the login can still refuse the envelope.
65+ -- Kept apart so neither can be read as the other. Cleared whenever the
66+ -- sender is edited, for the same reason the test result is: it was
67+ -- about settings that no longer exist.
68+ smtp_check_at TEXT,
69+ smtp_check_ms INTEGER,
70+ smtp_check_error TEXT,
5471 -- The address mail links point at, when the one the process was
5572 -- configured with is not the one people reach. A box behind a proxy
5673 -- answers on localhost and is known by a public name, and only an admin
@@ -147,6 +164,29 @@ CREATE TABLE board_column (
147164 is_done INTEGER NOT NULL DEFAULT 0
148165 );
149166
167+-- A tag is the project a task belongs to. A task wears at most one, so the
168+-- link is a column on `task` rather than a join table: two projects on one
169+-- task is a mistake the schema can refuse outright.
170+--
171+-- A tag belongs to a board, as a mail rule does. Its order is the admin's —
172+-- set by hand, up and down — so it is stored rather than derived from
173+-- anything the board already knows.
174+--
175+-- `is_default` marks the board's one fallback: every task must wear a tag,
176+-- so the board has one tag that catches whatever loses its own. That there
177+-- is exactly one is the partial index's job, not the store's.
178+CREATE TABLE tag (
179+ id TEXT PRIMARY KEY,
180+ board_id TEXT NOT NULL REFERENCES board(id),
181+ name TEXT NOT NULL,
182+ position INTEGER NOT NULL,
183+ is_default INTEGER NOT NULL DEFAULT 0,
184+ created_at TEXT NOT NULL
185+);
186+CREATE UNIQUE INDEX tag_one_default ON tag(board_id) WHERE is_default = 1;
187+CREATE UNIQUE INDEX tag_name_unique ON tag(board_id, name);
188+CREATE INDEX tag_by_board ON tag(board_id, position);
189+
150190 -- A task, and a subtask, which is the same thing with a parent.
151191 --
152192 -- `parent_id` is the whole of the subtask feature in this schema: a subtask
@@ -172,6 +212,10 @@ CREATE TABLE task (
172212 title TEXT NOT NULL,
173213 description TEXT NOT NULL DEFAULT '',
174214 column_id TEXT NOT NULL REFERENCES board_column(id),
215+ -- The project the task belongs to — NOT NULL on purpose, which a
216+ -- declared schema can say where an ALTER could not: every task wears a
217+ -- tag, and the board's default one catches whatever loses its own.
218+ tag_id TEXT NOT NULL REFERENCES tag(id),
175219 deadline TEXT,
176220 position REAL NOT NULL DEFAULT 0,
177221 created_by TEXT NOT NULL REFERENCES user(id),
@@ -294,6 +338,14 @@ CREATE TABLE activity (
294338 id TEXT PRIMARY KEY,
295339 task_id TEXT REFERENCES task(id),
296340 actor_id TEXT REFERENCES user(id),
341+ -- Who an activity line is about, as opposed to the actor who did it:
342+ -- an Assigned line is about the person just assigned, an Unassigned one
343+ -- about the person just removed. A mail rule aimed at the assignees
344+ -- re-derives its one recipient from this id, on a retry as well as on
345+ -- the first run — the detail column carries only a display name, and
346+ -- two people can share a name. NULL for lines that are about nobody: a
347+ -- comment, a move, a delete.
348+ subject_id TEXT REFERENCES user(id),
297349 kind TEXT NOT NULL,
298350 detail TEXT NOT NULL DEFAULT '',
299351 created_at TEXT NOT NULL
crates/izlek-core/src/board.rsmodified+24 -4
@@ -42,6 +42,9 @@ pub struct TaskRow {
4242 /// is still read with the rest, because a key it owns can appear on
4343 /// somebody else's card as a blocker.
4444 pub parent_id: Option<String>,
45+ /// The tag — the project — the task wears, if any. The name rides along
46+ /// so a card can show a chip without a second sweep.
47+ pub tag: Option<TagChip>,
4548 }
4649
4750 /// One card crossing from one column into another, as it was written.
@@ -111,6 +114,14 @@ impl Person {
111114 }
112115 }
113116
117+/// A tag's id and name, as a card and the detail carry them: enough to show
118+/// a chip and to filter the board on, and nothing more.
119+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
120+pub struct TagChip {
121+ pub id: String,
122+ pub name: String,
123+}
124+
114125 /// A card, assembled. Dependencies carry the *keys* of the tasks on the other
115126 /// end, because that is what the card shows and it saves the UI a second lookup.
116127 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
@@ -132,6 +143,8 @@ pub struct TaskCard {
132143 /// Both are zero for a card with none, which is what hides the chip.
133144 pub subtask_total: u32,
134145 pub subtask_done: u32,
146+ /// The tag the card wears — its project — when it has one.
147+ pub tag: Option<TagChip>,
135148 }
136149
137150 impl TaskCard {
@@ -143,8 +156,7 @@ impl TaskCard {
143156 /// also the only place the count appears when a move is refused, which is
144157 /// why the refusal itself does not carry one.
145158 pub fn subtask_label(&self) -> Option<String> {
146- (self.subtask_total > 0)
147- .then(|| format!("{}/{}", self.subtask_done, self.subtask_total))
159+ (self.subtask_total > 0).then(|| format!("{}/{}", self.subtask_done, self.subtask_total))
148160 }
149161
150162 /// Whether finishing this card is currently refused.
@@ -190,11 +202,18 @@ impl TaskCard {
190202 /// `None` when there's nothing to show (no deadline, not done).
191203 pub fn deadline_parts(&self, today: Date) -> Option<DeadlineParts> {
192204 if let Some(done) = self.done_at {
193- return Some(DeadlineParts { date: day_label(done.date()), state: DeadlineState::Done });
205+ return Some(DeadlineParts {
206+ date: day_label(done.date()),
207+ state: DeadlineState::Done,
208+ });
194209 }
195210 self.deadline.map(|day| DeadlineParts {
196211 date: day_label(day),
197- state: if day < today { DeadlineState::Overdue } else { DeadlineState::OnTime },
212+ state: if day < today {
213+ DeadlineState::Overdue
214+ } else {
215+ DeadlineState::OnTime
216+ },
198217 })
199218 }
200219 }
@@ -370,6 +389,7 @@ pub fn assemble(
370389 done_at: task.done_at,
371390 position: task.position,
372391 column_id: task.column_id,
392+ tag: task.tag,
373393 };
374394 cards.entry(card.column_id.clone()).or_default().push(card);
375395 }
crates/izlek-core/src/detail.rsmodified+14 -11
@@ -8,7 +8,7 @@
88 use serde::{Deserialize, Serialize};
99 use time::{Date, OffsetDateTime, UtcOffset};
1010
11-use crate::board::{Column, DeadlineParts, DeadlineState, Person, day_label};
11+use crate::board::{Column, DeadlineParts, DeadlineState, Person, TagChip, day_label};
1212
1313 /// The stored task, plus the two ids the reader needs to know it is allowed to
1414 /// see it. The description lives here rather than on
@@ -420,14 +420,8 @@ mod zone_tests {
420420 fn a_stamp_shifts_with_the_stored_offset() {
421421 let at = time::macros::datetime!(2026-08-19 11:04 UTC);
422422 assert_eq!(moment_label(at), "Aug 19 11:04");
423- assert_eq!(
424- moment_label_in(at, parse_zone("UTC+03:00")),
425- "Aug 19 14:04"
426- );
427- assert_eq!(
428- moment_label_in(at, parse_zone("UTC-05:00")),
429- "Aug 19 06:04"
430- );
423+ assert_eq!(moment_label_in(at, parse_zone("UTC+03:00")), "Aug 19 14:04");
424+ assert_eq!(moment_label_in(at, parse_zone("UTC-05:00")), "Aug 19 06:04");
431425 }
432426
433427 #[test]
@@ -449,6 +443,8 @@ pub struct TaskDetail {
449443 /// Every column on the board, so the status control has its options
450444 /// without a second call.
451445 pub columns: Vec<Column>,
446+ /// The tag the task wears — its project — when it wears one.
447+ pub tag: Option<TagChip>,
452448 pub deadline: Option<Date>,
453449 pub done_at: Option<OffsetDateTime>,
454450 pub assignees: Vec<Person>,
@@ -505,7 +501,11 @@ impl TaskDetail {
505501 pub fn deadline_parts(&self, today: Date) -> Option<DeadlineParts> {
506502 self.deadline.map(|day| DeadlineParts {
507503 date: day_label(day),
508- state: if !self.is_done() && day < today { DeadlineState::Overdue } else { DeadlineState::OnTime },
504+ state: if !self.is_done() && day < today {
505+ DeadlineState::Overdue
506+ } else {
507+ DeadlineState::OnTime
508+ },
509509 })
510510 }
511511
@@ -538,7 +538,9 @@ pub use reads::{DetailReads, load};
538538 mod reads {
539539 use async_trait::async_trait;
540540
541- use super::{ActivityEntry, Comment, DependencyEdge, FileLine, SubtaskLine, TaskDetail, TaskFacts};
541+ use super::{
542+ ActivityEntry, Comment, DependencyEdge, FileLine, SubtaskLine, TaskDetail, TaskFacts,
543+ };
542544 use crate::board::{Column, Person};
543545 use crate::store::Result;
544546
@@ -642,6 +644,7 @@ mod reads {
642644 description: facts.description,
643645 column,
644646 columns,
647+ tag: task.tag,
645648 deadline: task.deadline,
646649 done_at: task.done_at,
647650 assignees,
crates/izlek-core/src/live.rsmodified+4 -0
@@ -28,6 +28,9 @@ pub enum Topic {
2828 Queue,
2929 /// Mail rules and the decisions they made.
3030 Rules,
31+ /// The board's tags — the projects tasks wear. Every member sees them on
32+ /// the board, so every member may hear.
33+ Tags,
3134 /// Workspace settings, sender, limits, public URL.
3235 Settings,
3336 /// The activity and event log.
@@ -44,6 +47,7 @@ impl Topic {
4447 Topic::Members => "members",
4548 Topic::Queue => "queue",
4649 Topic::Rules => "rules",
50+ Topic::Tags => "tags",
4751 Topic::Settings => "settings",
4852 Topic::Activity => "activity",
4953 }
crates/izlek-core/src/mail.rsmodified+226 -33
@@ -123,6 +123,11 @@ pub const HOLD: Duration = Duration::minutes(1);
123123 /// that is thinking about it, short enough that a crash is not a lost day.
124124 pub const LEASE: Duration = Duration::minutes(5);
125125
126+/// How far past its first trigger a batch can be pushed. A card somebody is
127+/// working on all afternoon would otherwise never settle, and its mail would
128+/// never go — so the debounce yields after four windows and sends what it has.
129+pub const MAX_HOLD_WINDOWS: i32 = 4;
130+
126131 /// The wait before the next attempt, doubling and capped: five minutes, ten,
127132 /// twenty, forty, an hour.
128133 pub fn backoff(attempts: u32) -> Duration {
@@ -144,6 +149,9 @@ pub struct Report {
144149 /// Mails held back because there is no sender to send them through. Owed,
145150 /// not failed: no attempt was spent and none will be until one exists.
146151 pub held: u32,
152+ /// Mails written down and left to wait out the workspace's quiet window,
153+ /// so the rest of the workflow can join them in one envelope.
154+ pub batched: u32,
147155 }
148156
149157 pub struct Engine {
@@ -495,6 +503,12 @@ impl Engine {
495503 /// anything is claimed: an empty audience leaves no ledger row at all, so
496504 /// a rule that only ever resolves to the actor is silent rather than being
497505 /// a row the admin has to read as a failure.
506+ ///
507+ /// A line that is about one person narrows the audience to that person:
508+ /// an Assigned rule is for the one just assigned, not for everybody
509+ /// already on the card. The subject is read from the stored row rather
510+ /// than from the name in the detail, so the audience a restart resolves
511+ /// is the audience the first pass resolved — two people can share a name.
498512 async fn owe(
499513 &self,
500514 rule: &MailRule,
@@ -502,10 +516,22 @@ impl Engine {
502516 task_id: &str,
503517 report: &mut Report,
504518 ) -> crate::store::Result<()> {
505- let recipients = match rule.audience {
506- Audience::Assignees => self.store.recipients_for_task(task_id).await?,
507- Audience::Board => self.store.recipients_for_board(&rule.board_id).await?,
508- Audience::Creator => self.store.recipients_for_task_creator(task_id).await?,
519+ let recipients = match (rule.audience, event) {
520+ (
521+ Audience::Assignees,
522+ Event::Happened(ActivityEvent {
523+ subject_id: Some(about),
524+ ..
525+ }),
526+ ) => self
527+ .store
528+ .recipient(about)
529+ .await?
530+ .map(|one| vec![one])
531+ .unwrap_or_default(),
532+ (Audience::Assignees, _) => self.store.recipients_for_task(task_id).await?,
533+ (Audience::Board, _) => self.store.recipients_for_board(&rule.board_id).await?,
534+ (Audience::Creator, _) => self.store.recipients_for_task_creator(task_id).await?,
509535 };
510536 let resolved_nobody = recipients.is_empty();
511537 let now = OffsetDateTime::now_utc();
@@ -531,18 +557,39 @@ impl Engine {
531557 .await?;
532558 return Ok(());
533559 }
560+ // The workspace's quiet window. Zero is what İzlek did before it had
561+ // one: every trigger its own mail, sent as soon as it is owed.
562+ let window = self
563+ .store
564+ .workspace()
565+ .await?
566+ .map(|workspace| i64::from(workspace.mail_batch_minutes))
567+ .unwrap_or(0);
568+ let hold = Duration::minutes(window);
534569 for recipient in audience {
570+ // A held row comes due when the window closes rather than when the
571+ // lease does; with no window it keeps the lease it always had,
572+ // which is what stops the pass that queued it from grabbing it
573+ // back before it has been composed.
574+ let due = if window > 0 { now + hold } else { now + LEASE };
535575 let claimed = self
536576 .store
537- .claim_send(
538- &rule.id,
539- event.id(),
540- task_id,
541- &recipient.email,
542- now,
543- now + LEASE,
544- )
577+ .claim_send(&rule.id, event.id(), task_id, &recipient.email, now, due)
545578 .await?;
579+ if window > 0 {
580+ // Everything this person is already owed about this card waits
581+ // for the new arrival: that is the debounce. The ceiling is
582+ // measured from the oldest mail in the batch, so a card under
583+ // constant edit still goes out.
584+ self.store
585+ .hold_batch(
586+ task_id,
587+ &recipient.email,
588+ now + hold,
589+ hold * MAX_HOLD_WINDOWS,
590+ )
591+ .await?;
592+ }
546593 match claimed {
547594 Some(send) => {
548595 self.store
@@ -555,8 +602,15 @@ impl Engine {
555602 now,
556603 )
557604 .await?;
558- let mail = self.compose(&send, rule, event).await?;
559- self.attempt(&send, mail, report).await?;
605+ // With a window the row is left where it lies: the
606+ // delivery pass picks it up when it comes due, together
607+ // with everything else this person is owed about the card.
608+ if window > 0 {
609+ report.batched += 1;
610+ } else {
611+ let mail = self.compose(&send, rule, event).await?;
612+ self.attempt(&send, mail, report).await?;
613+ }
560614 }
561615 None => {
562616 self.store
@@ -588,11 +642,15 @@ impl Engine {
588642 // pass and the same write wakes the sweep, so two passes reach the
589643 // same row together. Each is handed only what it took, and only a
590644 // `ClaimedSend` can be mailed. See `Store::claim_sends_owed`.
645+ // Rule rows are answered one mail per task per person: several
646+ // triggers about one card, held through the same quiet window, are
647+ // one thing that happened as far as the reader is concerned. Invites
648+ // and notices are never folded in — each carries its own subject and
649+ // body, composed once at mint time, and belongs to nobody's card.
650+ let mut batches: Vec<(String, String, Vec<ClaimedSend>)> = Vec::new();
591651 for send in self.store.claim_sends_owed(now, now + LEASE, limit).await? {
592- // An invite and an admin's notice both owe no rule and no event:
593- // each carries its own subject and body, composed once at mint
594- // time. Without this arm a notice falls through to the rule path,
595- // finds no rule_id, and is skipped every run — queued forever.
652+ // Without this arm a notice falls through to the rule path, finds
653+ // no rule_id, and is skipped every run — queued forever.
596654 if matches!(send.kind, SendKind::Invite | SendKind::Notice) {
597655 let mail = Outgoing {
598656 to: send.recipient.clone(),
@@ -602,47 +660,110 @@ impl Engine {
602660 self.attempt(&send, Some(mail), &mut report).await?;
603661 continue;
604662 }
605- let Some(rule_id) = send.rule_id.as_deref() else {
663+ let Some(task_id) = send.task_id.clone() else {
606664 continue;
607665 };
608- let Some(event_id) = send.event_id.as_deref() else {
666+ let recipient = send.recipient.clone();
667+ match batches
668+ .iter_mut()
669+ .find(|(task, to, _)| task == &task_id && to == &recipient)
670+ {
671+ Some((_, _, group)) => group.push(send),
672+ None => batches.push((task_id, recipient, vec![send])),
673+ }
674+ }
675+
676+ for (_, _, group) in batches {
677+ // The newest event is the one that decides the mail: its rule
678+ // supplies the subject, and its moment is the moment the mail
679+ // speaks about.
680+ let mut newest: Option<(Event, MailRule)> = None;
681+ let mut details = false;
682+ for send in &group {
683+ let (Some(rule_id), Some(event_id)) =
684+ (send.rule_id.as_deref(), send.event_id.as_deref())
685+ else {
686+ continue;
687+ };
688+ let (Some(rule), Some(event)) = (
689+ self.store.mail_rule(rule_id).await?,
690+ self.store.event(event_id).await?,
691+ ) else {
692+ continue;
693+ };
694+ details |= rule.include_task_details;
695+ let newer = newest
696+ .as_ref()
697+ .map(|(known, _)| event.at() > known.at())
698+ .unwrap_or(true);
699+ if newer {
700+ newest = Some((event, rule));
701+ }
702+ }
703+ let Some((event, rule)) = newest else {
609704 continue;
610705 };
611- let Some(rule) = self.store.mail_rule(rule_id).await? else {
706+ let Some(first) = group.first() else {
612707 continue;
613708 };
614- let Some(event) = self.store.event(event_id).await? else {
615- continue;
709+ let mail = if group.len() == 1 {
710+ self.compose(first, &rule, &event).await?
711+ } else {
712+ self.compose_batch(first, &rule, &event, details).await?
616713 };
617- let mail = self.compose(&send, &rule, &event).await?;
618- self.attempt(&send, mail, &mut report).await?;
714+ self.attempt_group(&group, mail, &mut report).await?;
619715 }
620716 Ok(report)
621717 }
622718
623- /// One attempt, and the ledger line it leaves behind.
719+ /// One attempt for one claimed row.
624720 async fn attempt(
625721 &self,
626722 send: &ClaimedSend,
627723 mail: Option<Outgoing>,
628724 report: &mut Report,
725+ ) -> crate::store::Result<()> {
726+ self.attempt_group(std::slice::from_ref(send), mail, report)
727+ .await
728+ }
729+
730+ /// One attempt, and the ledger lines it leaves behind — one per row in
731+ /// the group.
732+ ///
733+ /// A batch is several owed rows answered by a single mail, so the send
734+ /// happens once and every row in it is marked with the same outcome: they
735+ /// were all in that envelope. The claim invariant is unchanged — this
736+ /// takes `ClaimedSend`s, so a row that was merely read still cannot be
737+ /// mailed.
738+ async fn attempt_group(
739+ &self,
740+ sends: &[ClaimedSend],
741+ mail: Option<Outgoing>,
742+ report: &mut Report,
629743 ) -> crate::store::Result<()> {
630744 let Some(mail) = mail else {
631745 return Ok(());
632746 };
747+ let Some(send) = sends.first() else {
748+ return Ok(());
749+ };
633750 let now = OffsetDateTime::now_utc();
634751 match self.mailer.send(&mail).await {
635752 Ok(()) => {
636- self.store.record_send_accepted(&send.id, now).await?;
753+ for one in sends {
754+ self.store.record_send_accepted(&one.id, now).await?;
755+ }
637756 report.sent += 1;
638757 }
639758 Err(problem) if !problem.attempted => {
640759 // No sender. The mail keeps its place in the ledger and its
641760 // attempts, and is looked at again on the next sweep — by then
642761 // an admin may have filled the panel in.
643- self.store
644- .defer_send(&send.id, &problem.message, now + HOLD, now)
645- .await?;
762+ for one in sends {
763+ self.store
764+ .defer_send(&one.id, &problem.message, now + HOLD, now)
765+ .await?;
766+ }
646767 report.held += 1;
647768 }
648769 Err(problem) => {
@@ -651,9 +772,11 @@ impl Engine {
651772 // left looking like it is still coming.
652773 let retry_at =
653774 (problem.retryable && attempts < MAX_ATTEMPTS).then(|| now + backoff(attempts));
654- self.store
655- .record_send_refused(&send.id, &problem.message, retry_at, now)
656- .await?;
775+ for one in sends {
776+ self.store
777+ .record_send_refused(&one.id, &problem.message, retry_at, now)
778+ .await?;
779+ }
657780 if retry_at.is_some() {
658781 report.failed += 1;
659782 } else {
@@ -810,6 +933,76 @@ impl Engine {
810933 body,
811934 }))
812935 }
936+
937+ /// The mail a whole batch answers with: where the task stands NOW.
938+ ///
939+ /// A batch is several triggers about one task for one person, held
940+ /// together through a quiet window. Naming each of them would be a diary,
941+ /// and half its entries are already wrong — a column set by mistake and
942+ /// corrected inside the window happened, but is not the case. So the mail
943+ /// reads the task as it is at send time and says that; the subject comes
944+ /// from the rule behind the newest event, which is the reason the mail is
945+ /// going out at all.
946+ async fn compose_batch(
947+ &self,
948+ send: &MailSend,
949+ newest_rule: &MailRule,
950+ newest_event: &Event,
951+ details: bool,
952+ ) -> crate::store::Result<Option<Outgoing>> {
953+ let Some(task_id) = send.task_id.as_deref() else {
954+ return Ok(None);
955+ };
956+ let Some(facts) = self.store.task(task_id).await? else {
957+ return Ok(None);
958+ };
959+ let columns = self.store.columns_for_board(&facts.board_id).await?;
960+ let column = columns
961+ .iter()
962+ .find(|column| column.id == facts.row.column_id)
963+ .map(|column| column.name.clone())
964+ .unwrap_or_else(|| "somewhere".to_string());
965+ let assignees = self.store.assignees_for_task(task_id).await?;
966+ let assignees = if assignees.is_empty() {
967+ "none".to_string()
968+ } else {
969+ assignees
970+ .iter()
971+ .map(|person| person.display_name.as_str())
972+ .collect::<Vec<_>>()
973+ .join(", ")
974+ };
975+ let deadline = facts
976+ .row
977+ .deadline
978+ .map(|date| date.to_string())
979+ .unwrap_or_else(|| "none".to_string());
980+ let base = self
981+ .store
982+ .workspace()
983+ .await?
984+ .and_then(|workspace| workspace.public_url)
985+ .unwrap_or_else(|| self.fallback_url.clone());
986+ let mut body = format!(
987+ "{key} — {title}\n\nColumn: {column}\nDeadline: {deadline}\nAssignees: {assignees}\n\n{when}\n\n{base}/?task={id}\n",
988+ key = facts.row.task_key,
989+ title = facts.row.title,
990+ when = day_and_time(newest_event.at()),
991+ id = facts.row.id,
992+ );
993+ if details {
994+ body.push_str(&format!(
995+ "\nKey: {key}\nTitle: {title}\n",
996+ key = facts.row.task_key,
997+ title = facts.row.title,
998+ ));
999+ }
1000+ Ok(Some(Outgoing {
1001+ to: send.recipient.clone(),
1002+ subject: newest_rule.subject.clone(),
1003+ body,
1004+ }))
1005+ }
8131006 }
8141007
8151008 /// The `ActivityKind` a trigger fires on. `StatusBecomes`/`Unblocked` fire on
crates/izlek-core/src/store/mod.rsmodified+96 -2
@@ -6,7 +6,7 @@
66
77 use async_trait::async_trait;
88 use serde::{Deserialize, Serialize};
9-use time::OffsetDateTime;
9+use time::{Duration, OffsetDateTime};
1010
1111 use crate::Role;
1212 use crate::board::{BoardReads, Moved, TaskRow, Transition};
@@ -14,9 +14,15 @@ use crate::detail::{ActivityKind, DeletionCost, DetailReads};
1414
1515 #[cfg(feature = "server")]
1616 pub mod secret;
17+#[cfg(feature = "server")]
18+pub mod reconcile;
19+#[cfg(feature = "server")]
20+pub mod schema;
1721 pub mod turso_store;
1822
1923 pub use turso_store::TursoStore;
24+#[cfg(feature = "server")]
25+pub use reconcile::{reconcile, ReconcileOptions};
2026
2127 #[derive(Debug, thiserror::Error)]
2228 pub enum StoreError {
@@ -75,6 +81,9 @@ pub struct Workspace {
7581 pub attachment_limit_bytes: u64,
7682 pub photo_limit_bytes: u64,
7783 pub allowed_file_types: Vec<String>,
84+ /// The quiet window a notification waits out before it is sent, in
85+ /// minutes. `0` sends every trigger the moment it is owed.
86+ pub mail_batch_minutes: u32,
7887 /// The origin mail links point at, when an admin has set one. `None`
7988 /// means the address the process listens on — a box behind a proxy
8089 /// answers on localhost and is reached on a public name, and only an
@@ -206,6 +215,20 @@ pub struct NewUser {
206215 pub invited_by: Option<String>,
207216 }
208217
218+/// The profile page's totals for one person: what is on their plate, what
219+/// finished under them, what they opened, what they said.
220+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
221+pub struct UserStats {
222+ /// Tasks the person is on now, sitting in a column that is not done.
223+ pub assigned_open: u32,
224+ /// Tasks they are on that reached a done column.
225+ pub assigned_done: u32,
226+ /// Tasks they opened, whoever carries them now.
227+ pub created: u32,
228+ /// Comments they wrote.
229+ pub comments: u32,
230+}
231+
209232 /// A first-sign-in link. Only the hash of the token is ever stored; the
210233 /// plaintext is shown once, when the link is created or resent.
211234 #[derive(Debug, Clone, PartialEq)]
@@ -323,6 +346,21 @@ pub struct MailRule {
323346 pub include_task_details: bool,
324347 }
325348
349+/// A tag is the project a task belongs to. A task wears at most one, so the
350+/// link is a column on the task, not a join table. Tags belong to a board,
351+/// like the mail rules do, and their order is the admin's — set by hand, so
352+/// it is stored rather than derived. One tag per board is the default its
353+/// tasks fall back to, and it cannot be deleted — only renamed and
354+/// reordered.
355+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
356+pub struct Tag {
357+ pub id: String,
358+ pub board_id: String,
359+ pub name: String,
360+ pub position: i64,
361+ pub is_default: bool,
362+}
363+
326364 /// Where one mail got to.
327365 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
328366 pub enum SendState {
@@ -585,6 +623,9 @@ pub struct ActivityEvent {
585623 pub board_id: String,
586624 pub kind: ActivityKind,
587625 pub actor_id: String,
626+ /// The person the line is about — the one just assigned, say — when it
627+ /// is about anyone in particular.
628+ pub subject_id: Option<String>,
588629 pub detail: String,
589630 pub at: OffsetDateTime,
590631 }
@@ -646,7 +687,6 @@ pub struct Recipient {
646687 /// trait a test can wrap and count.
647688 #[async_trait]
648689 pub trait Store: BoardReads + DetailReads + 'static {
649-
650690 // -- live updates ------------------------------------------------------
651691
652692 /// A receiver of committed-write announcements. One [`Change`] per
@@ -705,6 +745,7 @@ pub trait Store: BoardReads + DetailReads + 'static {
705745 attachment_limit_bytes: u64,
706746 photo_limit_bytes: u64,
707747 allowed_file_types: &[String],
748+ mail_batch_minutes: u32,
708749 ) -> Result<()>;
709750
710751 // -- users -------------------------------------------------------------
@@ -722,6 +763,12 @@ pub trait Store: BoardReads + DetailReads + 'static {
722763
723764 async fn count_users(&self, workspace_id: &str) -> Result<u64>;
724765
766+ /// One person's totals, for their profile. A soft-deleted task counts
767+ /// nowhere: it has left the board, so it has left the person.
768+ ///
769+ /// This is a read, for looking: nothing announces.
770+ async fn user_stats(&self, user_id: &str) -> Result<UserStats>;
771+
725772 async fn set_password_hash(&self, user_id: &str, hash: &str) -> Result<()>;
726773
727774 async fn set_profile(&self, user_id: &str, display_name: &str) -> Result<()>;
@@ -964,10 +1011,13 @@ pub trait Store: BoardReads + DetailReads + 'static {
9641011
9651012 /// Appends one line to a task's activity trail and returns its row id.
9661013 /// `actor_id` is `None` when the system did it rather than a person.
1014+ /// `subject_id` is the person the line is ABOUT — the one just assigned,
1015+ /// say — and `None` for a line that is about nobody.
9671016 async fn record_activity(
9681017 &self,
9691018 task_id: &str,
9701019 actor_id: Option<&str>,
1020+ subject_id: Option<&str>,
9711021 kind: &ActivityKind,
9721022 detail: &str,
9731023 at: OffsetDateTime,
@@ -1033,6 +1083,29 @@ pub trait Store: BoardReads + DetailReads + 'static {
10331083 /// When each rule last got a mail accepted, for the "last sent" line.
10341084 async fn mail_rule_last_sent(&self, board_id: &str) -> Result<Vec<(String, OffsetDateTime)>>;
10351085
1086+ // -- tags --------------------------------------------------------------
1087+
1088+ /// Every tag on the board, in the admin's hand-set order.
1089+ async fn tags(&self, board_id: &str) -> Result<Vec<Tag>>;
1090+
1091+ /// Appends a tag at the end of the board's order. The name is unique per
1092+ /// board: two tags with one name are one project spelled twice.
1093+ async fn create_tag(&self, board_id: &str, name: &str, at: OffsetDateTime) -> Result<Tag>;
1094+
1095+ async fn rename_tag(&self, tag_id: &str, name: &str) -> Result<()>;
1096+
1097+ /// Deletes a tag. Its tasks move to the board's default tag; the default
1098+ /// itself is refused — it is where they would go.
1099+ async fn delete_tag(&self, tag_id: &str) -> Result<()>;
1100+
1101+ /// Swaps a tag with its neighbour in the order. A tag already at that end
1102+ /// stays put: nothing to swap is not an error.
1103+ async fn move_tag(&self, tag_id: &str, up: bool) -> Result<()>;
1104+
1105+ /// Sets the tag a task wears. A tag from another board is
1106+ /// [`StoreError::NotFound`] — it is not one of this board's projects at
1107+ /// all.
1108+ async fn set_task_tag(&self, task_id: &str, tag_id: &str) -> Result<()>;
10361109 // -- the send ledger ---------------------------------------------------
10371110
10381111 /// Takes ownership of one mail by writing its row, and answers `None` if
@@ -1240,6 +1313,27 @@ pub trait Store: BoardReads + DetailReads + 'static {
12401313 /// store, so no caller can mail one by forgetting to filter.
12411314 async fn recipients_for_board(&self, board_id: &str) -> Result<Vec<Recipient>>;
12421315
1316+ /// Pushes every mail still merely owed about this task, for this person,
1317+ /// out to `until` — but never past `cap`, the moment the oldest of them
1318+ /// stops waiting no matter what.
1319+ ///
1320+ /// This is the debounce: each new trigger about a card postpones the mail
1321+ /// the card already owes, so a person is told once, after the work has
1322+ /// settled. Only rows that are still pending and have never been
1323+ /// attempted move — a mail already refused is on its own retry clock, and
1324+ /// a batch must not drag it back.
1325+ async fn hold_batch(
1326+ &self,
1327+ task_id: &str,
1328+ recipient: &str,
1329+ until: OffsetDateTime,
1330+ cap: Duration,
1331+ ) -> Result<()>;
1332+
12431333 /// Whoever opened the task, unless they are a Viewer.
12441334 async fn recipients_for_task_creator(&self, task_id: &str) -> Result<Vec<Recipient>>;
1335+
1336+ /// One person by id, unless they are a Viewer — the subject of an
1337+ /// activity line, for a rule that mails the person the line is about.
1338+ async fn recipient(&self, user_id: &str) -> Result<Option<Recipient>>;
12451339 }
crates/izlek-core/src/store/reconcile.rsadded+738 -0
@@ -0,0 +1,738 @@
1+//! Reconcile a live Turso database with the declared whole schema.
2+//!
3+//! The live file is never altered in place. Instead a new file is built from
4+//! `migrations/0001_init.sql`, the data is copied with an explicit per-table
5+//! column map, the copy is verified, and only then the files are swapped. The
6+//! original file is kept as a timestamped backup and is never deleted.
7+
8+use super::{Result, StoreError};
9+use super::schema::{SCHEMA, declared_fingerprint, diff_report, fingerprint};
10+use turso::{Builder, Connection, params};
11+use ulid::Ulid;
12+
13+/// How the caller wants to confirm the rebuild.
14+pub struct ReconcileOptions {
15+ /// Print the diff and plan, then stop without touching anything.
16+ pub dry_run: bool,
17+ /// Skip the interactive confirmation.
18+ pub yes: bool,
19+ /// Boot path: do not prompt, log what happened and proceed.
20+ pub auto: bool,
21+}
22+
23+/// Rebuilds the database at `path` to match the declared schema.
24+///
25+/// - Empty or already-current databases are a no-op.
26+/// - A differing database is backed up, rebuilt, verified and swapped into
27+/// place.
28+/// - A rebuild that fails verification deletes the `.rebuilt` file and leaves
29+/// the original untouched.
30+pub async fn reconcile(path: &str, opts: ReconcileOptions) -> Result<()> {
31+ if path == ":memory:" {
32+ return Err(StoreError::Backend(
33+ "reconcile is not meaningful on an in-memory database".into(),
34+ ));
35+ }
36+ let db_path = std::path::Path::new(path);
37+ if !db_path.exists() {
38+ return Err(StoreError::Backend(format!("database not found: {}", path)));
39+ }
40+
41+ // Open the live database read-only to inspect its fingerprint.
42+ let old_db = Builder::new_local(path)
43+ .build()
44+ .await
45+ .map_err(|e| StoreError::Backend(e.to_string()))?;
46+ let old_conn = old_db.connect().map_err(|e| StoreError::Backend(e.to_string()))?;
47+
48+ let old_fp = fingerprint(&old_conn).await?;
49+ let new_fp = declared_fingerprint().await?;
50+
51+ if old_fp == new_fp {
52+ if !opts.auto {
53+ println!("database already matches the declared schema");
54+ }
55+ return Ok(());
56+ }
57+
58+ let diff = diff_report(&old_fp, &new_fp);
59+
60+ if opts.dry_run {
61+ println!("schema difference:\n{}", diff);
62+ println!("dry run: would rebuild {}", path);
63+ return Ok(());
64+ }
65+
66+ if opts.auto {
67+ eprintln!("database schema differs from declared schema; rebuilding automatically");
68+ eprintln!("difference:\n{}", diff);
69+ } else {
70+ println!("schema difference:\n{}", diff);
71+ if !opts.yes {
72+ print!("rebuild {}? [y/N] ", path);
73+ let _ = std::io::Write::flush(&mut std::io::stdout());
74+ let mut answer = String::new();
75+ match std::io::stdin().read_line(&mut answer) {
76+ Ok(_) if answer.trim().eq_ignore_ascii_case("y") => {}
77+ _ => {
78+ println!("rebuild cancelled");
79+ return Ok(());
80+ }
81+ }
82+ }
83+ }
84+
85+ let rebuilt_path = format!("{}.rebuilt", path);
86+ cleanup_rebuilt(&rebuilt_path);
87+
88+ let result = rebuild(path, &rebuilt_path, &old_conn).await;
89+
90+ // Close the read-only connection before any file moves; this also
91+ // releases the WAL locks on the original file.
92+ drop(old_conn);
93+ drop(old_db);
94+
95+ if let Err(e) = result {
96+ cleanup_rebuilt(&rebuilt_path);
97+ return Err(e);
98+ }
99+
100+ let backup_path = backup_name(path)?;
101+ std::fs::rename(path, &backup_path).map_err(|e| {
102+ StoreError::Backend(format!(
103+ "failed to move original database to backup {}: {}",
104+ backup_path, e
105+ ))
106+ })?;
107+ // SQLite WAL/SHM siblings belong to the main file; the backup must be a
108+ // complete database on its own, and the rebuilt file starts with none.
109+ rename_sibling(path, &backup_path, "-wal");
110+ rename_sibling(path, &backup_path, "-shm");
111+ if let Err(e) = std::fs::rename(&rebuilt_path, path) {
112+ // Best-effort undo so the live file is not gone. If this also fails,
113+ // the caller has both the backup and the rebuilt file to recover from.
114+ let _ = std::fs::rename(&backup_path, path);
115+ let _ = rename_sibling(&backup_path, path, "-wal");
116+ let _ = rename_sibling(&backup_path, path, "-shm");
117+ return Err(StoreError::Backend(format!(
118+ "failed to move rebuilt database into place {}: {}",
119+ rebuilt_path, e
120+ )));
121+ }
122+ // The rebuilt file was checkpointed before the swap, so its own sidecars
123+ // hold nothing — but a `.rebuilt-wal` left lying about would be adopted by
124+ // the NEXT rebuild's fresh `.rebuilt` file, which is how a stale WAL
125+ // corrupts a database that was otherwise fine.
126+ let _ = std::fs::remove_file(format!("{}-wal", rebuilt_path));
127+ let _ = std::fs::remove_file(format!("{}-shm", rebuilt_path));
128+
129+ if opts.auto {
130+ eprintln!("database rebuilt and verified; original backed up to {}", backup_path);
131+ eprintln!("rebuilt database now at {}", path);
132+ } else {
133+ println!("database rebuilt and verified");
134+ println!("original backed up to {}", backup_path);
135+ println!("rebuilt database now at {}", path);
136+ }
137+
138+ Ok(())
139+}
140+
141+/// Does the actual rebuild: creates `.rebuilt`, copies the data (seeding the
142+/// tags partway, where the foreign keys allow it), and verifies the result. On success the rebuilt file is complete and
143+/// checkpointed; on failure the caller deletes it.
144+async fn rebuild(path: &str, rebuilt_path: &str, old_conn: &Connection) -> Result<()> {
145+ // The copy runs as `INSERT ... SELECT FROM old.<table>`, which needs
146+ // ATTACH — still gated in this engine, and switched on only here, for the
147+ // one connection that does the rebuild. The verification afterwards is
148+ // what protects the data, not the copy's mechanism.
149+ let new_db = Builder::new_local(rebuilt_path)
150+ .experimental_attach(true)
151+ .build()
152+ .await
153+ .map_err(|e| StoreError::Backend(e.to_string()))?;
154+ let new_conn = new_db.connect().map_err(|e| StoreError::Backend(e.to_string()))?;
155+
156+ new_conn
157+ .execute("PRAGMA foreign_keys = ON", ())
158+ .await
159+ .map_err(|e| StoreError::Backend(e.to_string()))?;
160+ new_conn
161+ .execute_batch(SCHEMA)
162+ .await
163+ .map_err(|e| StoreError::Backend(e.to_string()))?;
164+
165+ copy_data(old_conn, &new_conn, path).await?;
166+ verify(old_conn, &new_conn).await?;
167+
168+ // A checkpoint PRAGMA answers with a row, so it is a query: `execute`
169+ // treats a row as a failure ("unexpected row during execution").
170+ let mut checkpoint = new_conn
171+ .query("PRAGMA wal_checkpoint(TRUNCATE)", ())
172+ .await
173+ .map_err(|e| StoreError::Backend(format!("checkpoint: {e}")))?;
174+ while checkpoint
175+ .next()
176+ .await
177+ .map_err(|e| StoreError::Backend(format!("checkpoint: {e}")))?
178+ .is_some()
179+ {}
180+
181+ Ok(())
182+}
183+
184+/// Seeds one `General` tag per board into the new database, before `task`
185+/// is copied. The tag is the default for that board, so every task copied
186+/// afterwards can map its `tag_id` to it.
187+async fn seed_general_tags(old_conn: &Connection, new_conn: &Connection) -> Result<()> {
188+ let mut rows = old_conn
189+ .query("SELECT id, created_at FROM board", ())
190+ .await
191+ .map_err(|e| StoreError::Backend(e.to_string()))?;
192+ while let Some(row) = rows.next().await.map_err(|e| StoreError::Backend(e.to_string()))? {
193+ let board_id: String = row.get(0).map_err(|e| StoreError::Backend(e.to_string()))?;
194+ let created_at: String = row.get(1).map_err(|e| StoreError::Backend(e.to_string()))?;
195+ let id = Ulid::new().to_string();
196+ new_conn
197+ .execute(
198+ "INSERT INTO main.tag (id, board_id, name, position, is_default, created_at) \
199+ VALUES (?1, ?2, 'General', 0, 1, ?3)",
200+ params![id, board_id, created_at],
201+ )
202+ .await
203+ .map_err(|e| StoreError::Backend(e.to_string()))?;
204+ }
205+ Ok(())
206+}
207+
208+/// A per-table column map. Every destination column must appear exactly once;
209+/// `copy_data` validates this against the declared schema before inserting.
210+struct TableMap {
211+ name: &'static str,
212+ columns: Vec<(&'static str, String)>,
213+}
214+
215+/// Builds the explicit column map. Unchanged tables map every column to
216+/// `old.<col>`; the changed tables carry the migration-specific expressions.
217+fn build_maps(old_has_smtp_check: bool, old_has_batch_window: bool) -> Vec<TableMap> {
218+ let mut maps = Vec::new();
219+
220+ maps.push(TableMap {
221+ name: "workspace",
222+ columns: vec![
223+ ("id", "old.id".into()),
224+ ("name", "old.name".into()),
225+ ("created_at", "old.created_at".into()),
226+ ("attachment_limit_bytes", "old.attachment_limit_bytes".into()),
227+ ("photo_limit_bytes", "old.photo_limit_bytes".into()),
228+ ("allowed_file_types", "old.allowed_file_types".into()),
229+ (
230+ // A database written before notifications were batched has no
231+ // window of its own; it starts on the schema's own default
232+ // rather than on zero, which would keep the old behaviour by
233+ // accident and make the feature look broken.
234+ "mail_batch_minutes",
235+ if old_has_batch_window {
236+ "old.mail_batch_minutes".into()
237+ } else {
238+ "5".to_string()
239+ },
240+ ),
241+ ("smtp_host", "old.smtp_host".into()),
242+ ("smtp_port", "old.smtp_port".into()),
243+ ("smtp_username", "old.smtp_username".into()),
244+ ("smtp_password", "old.smtp_password".into()),
245+ ("smtp_from_name", "old.smtp_from_name".into()),
246+ ("smtp_from_address", "old.smtp_from_address".into()),
247+ ("smtp_test_at", "old.smtp_test_at".into()),
248+ ("smtp_test_ms", "old.smtp_test_ms".into()),
249+ ("smtp_test_error", "old.smtp_test_error".into()),
250+ (
251+ "smtp_check_at",
252+ if old_has_smtp_check {
253+ "old.smtp_check_at".into()
254+ } else {
255+ "NULL".into()
256+ },
257+ ),
258+ (
259+ "smtp_check_ms",
260+ if old_has_smtp_check {
261+ "old.smtp_check_ms".into()
262+ } else {
263+ "NULL".into()
264+ },
265+ ),
266+ (
267+ "smtp_check_error",
268+ if old_has_smtp_check {
269+ "old.smtp_check_error".into()
270+ } else {
271+ "NULL".into()
272+ },
273+ ),
274+ ("public_url", "old.public_url".into()),
275+ ],
276+ });
277+
278+ maps.push(TableMap {
279+ name: "user",
280+ columns: old_cols(&[
281+ "id",
282+ "workspace_id",
283+ "email",
284+ "display_name",
285+ "role",
286+ "password_hash",
287+ "invited_by",
288+ "timezone",
289+ "theme",
290+ "language",
291+ "ui",
292+ "photo",
293+ "photo_mime",
294+ "created_at",
295+ "last_signed_in_at",
296+ ]),
297+ });
298+ maps.push(TableMap {
299+ name: "workspace_owner",
300+ columns: old_cols(&["singleton", "user_id", "claimed_at"]),
301+ });
302+ maps.push(TableMap {
303+ name: "signin_link",
304+ columns: old_cols(&["id", "user_id", "token_hash", "created_at", "expires_at", "used_at"]),
305+ });
306+ maps.push(TableMap {
307+ name: "session",
308+ columns: old_cols(&["id", "user_id", "token_hash", "created_at", "expires_at", "revoked_at"]),
309+ });
310+ maps.push(TableMap {
311+ name: "auth_attempt",
312+ columns: old_cols(&["id", "bucket", "attempted_at"]),
313+ });
314+ maps.push(TableMap {
315+ name: "board",
316+ columns: old_cols(&["id", "workspace_id", "name", "task_prefix", "created_at"]),
317+ });
318+ maps.push(TableMap {
319+ name: "board_column",
320+ columns: old_cols(&["id", "board_id", "name", "position", "is_done"]),
321+ });
322+ // `tag` is seeded, not copied.
323+ maps.push(TableMap {
324+ name: "task",
325+ columns: vec![
326+ ("id", "old.id".into()),
327+ ("board_id", "old.board_id".into()),
328+ ("parent_id", "old.parent_id".into()),
329+ ("task_key", "old.task_key".into()),
330+ ("title", "old.title".into()),
331+ ("description", "old.description".into()),
332+ ("column_id", "old.column_id".into()),
333+ (
334+ "tag_id",
335+ "(SELECT id FROM main.tag WHERE board_id = old.board_id AND is_default = 1)".into(),
336+ ),
337+ ("deadline", "old.deadline".into()),
338+ ("position", "old.position".into()),
339+ ("created_by", "old.created_by".into()),
340+ ("created_at", "old.created_at".into()),
341+ ("updated_at", "old.updated_at".into()),
342+ ("done_at", "old.done_at".into()),
343+ ("deleted_at", "old.deleted_at".into()),
344+ ],
345+ });
346+ maps.push(TableMap {
347+ name: "task_assignee",
348+ columns: old_cols(&["task_id", "user_id"]),
349+ });
350+ maps.push(TableMap {
351+ name: "task_watcher",
352+ columns: old_cols(&["task_id", "user_id"]),
353+ });
354+ maps.push(TableMap {
355+ name: "task_dependency",
356+ columns: old_cols(&[
357+ "blocked_task_id",
358+ "blocking_task_id",
359+ "created_at",
360+ "cleared_at",
361+ ]),
362+ });
363+ maps.push(TableMap {
364+ name: "comment",
365+ columns: old_cols(&["id", "task_id", "author_id", "body", "created_at"]),
366+ });
367+ maps.push(TableMap {
368+ name: "attachment",
369+ columns: old_cols(&[
370+ "id",
371+ "task_id",
372+ "comment_id",
373+ "file_name",
374+ "mime_type",
375+ "size_bytes",
376+ "bytes",
377+ "uploaded_by",
378+ "created_at",
379+ ]),
380+ });
381+ maps.push(TableMap {
382+ name: "transition",
383+ columns: old_cols(&[
384+ "id",
385+ "task_id",
386+ "from_column",
387+ "to_column",
388+ "actor_id",
389+ "created_at",
390+ ]),
391+ });
392+ maps.push(TableMap {
393+ name: "freeing",
394+ columns: old_cols(&[
395+ "id",
396+ "board_id",
397+ "cause_key",
398+ "cause_title",
399+ "actor_id",
400+ "created_at",
401+ ]),
402+ });
403+ maps.push(TableMap {
404+ name: "activity",
405+ columns: vec![
406+ ("id", "old.id".into()),
407+ ("task_id", "old.task_id".into()),
408+ ("actor_id", "old.actor_id".into()),
409+ ("subject_id", "NULL".into()),
410+ ("kind", "old.kind".into()),
411+ ("detail", "old.detail".into()),
412+ ("created_at", "old.created_at".into()),
413+ ],
414+ });
415+ maps.push(TableMap {
416+ name: "mail_rule",
417+ columns: old_cols(&[
418+ "id",
419+ "board_id",
420+ "trigger_kind",
421+ "trigger_column",
422+ "subject",
423+ "audience",
424+ "enabled",
425+ "created_at",
426+ "include_task_details",
427+ ]),
428+ });
429+ maps.push(TableMap {
430+ name: "mail_send",
431+ columns: old_cols(&[
432+ "id",
433+ "rule_id",
434+ "event_id",
435+ "task_id",
436+ "recipient",
437+ "state",
438+ "attempts",
439+ "last_error",
440+ "claimed_at",
441+ "next_attempt_at",
442+ "sent_at",
443+ "kind",
444+ "subject",
445+ "body",
446+ ]),
447+ });
448+ maps.push(TableMap {
449+ name: "mail_decision",
450+ columns: old_cols(&[
451+ "id",
452+ "rule_id",
453+ "event_id",
454+ "task_id",
455+ "outcome",
456+ "detail",
457+ "created_at",
458+ ]),
459+ });
460+
461+ maps
462+}
463+
464+fn old_cols(cols: &[&'static str]) -> Vec<(&'static str, String)> {
465+ cols.iter().map(|c| (*c, format!("old.{}", c))).collect()
466+}
467+
468+/// Returns true if the attached old `workspace` table already carries the
469+/// sender-check columns added by the old 0002 migration.
470+async fn old_has_column(conn: &Connection, table: &str, column: &str) -> Result<bool> {
471+ let mut rows = conn
472+ .query(&format!("PRAGMA table_info({table})"), ())
473+ .await
474+ .map_err(|e| StoreError::Backend(e.to_string()))?;
475+ while let Some(row) = rows.next().await.map_err(|e| StoreError::Backend(e.to_string()))? {
476+ let name: String = row.get(1).map_err(|e| StoreError::Backend(e.to_string()))?;
477+ if name == column {
478+ return Ok(true);
479+ }
480+ }
481+ Ok(false)
482+}
483+
484+/// Validates that every destination column is covered and that no map
485+/// references a column that does not exist. A missing column is a startup
486+/// error, never a silent NULL.
487+async fn validate_maps(conn: &Connection, maps: &[TableMap]) -> Result<()> {
488+ use std::collections::HashSet;
489+
490+ for map in maps {
491+ let sql = format!("PRAGMA table_info({})", map.name);
492+ let mut rows = conn
493+ .query(&sql, ())
494+ .await
495+ .map_err(|e| StoreError::Backend(e.to_string()))?;
496+ let mut actual = HashSet::new();
497+ while let Some(row) = rows.next().await.map_err(|e| StoreError::Backend(e.to_string()))? {
498+ let name: String = row.get(1).map_err(|e| StoreError::Backend(e.to_string()))?;
499+ actual.insert(name);
500+ }
501+
502+ for (col, _) in &map.columns {
503+ if !actual.contains(*col) {
504+ return Err(StoreError::Backend(format!(
505+ "reconcile map for {} references missing column {}",
506+ map.name, col
507+ )));
508+ }
509+ }
510+ for col in actual {
511+ if !map.columns.iter().any(|(c, _)| c == &col) {
512+ return Err(StoreError::Backend(format!(
513+ "reconcile map for {} is missing column {} (would become NULL)",
514+ map.name, col
515+ )));
516+ }
517+ }
518+ }
519+ Ok(())
520+}
521+
522+/// Copies every mapped table from the attached old database into the new
523+/// main schema, in foreign-key-safe order.
524+async fn copy_data(old_conn: &Connection, new_conn: &Connection, path: &str) -> Result<()> {
525+ let escaped = path.replace('\'', "''");
526+ new_conn
527+ .execute(&format!("ATTACH DATABASE '{}' AS old", escaped), ())
528+ .await
529+ .map_err(|e| StoreError::Backend(e.to_string()))?;
530+
531+ let has_smtp_check = old_has_column(old_conn, "workspace", "smtp_check_at").await?;
532+ let has_batch_window =
533+ old_has_column(old_conn, "workspace", "mail_batch_minutes").await?;
534+ let maps = build_maps(has_smtp_check, has_batch_window);
535+ validate_maps(new_conn, &maps).await?;
536+
537+ for map in maps {
538+ // The `General` tags are seeded between `board` and `task`: they point
539+ // at boards, so the boards must already be here, and the tasks that
540+ // will point back at them must not be here yet.
541+ if map.name == "task" {
542+ seed_general_tags(old_conn, new_conn).await?;
543+ }
544+ let cols = map.columns.iter().map(|(c, _)| *c).collect::<Vec<_>>().join(", ");
545+ // `old` is the attached SCHEMA, not a table, so `old.id` in a select
546+ // list reads as "table old, column id". The source table is aliased
547+ // and the maps' `old.` prefix rewritten onto that alias.
548+ let exprs = map
549+ .columns
550+ .iter()
551+ .map(|(_, e)| e.replace("old.", "src."))
552+ .collect::<Vec<_>>()
553+ .join(", ");
554+ let sql = format!(
555+ "INSERT INTO main.{} ({}) SELECT {} FROM old.{} AS src",
556+ map.name, cols, exprs, map.name
557+ );
558+ new_conn
559+ .execute(&sql, ())
560+ .await
561+ .map_err(|e| StoreError::Backend(format!("{} while copying {}: {}", e, map.name, sql)))?;
562+ }
563+
564+ new_conn
565+ .execute("DETACH DATABASE old", ())
566+ .await
567+ .map_err(|e| StoreError::Backend(e.to_string()))?;
568+
569+ Ok(())
570+}
571+
572+/// Verifies the rebuilt database before the swap.
573+async fn verify(old_conn: &Connection, new_conn: &Connection) -> Result<()> {
574+ let mut rows = new_conn
575+ .query("PRAGMA foreign_key_check", ())
576+ .await
577+ .map_err(|e| StoreError::Backend(e.to_string()))?;
578+ let mut fk_errors = Vec::new();
579+ while let Some(row) = rows.next().await.map_err(|e| StoreError::Backend(e.to_string()))? {
580+ let table: String = row.get(0).map_err(|e| StoreError::Backend(e.to_string()))?;
581+ let rowid: i64 = row.get(1).map_err(|e| StoreError::Backend(e.to_string()))?;
582+ let parent: String = row.get(2).map_err(|e| StoreError::Backend(e.to_string()))?;
583+ let fkid: i64 = row.get(3).map_err(|e| StoreError::Backend(e.to_string()))?;
584+ fk_errors.push(format!(
585+ "{} rowid {} references {} (foreign key {})",
586+ table, rowid, parent, fkid
587+ ));
588+ }
589+ if !fk_errors.is_empty() {
590+ return Err(StoreError::Backend(format!(
591+ "foreign key check failed:\n{}",
592+ fk_errors.join("\n")
593+ )));
594+ }
595+
596+ let mut rows = new_conn
597+ .query("PRAGMA integrity_check", ())
598+ .await
599+ .map_err(|e| StoreError::Backend(e.to_string()))?;
600+ let mut integrity = Vec::new();
601+ while let Some(row) = rows.next().await.map_err(|e| StoreError::Backend(e.to_string()))? {
602+ let msg: String = row.get(0).map_err(|e| StoreError::Backend(e.to_string()))?;
603+ integrity.push(msg);
604+ }
605+ if integrity.len() != 1 || integrity[0] != "ok" {
606+ return Err(StoreError::Backend(format!(
607+ "integrity check failed: {:?}",
608+ integrity
609+ )));
610+ }
611+
612+ let tables = [
613+ "workspace",
614+ "user",
615+ "workspace_owner",
616+ "signin_link",
617+ "session",
618+ "auth_attempt",
619+ "board",
620+ "board_column",
621+ "task",
622+ "task_assignee",
623+ "task_watcher",
624+ "task_dependency",
625+ "comment",
626+ "attachment",
627+ "transition",
628+ "freeing",
629+ "activity",
630+ "mail_rule",
631+ "mail_send",
632+ "mail_decision",
633+ ];
634+ for table in tables {
635+ let old_count = count_rows(old_conn, table).await?;
636+ let new_count = count_rows(new_conn, table).await?;
637+ if old_count != new_count {
638+ return Err(StoreError::Backend(format!(
639+ "row count mismatch for {}: old {} new {}",
640+ table, old_count, new_count
641+ )));
642+ }
643+ }
644+
645+ // `tag` is new: one default tag per board.
646+ let board_count = count_rows(old_conn, "board").await?;
647+ let tag_count = count_rows(new_conn, "tag").await?;
648+ if tag_count != board_count {
649+ return Err(StoreError::Backend(format!(
650+ "tag row count {} does not match board count {}",
651+ tag_count, board_count
652+ )));
653+ }
654+
655+ Ok(())
656+}
657+
658+async fn count_rows(conn: &Connection, table: &str) -> Result<i64> {
659+ let sql = format!("SELECT COUNT(*) FROM {}", table);
660+ let mut rows = conn
661+ .query(&sql, ())
662+ .await
663+ .map_err(|e| StoreError::Backend(e.to_string()))?;
664+ let Some(row) = rows.next().await.map_err(|e| StoreError::Backend(e.to_string()))? else {
665+ return Err(StoreError::Backend(format!(
666+ "could not count rows in {}",
667+ table
668+ )));
669+ };
670+ row.get::<i64>(0).map_err(|e| StoreError::Backend(e.to_string()))
671+}
672+
673+fn cleanup_rebuilt(rebuilt_path: &str) {
674+ let _ = std::fs::remove_file(rebuilt_path);
675+ let _ = std::fs::remove_file(format!("{}-wal", rebuilt_path));
676+ let _ = std::fs::remove_file(format!("{}-shm", rebuilt_path));
677+}
678+
679+/// Move a SQLite sidecar file (`-wal` or `-shm`) if it exists. A missing
680+/// sibling is fine: WAL mode may not have created one, and the backup is
681+/// still consistent without it.
682+fn rename_sibling(from: &str, to: &str, suffix: &str) {
683+ let from_path = format!("{}{}", from, suffix);
684+ let to_path = format!("{}{}", to, suffix);
685+ if std::path::Path::new(&from_path).exists() {
686+ let _ = std::fs::rename(&from_path, &to_path);
687+ }
688+}
689+
690+fn backup_name(path: &str) -> Result<String> {
691+ let format = time::format_description::parse_borrowed::<2>(
692+ "[year]-[month]-[day]T[hour][minute][second]Z",
693+ )
694+ .map_err(|e| StoreError::Backend(format!("invalid time format: {}", e)))?;
695+ let stamp = time::OffsetDateTime::now_utc()
696+ .format(&format)
697+ .map_err(|e| StoreError::Backend(format!("time format failed: {}", e)))?;
698+
699+ let candidate = format!("{}.backup-{}", path, stamp);
700+ if !std::path::Path::new(&candidate).exists() {
701+ return Ok(candidate);
702+ }
703+ let mut n = 1;
704+ loop {
705+ let candidate = format!("{}.backup-{}-{}", path, stamp, n);
706+ if !std::path::Path::new(&candidate).exists() {
707+ return Ok(candidate);
708+ }
709+ n += 1;
710+ if n > 1000 {
711+ return Err(StoreError::Backend(
712+ "could not find an unused backup name".into(),
713+ ));
714+ }
715+ }
716+}
717+
718+#[cfg(test)]
719+mod tests {
720+ use super::backup_name;
721+
722+ #[test]
723+ fn backup_name_has_no_colons_or_spaces() {
724+ let name = backup_name("/tmp/izlek.db").unwrap();
725+ assert!(name.starts_with("/tmp/izlek.db.backup-"));
726+ assert!(!name.contains(':'));
727+ assert!(!name.contains(' '));
728+ }
729+
730+ #[test]
731+ fn backup_name_avoids_collision() {
732+ let first = backup_name("/tmp/izlek.db").unwrap();
733+ std::fs::File::create(&first).unwrap();
734+ let second = backup_name("/tmp/izlek.db").unwrap();
735+ assert_ne!(first, second);
736+ std::fs::remove_file(&first).unwrap();
737+ }
738+}
crates/izlek-core/src/store/schema.rsadded+360 -0
@@ -0,0 +1,360 @@
1+//! Schema fingerprinting: compare the database SQLite actually has with the
2+//! declared whole schema in `migrations/0001_init.sql`.
3+//!
4+//! SQLite stores `CREATE` statements as written, comments and all, so two
5+//! databases built from the same logical schema but different comments or
6+//! whitespace would otherwise look different. The normaliser here strips the
7+//! cosmetic differences that do not change what the schema means.
8+
9+use super::{Result, StoreError};
10+use turso::Connection;
11+
12+/// The declared whole schema, applied to an empty database.
13+pub(crate) const SCHEMA: &str = include_str!("../../migrations/0001_init.sql");
14+
15+/// Reads and normalises the schema of the connected database.
16+///
17+/// The fingerprint is a deterministic text built from `sqlite_master`:
18+/// `type|name|normalised_sql` for every non-sqlite object, ordered by type
19+/// and name. Two schemas that mean the same thing produce the same string;
20+/// two schemas that differ in tables, indexes, columns or constraints do not.
21+pub async fn fingerprint(conn: &Connection) -> Result<String> {
22+ let mut rows = conn
23+ .query(
24+ "SELECT type, name, sql FROM sqlite_master \
25+ WHERE name NOT LIKE 'sqlite_%' \
26+ ORDER BY type, name",
27+ (),
28+ )
29+ .await
30+ .map_err(|e| StoreError::Backend(e.to_string()))?;
31+
32+ let mut out = String::new();
33+ while let Some(row) = rows.next().await.map_err(|e| StoreError::Backend(e.to_string()))? {
34+ let t: String = row.get(0).map_err(|e| StoreError::Backend(e.to_string()))?;
35+ let name: String = row.get(1).map_err(|e| StoreError::Backend(e.to_string()))?;
36+ let sql: Option<String> =
37+ row.get(2).map_err(|e| StoreError::Backend(e.to_string()))?;
38+ out.push_str(&t);
39+ out.push('|');
40+ out.push_str(&name);
41+ out.push('|');
42+ if let Some(sql) = sql {
43+ out.push_str(&normalize_schema(&sql));
44+ }
45+ out.push('\n');
46+ }
47+ Ok(out)
48+}
49+
50+/// Builds an in-memory database from the declared schema and fingerprints it.
51+pub async fn declared_fingerprint() -> Result<String> {
52+ let db = turso::Builder::new_local(":memory:")
53+ .build()
54+ .await
55+ .map_err(|e| StoreError::Backend(e.to_string()))?;
56+ let conn = db.connect().map_err(|e| StoreError::Backend(e.to_string()))?;
57+ conn.execute_batch(SCHEMA)
58+ .await
59+ .map_err(|e| StoreError::Backend(e.to_string()))?;
60+ fingerprint(&conn).await
61+}
62+
63+/// A single schema object for diff reporting.
64+#[derive(Debug, Clone)]
65+pub(crate) struct SchemaObject {
66+ pub(crate) kind: String,
67+ pub(crate) name: String,
68+ pub(crate) sql: String,
69+}
70+
71+/// Parses the normalised schema into objects keyed by (kind, name).
72+pub(crate) fn parse_objects(fingerprint: &str) -> Vec<SchemaObject> {
73+ fingerprint
74+ .lines()
75+ .filter(|line| !line.is_empty())
76+ .filter_map(|line| {
77+ let mut parts = line.splitn(3, '|');
78+ let kind = parts.next()?.to_string();
79+ let name = parts.next()?.to_string();
80+ let sql = parts.next().unwrap_or("").to_string();
81+ Some(SchemaObject { kind, name, sql })
82+ })
83+ .collect()
84+}
85+
86+/// Human-readable description of how two fingerprints differ.
87+pub(crate) fn diff_report(old: &str, new: &str) -> String {
88+ let old_objs = parse_objects(old);
89+ let new_objs = parse_objects(new);
90+
91+ let mut missing = Vec::new();
92+ let mut extra = Vec::new();
93+ let mut changed = Vec::new();
94+
95+ for old_obj in &old_objs {
96+ match new_objs.iter().find(|n| n.kind == old_obj.kind && n.name == old_obj.name) {
97+ Some(new_obj) if new_obj.sql != old_obj.sql => changed.push((old_obj, new_obj)),
98+ Some(_) => {}
99+ None => missing.push(old_obj),
100+ }
101+ }
102+ for new_obj in &new_objs {
103+ if !old_objs.iter().any(|o| o.kind == new_obj.kind && o.name == new_obj.name) {
104+ extra.push(new_obj);
105+ }
106+ }
107+
108+ let mut lines = Vec::new();
109+ for obj in missing {
110+ lines.push(format!("- {} {} (removed)", obj.kind, obj.name));
111+ }
112+ for obj in extra {
113+ lines.push(format!("+ {} {} (added)", obj.kind, obj.name));
114+ }
115+ for (old_obj, new_obj) in changed {
116+ lines.push(format!("~ {} {} (changed)", old_obj.kind, old_obj.name));
117+ if old_obj.kind == "table" {
118+ let old_cols = extract_column_names(&old_obj.sql);
119+ let new_cols = extract_column_names(&new_obj.sql);
120+ let added: Vec<&str> = new_cols
121+ .iter()
122+ .filter(|c| !old_cols.contains(c))
123+ .map(String::as_str)
124+ .collect();
125+ let removed: Vec<&str> = old_cols
126+ .iter()
127+ .filter(|c| !new_cols.contains(c))
128+ .map(String::as_str)
129+ .collect();
130+ if !added.is_empty() {
131+ lines.push(format!(" added columns: {}", added.join(", ")));
132+ }
133+ if !removed.is_empty() {
134+ lines.push(format!(" removed columns: {}", removed.join(", ")));
135+ }
136+ }
137+ }
138+
139+ if lines.is_empty() {
140+ "schemas differ (cosmetic normalisation only)".to_string()
141+ } else {
142+ lines.join("\n")
143+ }
144+}
145+
146+/// Extracts the column names from a normalised CREATE TABLE statement.
147+/// Constraints at the table level are ignored; only top-level definitions
148+/// that start with an identifier are collected.
149+fn extract_column_names(sql: &str) -> Vec<String> {
150+ let body = match sql.strip_prefix("CREATE TABLE ") {
151+ Some(rest) => rest,
152+ None => return Vec::new(),
153+ };
154+ let body = remove_if_not_exists(body);
155+ let Some(start) = body.find('(') else {
156+ return Vec::new();
157+ };
158+ let Some(end) = body.rfind(')') else {
159+ return Vec::new();
160+ };
161+ let body = &body[start + 1..end];
162+
163+ let mut cols = Vec::new();
164+ let mut depth = 0i32;
165+ let mut current = String::new();
166+ for ch in body.chars() {
167+ match ch {
168+ '(' => {
169+ depth += 1;
170+ current.push(ch);
171+ }
172+ ')' => {
173+ depth -= 1;
174+ current.push(ch);
175+ }
176+ ',' if depth == 0 => {
177+ if let Some(col) = first_identifier(&current) {
178+ cols.push(col);
179+ }
180+ current.clear();
181+ }
182+ _ => current.push(ch),
183+ }
184+ }
185+ if !current.is_empty() {
186+ if let Some(col) = first_identifier(&current) {
187+ cols.push(col);
188+ }
189+ }
190+ cols
191+}
192+
193+fn first_identifier(item: &str) -> Option<String> {
194+ let item = item.trim();
195+ if item.is_empty() {
196+ return None;
197+ }
198+ let first = item.split_whitespace().next()?;
199+ let first = first.to_lowercase();
200+ if first == "constraint"
201+ || first == "primary"
202+ || first == "unique"
203+ || first == "check"
204+ || first == "foreign"
205+ {
206+ return None;
207+ }
208+ Some(first)
209+}
210+
211+/// Normalises SQL text so that cosmetic differences disappear.
212+///
213+/// Differences deliberately ignored:
214+/// - whitespace runs collapse to a single space;
215+/// - SQL comments (`--` to end of line, `/* ... */`) are removed;
216+/// - `IF NOT EXISTS` is removed (case-insensitive, whole tokens only).
217+///
218+/// Differences deliberately preserved:
219+/// - identifier case and spelling;
220+/// - string literal contents, including any whitespace or comment-like text
221+/// inside them;
222+/// - numeric literals, keyword order and constraint text.
223+fn normalize_schema(sql: &str) -> String {
224+ let mut out = String::with_capacity(sql.len());
225+ let mut chars = sql.chars().peekable();
226+ let mut in_string = false;
227+ let mut prev_ws = false;
228+
229+ while let Some(ch) = chars.next() {
230+ if in_string {
231+ out.push(ch);
232+ if ch == '\'' {
233+ if chars.peek() == Some(&'\'') {
234+ out.push(chars.next().unwrap());
235+ } else {
236+ in_string = false;
237+ }
238+ }
239+ continue;
240+ }
241+
242+ if ch == '-' && chars.peek() == Some(&'-') {
243+ chars.next();
244+ while let Some(c) = chars.next() {
245+ if c == '\n' {
246+ break;
247+ }
248+ }
249+ prev_ws = true;
250+ continue;
251+ }
252+
253+ if ch == '/' && chars.peek() == Some(&'*') {
254+ chars.next();
255+ while let Some(c) = chars.next() {
256+ if c == '*' && chars.peek() == Some(&'/') {
257+ chars.next();
258+ break;
259+ }
260+ }
261+ prev_ws = true;
262+ continue;
263+ }
264+
265+ if ch == '\'' {
266+ in_string = true;
267+ out.push(ch);
268+ prev_ws = false;
269+ continue;
270+ }
271+
272+ if ch.is_whitespace() {
273+ prev_ws = true;
274+ continue;
275+ }
276+
277+ if prev_ws && !out.is_empty() {
278+ out.push(' ');
279+ }
280+ out.push(ch);
281+ prev_ws = false;
282+ }
283+
284+ remove_if_not_exists(&out)
285+}
286+
287+/// Strips a normalised `IF NOT EXISTS` token sequence, preserving whitespace
288+/// around it. Because `normalize_schema` has already collapsed whitespace, the
289+/// sequence appears as separate tokens separated by single spaces.
290+fn remove_if_not_exists(sql: &str) -> String {
291+ let tokens: Vec<&str> = sql.split(' ').collect();
292+ let mut out = Vec::with_capacity(tokens.len());
293+ let mut i = 0;
294+ while i < tokens.len() {
295+ if i + 2 < tokens.len()
296+ && tokens[i].eq_ignore_ascii_case("IF")
297+ && tokens[i + 1].eq_ignore_ascii_case("NOT")
298+ && tokens[i + 2].eq_ignore_ascii_case("EXISTS")
299+ {
300+ i += 3;
301+ } else {
302+ out.push(tokens[i]);
303+ i += 1;
304+ }
305+ }
306+ out.join(" ")
307+}
308+
309+#[cfg(test)]
310+mod tests {
311+ use super::{normalize_schema, parse_objects};
312+
313+ #[test]
314+ fn comments_and_whitespace_do_not_change_meaning() {
315+ let a = "CREATE TABLE foo (\n id INTEGER, -- the key\n name TEXT /* a comment */\n);";
316+ let b = "CREATE TABLE foo ( id INTEGER, name TEXT );";
317+ assert_eq!(normalize_schema(a), normalize_schema(b));
318+ }
319+
320+ #[test]
321+ fn if_not_exists_is_ignored() {
322+ let a = "CREATE TABLE IF NOT EXISTS foo (id INTEGER);";
323+ let b = "CREATE TABLE foo (id INTEGER);";
324+ assert_eq!(normalize_schema(a), normalize_schema(b));
325+ }
326+
327+ #[test]
328+ fn string_literals_are_preserved() {
329+ let a = "CREATE TABLE foo (name TEXT DEFAULT 'a -- b /* c */');";
330+ let b = "CREATE TABLE foo (name TEXT DEFAULT 'a -- b /* c */');";
331+ assert_eq!(normalize_schema(a), normalize_schema(b));
332+ }
333+
334+ #[test]
335+ fn real_differences_still_differ() {
336+ let a = "CREATE TABLE foo (id INTEGER);";
337+ let b = "CREATE TABLE foo (id TEXT);";
338+ assert_ne!(normalize_schema(a), normalize_schema(b));
339+ }
340+
341+ #[test]
342+ fn if_not_exists_does_not_corrupt_identifiers() {
343+ // The stripper looks for whole tokens; words that merely appear
344+ // inside identifiers or string literals must stay put.
345+ let a = "CREATE TABLE IF NOT EXISTS notification (if_not_exists TEXT DEFAULT 'IF NOT EXISTS');";
346+ let b = "CREATE TABLE notification (if_not_exists TEXT DEFAULT 'IF NOT EXISTS');";
347+ assert_eq!(normalize_schema(a), normalize_schema(b));
348+ }
349+
350+ #[test]
351+ fn partial_index_where_clause_is_parsed_safely() {
352+ // Partial-index SQL contains a WHERE clause; diff_report must not
353+ // try to extract column names from it, and parsing must not panic.
354+ let fp = "index|tag_one_default|CREATE UNIQUE INDEX tag_one_default ON tag(board_id) WHERE is_default = 1\n";
355+ let objs = parse_objects(fp);
356+ assert_eq!(objs.len(), 1);
357+ assert_eq!(objs[0].kind, "index");
358+ assert_eq!(objs[0].name, "tag_one_default");
359+ }
360+}
crates/izlek-core/src/store/turso_store.rsmodified+723 -319
@@ -7,7 +7,7 @@
77
88 use async_trait::async_trait;
99 use rand::Rng;
10-use time::OffsetDateTime;
10+use time::{Duration, OffsetDateTime};
1111 use time::format_description::well_known::Rfc3339;
1212 use turso::transaction::TransactionBehavior;
1313 use turso::{Builder, Connection, Row, Value, params};
@@ -15,32 +15,24 @@ use ulid::Ulid;
1515
1616 use super::secret;
1717 use super::{
18- ActivityEvent, ActivityFilter, ActivityLine, Attachment, Audience, CommentWritten, Deletion,
19- ClaimedSend, Dir, Event, FeedCursor, FeedPage, Freeing, MailDecision, MailOutcome, MailRule,
20- MailSend,
21- NewAttachment, NewSender, NewTask, NewUser, Recipient, Result, SendKind, SendState,
22- SenderCheck, SenderTest, Session, SigninLink, Store, StoreError, TaskCreated, Trigger, User,
23- Workspace,
18+ ActivityEvent, ActivityFilter, ActivityLine, Attachment, Audience, ClaimedSend, CommentWritten,
19+ Deletion, Dir, Event, FeedCursor, FeedPage, Freeing, MailDecision, MailOutcome, MailRule,
20+ MailSend, NewAttachment, NewSender, NewTask, NewUser, Recipient, Result, SendKind, SendState,
21+ SenderCheck, SenderTest, Session, SigninLink, Store, StoreError, Tag, TaskCreated, Trigger,
22+ User, UserStats, Workspace,
2423 };
24+use super::{reconcile, ReconcileOptions, schema};
2525 use crate::Role;
26-use crate::live::{Change, Topic};
27-use crate::board::{BoardMeta, BoardReads, Column, Moved, Person, TaskRow, Transition};
26+use crate::board::{BoardMeta, BoardReads, Column, Moved, Person, TagChip, TaskRow, Transition};
2827 use crate::detail::{
2928 ActivityEntry, ActivityKind, Comment, DeletionCost, DependencyEdge, DetailReads, FileLine,
3029 SubtaskLine, TaskFacts,
3130 };
31+use crate::live::{Change, Topic};
3232 use time::Date;
3333 use time::format_description::BorrowedFormatItem;
3434 use time::macros::format_description;
3535
36-/// Every migration, in order. There is one: nothing has been released, so a
37-/// schema change is made in `0001_init.sql` and the database recreated. A
38-/// second file is for the day there is data worth keeping.
39-const MIGRATIONS: &[(i64, &str)] = &[
40- (1, include_str!("../../migrations/0001_init.sql")),
41- (2, include_str!("../../migrations/0002_sender_check.sql")),
42-];
43-
4436 /// The board a fresh workspace gets, and its columns. `Done` is the column
4537 /// that stamps a card finished.
4638 const DEFAULT_BOARD_NAME: &str = "Board";
@@ -79,7 +71,10 @@ impl TursoStore {
7971 /// would fill the log with the sound of an idle app.
8072 fn announce(&self, topics: impl IntoIterator<Item = Topic>) {
8173 for topic in topics {
82- let _ = self.live.send(Change { topic, seq: crate::live::next_seq() });
74+ let _ = self.live.send(Change {
75+ topic,
76+ seq: crate::live::next_seq(),
77+ });
8378 }
8479 }
8580
@@ -87,6 +82,10 @@ impl TursoStore {
8782 /// up to date. `:memory:` gives a throwaway database for tests.
8883 pub async fn open(path: &str) -> Result<Self> {
8984 let existed = path != ":memory:" && std::path::Path::new(path).exists();
85+ // Before anything holds this file open: a database of an older shape is
86+ // rebuilt now, while no handle of ours points at the file that the
87+ // rebuild is about to replace.
88+ Self::repair_if_stale(path).await?;
9089 let db = Builder::new_local(path).build().await.map_err(backend)?;
9190 let conn = db.connect().map_err(backend)?;
9291 // Turso is a single-writer engine. Two connections on one Database
@@ -117,9 +116,21 @@ impl TursoStore {
117116 // the reader is told it lagged and resyncs, which is cheaper than the
118117 // memory a larger buffer would cost to avoid saying so.
119118 let (live, _) = tokio::sync::broadcast::channel(256);
120- let store = Self { conn: tokio::sync::Mutex::new(conn), db, key, live };
121- store.migrate().await?;
119+ let store = Self {
120+ conn: tokio::sync::Mutex::new(conn),
121+ db,
122+ key,
123+ live,
124+ };
125+ store.migrate(path).await?;
122126 store.encrypt_plaintext_passwords().await?;
127+ // The file may have been rebuilt from a backup; its permissions and
128+ // any transient WAL/SHM siblings should still be private.
129+ if path != ":memory:" {
130+ restrict_if_present(std::path::Path::new(path))?;
131+ restrict_if_present(&sibling(path, "-wal"))?;
132+ restrict_if_present(&sibling(path, "-shm"))?;
133+ }
123134 Ok(store)
124135 }
125136
@@ -151,107 +162,145 @@ impl TursoStore {
151162 }
152163 for (id, plaintext) in pending {
153164 let sealed = secret::seal(&self.key, &plaintext);
154- conn
155- .execute(
156- "UPDATE workspace SET smtp_password = ?1 WHERE id = ?2",
157- params![sealed, id],
158- )
159- .await
160- .map_err(backend)?;
165+ conn.execute(
166+ "UPDATE workspace SET smtp_password = ?1 WHERE id = ?2",
167+ params![sealed, id],
168+ )
169+ .await
170+ .map_err(backend)?;
161171 }
162172 Ok(())
163173 }
164174
165- async fn migrate(&self) -> Result<()> {
166- self.conn
167- .lock()
168- .await
169- .execute(
170- "CREATE TABLE IF NOT EXISTS schema_version (
171- version INTEGER PRIMARY KEY,
172- applied_at TEXT NOT NULL
173- )",
175+ /// Brings the database to the declared schema.
176+ ///
177+ /// - An empty database is created from `migrations/0001_init.sql`.
178+ /// - A database that already matches the declared schema is left alone.
179+ /// - A stale database is backed up, rebuilt, and re-verified once.
180+ /// If the rebuilt database still does not match, the process stops
181+ /// with the original backed up and untouched.
182+ ///
183+ /// SQLite's DDL is transactional, so a schema that dies halfway leaves
184+ /// nothing behind: a half-created database is a boot that starts over,
185+ /// not a database with a hole in it.
186+ async fn migrate(&self, path: &str) -> Result<()> {
187+ let conn = self.conn.lock().await;
188+ let mut rows = conn
189+ .query(
190+ "SELECT COUNT(*) FROM sqlite_master \
191+ WHERE type = 'table' AND name NOT LIKE 'sqlite_%'",
174192 (),
175193 )
176194 .await
177195 .map_err(backend)?;
196+ let empty = match rows.next().await.map_err(backend)? {
197+ Some(row) => row.get::<i64>(0).map_err(backend)? == 0,
198+ None => true,
199+ };
200+ drop(rows);
178201
179- let applied = self.applied_versions().await?;
180- for (version, sql) in MIGRATIONS {
181- if applied.contains(version) {
182- continue;
202+ if empty {
203+ conn.execute("BEGIN IMMEDIATE", ()).await.map_err(backend)?;
204+ if let Err(e) = conn.execute_batch(super::schema::SCHEMA).await {
205+ let _ = conn.execute("ROLLBACK", ()).await;
206+ return Err(backend(e));
183207 }
184- self.apply(*version, sql).await?;
208+ return conn.execute("COMMIT", ()).await.map_err(backend).map(|_| ());
209+ }
210+
211+ if path == ":memory:" {
212+ // Tests own an in-memory database; its schema is whatever the
213+ // test created, and the open should not try to reconcile it.
214+ return Ok(());
215+ }
216+
217+ // `repair_if_stale` ran before this handle was ever opened, so by now
218+ // the file on disk matches. Saying so here is cheap and turns a
219+ // reordering mistake into a refusal to start rather than a store
220+ // running against a schema the code does not expect.
221+ let have = schema::fingerprint(&conn).await.map_err(backend)?;
222+ let want = schema::declared_fingerprint().await.map_err(backend)?;
223+ if have != want {
224+ return Err(StoreError::Backend(format!(
225+ "database does not match the declared schema and was not repaired; \
226+ do not restart. diff:\n{}",
227+ schema::diff_report(&have, &want)
228+ )));
185229 }
186230 Ok(())
187231 }
188232
189- /// One migration and the row that says it ran, in one transaction.
233+ /// Brings a database of an older shape onto the declared schema, BEFORE
234+ /// any long-lived handle is opened on it.
190235 ///
191- /// A migration is not only a thing that can fail: one that rebuilds a
192- /// table — which is how SQLite drops a CHECK or a foreign key — would
193- /// leave the table gone rather than merely unmigrated if it died between
194- /// the DROP and the RENAME. So the file and its `schema_version` row
195- /// commit together or not at all, and a half-applied migration is a boot
196- /// that starts over rather than a database with a hole in it.
197- ///
198- /// SQLite's DDL is transactional, which is what makes this possible at all.
199- async fn apply(&self, version: i64, sql: &str) -> Result<()> {
200- let conn = self.conn.lock().await;
201- conn
202- .execute("BEGIN IMMEDIATE", ())
203- .await
204- .map_err(backend)?;
205- let written = async {
206- conn.execute_batch(sql).await?;
207- conn
208- .execute(
209- "INSERT INTO schema_version (version, applied_at) VALUES (?1, ?2)",
210- params![
211- version,
212- now_text().map_err(|_| turso::Error::Misuse(
213- "the clock could not be read".to_string()
214- ))?
215- ],
216- )
217- .await?;
218- Ok::<_, turso::Error>(())
236+ /// The order matters and is the whole reason this is not part of
237+ /// `migrate`: `reconcile` swaps a rebuilt file into place, so a
238+ /// `turso::Database` opened beforehand still refers to the file that is
239+ /// now the backup. Reconnecting such a handle reads the old database and
240+ /// makes a successful rebuild look like a failed one.
241+ async fn repair_if_stale(path: &str) -> Result<()> {
242+ if path == ":memory:" || !std::path::Path::new(path).exists() {
243+ return Ok(());
219244 }
220- .await;
221- match written {
222- Ok(()) => conn
223- .execute("COMMIT", ())
245+ let (have, empty) = {
246+ let db = Builder::new_local(path).build().await.map_err(backend)?;
247+ let conn = db.connect().map_err(backend)?;
248+ let mut rows = conn
249+ .query(
250+ "SELECT COUNT(*) FROM sqlite_master \
251+ WHERE type = 'table' AND name NOT LIKE 'sqlite_%'",
252+ (),
253+ )
224254 .await
225- .map_err(backend)
226- .map(|_| ()),
227- Err(e) => {
228- let _ = conn.execute("ROLLBACK", ()).await;
229- Err(backend(e))
230- }
255+ .map_err(backend)?;
256+ let empty = match rows.next().await.map_err(backend)? {
257+ Some(row) => row.get::<i64>(0).map_err(backend)? == 0,
258+ None => true,
259+ };
260+ drop(rows);
261+ let have = if empty {
262+ String::new()
263+ } else {
264+ schema::fingerprint(&conn).await.map_err(backend)?
265+ };
266+ (have, empty)
267+ };
268+ if empty {
269+ return Ok(());
231270 }
232- }
233-
234- async fn applied_versions(&self) -> Result<Vec<i64>> {
235- let conn = self.conn.lock().await;
236- let mut rows = conn
237- .query("SELECT version FROM schema_version", ())
238- .await
239- .map_err(backend)?;
240- let mut out = Vec::new();
241- while let Some(row) = rows.next().await.map_err(backend)? {
242- out.push(row.get::<i64>(0).map_err(backend)?);
271+ let want = schema::declared_fingerprint().await.map_err(backend)?;
272+ if have == want {
273+ return Ok(());
243274 }
244- Ok(out)
245- }
246275
247- /// The schema version the database is actually at.
248- pub async fn schema_version(&self) -> Result<i64> {
249- Ok(self
250- .applied_versions()
251- .await?
252- .into_iter()
253- .max()
254- .unwrap_or(0))
276+ eprintln!(
277+ "database schema differs from the declared schema; rebuilding automatically\n{}",
278+ schema::diff_report(&have, &want)
279+ );
280+ reconcile(
281+ path,
282+ ReconcileOptions {
283+ dry_run: false,
284+ yes: false,
285+ auto: true,
286+ },
287+ )
288+ .await?;
289+
290+ // Check the result once, on a handle opened after the swap. A
291+ // normalisation bug that rebuilt forever would otherwise write a
292+ // full-size backup on every restart until the disk filled.
293+ let db = Builder::new_local(path).build().await.map_err(backend)?;
294+ let conn = db.connect().map_err(backend)?;
295+ let after = schema::fingerprint(&conn).await.map_err(backend)?;
296+ if after != want {
297+ return Err(StoreError::Backend(format!(
298+ "rebuild did not match the declared schema; the original is backed up beside it \
299+ and this is not retried. diff:\n{}",
300+ schema::diff_report(&after, &want)
301+ )));
302+ }
303+ Ok(())
255304 }
256305
257306 /// A connection of its own, for work that opens a transaction.
@@ -376,8 +425,8 @@ const DECISION_COLUMNS: &str = "id, rule_id, event_id, task_id, outcome, detail,
376425
377426 fn decision_from(row: &Row) -> Result<MailDecision> {
378427 let raw = text(row, 4)?;
379- let outcome =
380- MailOutcome::parse(&raw).ok_or_else(|| StoreError::Corrupt(format!("mail outcome {raw:?}")))?;
428+ let outcome = MailOutcome::parse(&raw)
429+ .ok_or_else(|| StoreError::Corrupt(format!("mail outcome {raw:?}")))?;
381430 Ok(MailDecision {
382431 id: text(row, 0)?,
383432 rule_id: text(row, 1)?,
@@ -575,6 +624,7 @@ fn workspace_from(row: &Row) -> Result<Workspace> {
575624 attachment_limit_bytes: row.get::<i64>(3).map_err(backend)?.max(0) as u64,
576625 allowed_file_types,
577626 photo_limit_bytes: row.get::<i64>(5).map_err(backend)?.max(0) as u64,
627+ mail_batch_minutes: row.get::<i64>(19).map_err(backend)?.max(0) as u32,
578628 smtp_host: opt_text(row, 6)?,
579629 smtp_port: row.get::<Option<u32>>(7).map_err(backend)?,
580630 smtp_username: opt_text(row, 8)?,
@@ -609,7 +659,7 @@ const WORKSPACE_COLUMNS: &str = "id, name, created_at, attachment_limit_bytes, \
609659 smtp_from_name, smtp_from_address, \
610660 (smtp_password IS NOT NULL AND smtp_password <> ''), \
611661 smtp_test_at, smtp_test_ms, smtp_test_error, public_url, \
612- smtp_check_at, smtp_check_ms, smtp_check_error";
662+ smtp_check_at, smtp_check_ms, smtp_check_error, mail_batch_minutes";
613663
614664 fn user_from(row: &Row) -> Result<User> {
615665 Ok(User {
@@ -723,7 +773,7 @@ impl Store for TursoStore {
723773 board_id.clone(),
724774 workspace_id.clone(),
725775 DEFAULT_BOARD_NAME,
726- now
776+ now.clone(),
727777 ],
728778 )
729779 .await?;
@@ -741,6 +791,15 @@ impl Store for TursoStore {
741791 )
742792 .await?;
743793 }
794+ // Every task must wear a tag, so the board comes with the one
795+ // that catches whatever loses its own — English, like the
796+ // columns beside it.
797+ tx.execute(
798+ "INSERT INTO tag (id, board_id, name, position, is_default, created_at) \
799+ VALUES (?1, ?2, 'General', 0, 1, ?3)",
800+ params![Ulid::new().to_string(), board_id.clone(), now.clone()],
801+ )
802+ .await?;
744803 Ok::<_, turso::Error>(())
745804 }
746805 .await;
@@ -803,26 +862,28 @@ impl Store for TursoStore {
803862 // Sealed here, not by the caller — the `Store` trait keeps passing
804863 // plaintext so nothing outside this file needs to know a cipher
805864 // exists. See `crate::store::secret`.
806- let sealed_password = sender.password.as_deref().map(|p| secret::seal(&self.key, p));
807- conn
808- .execute(
809- "UPDATE workspace SET smtp_host = ?1, smtp_port = ?2, smtp_username = ?3, \
865+ let sealed_password = sender
866+ .password
867+ .as_deref()
868+ .map(|p| secret::seal(&self.key, p));
869+ conn.execute(
870+ "UPDATE workspace SET smtp_host = ?1, smtp_port = ?2, smtp_username = ?3, \
810871 smtp_password = COALESCE(?4, smtp_password), smtp_from_name = ?5, \
811872 smtp_from_address = ?6, smtp_test_at = NULL, smtp_test_ms = NULL, \
812873 smtp_test_error = NULL, smtp_check_at = NULL, smtp_check_ms = NULL, \
813874 smtp_check_error = NULL WHERE id = ?7",
814- params![
815- sender.host,
816- sender.port as i64,
817- sender.username,
818- sealed_password,
819- sender.from_name,
820- sender.from_address,
821- workspace_id
822- ],
823- )
824- .await
825- .map_err(backend)?;
875+ params![
876+ sender.host,
877+ sender.port as i64,
878+ sender.username,
879+ sealed_password,
880+ sender.from_name,
881+ sender.from_address,
882+ workspace_id
883+ ],
884+ )
885+ .await
886+ .map_err(backend)?;
826887 drop(conn);
827888 self.announce([Topic::Settings]);
828889 Ok(())
@@ -830,19 +891,18 @@ impl Store for TursoStore {
830891
831892 async fn record_sender_check(&self, workspace_id: &str, check: SenderCheck) -> Result<()> {
832893 let conn = self.conn.lock().await;
833- conn
834- .execute(
835- "UPDATE workspace SET smtp_check_at = ?1, smtp_check_ms = ?2, \
894+ conn.execute(
895+ "UPDATE workspace SET smtp_check_at = ?1, smtp_check_ms = ?2, \
836896 smtp_check_error = ?3 WHERE id = ?4",
837- params![
838- stamp(check.at)?,
839- check.took_ms as i64,
840- check.error,
841- workspace_id
842- ],
843- )
844- .await
845- .map_err(backend)?;
897+ params![
898+ stamp(check.at)?,
899+ check.took_ms as i64,
900+ check.error,
901+ workspace_id
902+ ],
903+ )
904+ .await
905+ .map_err(backend)?;
846906 drop(conn);
847907 self.announce([Topic::Settings]);
848908 Ok(())
@@ -850,19 +910,18 @@ impl Store for TursoStore {
850910
851911 async fn record_sender_test(&self, workspace_id: &str, test: SenderTest) -> Result<()> {
852912 let conn = self.conn.lock().await;
853- conn
854- .execute(
855- "UPDATE workspace SET smtp_test_at = ?1, smtp_test_ms = ?2, \
913+ conn.execute(
914+ "UPDATE workspace SET smtp_test_at = ?1, smtp_test_ms = ?2, \
856915 smtp_test_error = ?3 WHERE id = ?4",
857- params![
858- stamp(test.at)?,
859- test.took_ms as i64,
860- test.error,
861- workspace_id
862- ],
863- )
864- .await
865- .map_err(backend)?;
916+ params![
917+ stamp(test.at)?,
918+ test.took_ms as i64,
919+ test.error,
920+ workspace_id
921+ ],
922+ )
923+ .await
924+ .map_err(backend)?;
866925 drop(conn);
867926 self.announce([Topic::Settings]);
868927 Ok(())
@@ -891,13 +950,12 @@ impl Store for TursoStore {
891950
892951 async fn set_public_url(&self, workspace_id: &str, public_url: Option<&str>) -> Result<()> {
893952 let conn = self.conn.lock().await;
894- conn
895- .execute(
896- "UPDATE workspace SET public_url = ?1 WHERE id = ?2",
897- params![public_url, workspace_id],
898- )
899- .await
900- .map_err(backend)?;
953+ conn.execute(
954+ "UPDATE workspace SET public_url = ?1 WHERE id = ?2",
955+ params![public_url, workspace_id],
956+ )
957+ .await
958+ .map_err(backend)?;
901959 drop(conn);
902960 self.announce([Topic::Settings]);
903961 Ok(())
@@ -909,23 +967,24 @@ impl Store for TursoStore {
909967 attachment_limit_bytes: u64,
910968 photo_limit_bytes: u64,
911969 allowed_file_types: &[String],
970+ mail_batch_minutes: u32,
912971 ) -> Result<()> {
913972 let conn = self.conn.lock().await;
914973 let types = serde_json::to_string(allowed_file_types)
915974 .map_err(|e| StoreError::Corrupt(format!("allowed_file_types: {e}")))?;
916- conn
917- .execute(
918- "UPDATE workspace SET attachment_limit_bytes = ?1, photo_limit_bytes = ?2, \
919- allowed_file_types = ?3 WHERE id = ?4",
920- params![
921- attachment_limit_bytes as i64,
922- photo_limit_bytes as i64,
923- types,
924- workspace_id
925- ],
926- )
927- .await
928- .map_err(backend)?;
975+ conn.execute(
976+ "UPDATE workspace SET attachment_limit_bytes = ?1, photo_limit_bytes = ?2, \
977+ allowed_file_types = ?3, mail_batch_minutes = ?5 WHERE id = ?4",
978+ params![
979+ attachment_limit_bytes as i64,
980+ photo_limit_bytes as i64,
981+ types,
982+ workspace_id,
983+ i64::from(mail_batch_minutes)
984+ ],
985+ )
986+ .await
987+ .map_err(backend)?;
929988 drop(conn);
930989 self.announce([Topic::Settings]);
931990 Ok(())
@@ -1018,6 +1077,46 @@ impl Store for TursoStore {
10181077 }
10191078 }
10201079
1080+ async fn user_stats(&self, user_id: &str) -> Result<UserStats> {
1081+ // One row of four scalars: a profile reads its whole summary in a
1082+ // single trip. `deleted_at` is excluded everywhere — a task off the
1083+ // board is off the person's page as well.
1084+ let row = self
1085+ .one_row(
1086+ "SELECT \
1087+ (SELECT COUNT(*) FROM task_assignee a \
1088+ JOIN task t ON t.id = a.task_id \
1089+ JOIN board_column c ON c.id = t.column_id \
1090+ WHERE a.user_id = ?1 AND t.deleted_at IS NULL AND c.is_done = 0), \
1091+ (SELECT COUNT(*) FROM task_assignee a \
1092+ JOIN task t ON t.id = a.task_id \
1093+ JOIN board_column c ON c.id = t.column_id \
1094+ WHERE a.user_id = ?1 AND t.deleted_at IS NULL AND c.is_done = 1), \
1095+ (SELECT COUNT(*) FROM task WHERE created_by = ?1 AND deleted_at IS NULL), \
1096+ (SELECT COUNT(*) FROM comment m JOIN task t ON t.id = m.task_id \
1097+ WHERE m.author_id = ?1 AND t.deleted_at IS NULL)",
1098+ params![user_id],
1099+ )
1100+ .await?;
1101+ let Some(row) = row else {
1102+ return Ok(UserStats {
1103+ assigned_open: 0,
1104+ assigned_done: 0,
1105+ created: 0,
1106+ comments: 0,
1107+ });
1108+ };
1109+ let at = |i: usize| -> Result<u32> {
1110+ row.get::<i64>(i).map_err(backend).map(|n| n.max(0) as u32)
1111+ };
1112+ Ok(UserStats {
1113+ assigned_open: at(0)?,
1114+ assigned_done: at(1)?,
1115+ created: at(2)?,
1116+ comments: at(3)?,
1117+ })
1118+ }
1119+
10211120 async fn set_password_hash(&self, user_id: &str, hash: &str) -> Result<()> {
10221121 let conn = self.conn.lock().await;
10231122 let n = conn
@@ -1125,7 +1224,13 @@ impl Store for TursoStore {
11251224 params![email, user_id],
11261225 )
11271226 .await
1128- .map_err(|e| if is_constraint_violation(&e) { StoreError::Conflict("account") } else { backend(e) })?;
1227+ .map_err(|e| {
1228+ if is_constraint_violation(&e) {
1229+ StoreError::Conflict("account")
1230+ } else {
1231+ backend(e)
1232+ }
1233+ })?;
11291234 if n == 0 {
11301235 Err(StoreError::NotFound)
11311236 } else {
@@ -1355,13 +1460,12 @@ impl Store for TursoStore {
13551460 // sign-in — traffic in exchange for a screen that would look identical.
13561461 async fn record_auth_attempt(&self, bucket: &str, at: OffsetDateTime) -> Result<()> {
13571462 let conn = self.conn.lock().await;
1358- conn
1359- .execute(
1360- "INSERT INTO auth_attempt (id, bucket, attempted_at) VALUES (?1, ?2, ?3)",
1361- params![Ulid::new().to_string(), bucket, stamp(at)?],
1362- )
1363- .await
1364- .map_err(backend)?;
1463+ conn.execute(
1464+ "INSERT INTO auth_attempt (id, bucket, attempted_at) VALUES (?1, ?2, ?3)",
1465+ params![Ulid::new().to_string(), bucket, stamp(at)?],
1466+ )
1467+ .await
1468+ .map_err(backend)?;
13651469 Ok(())
13661470 }
13671471
@@ -1382,25 +1486,23 @@ impl Store for TursoStore {
13821486
13831487 async fn clear_auth_attempts(&self, bucket: &str) -> Result<()> {
13841488 let conn = self.conn.lock().await;
1385- conn
1386- .execute(
1387- "DELETE FROM auth_attempt WHERE bucket = ?1",
1388- params![bucket],
1389- )
1390- .await
1391- .map_err(backend)?;
1489+ conn.execute(
1490+ "DELETE FROM auth_attempt WHERE bucket = ?1",
1491+ params![bucket],
1492+ )
1493+ .await
1494+ .map_err(backend)?;
13921495 Ok(())
13931496 }
13941497
13951498 async fn prune_auth_attempts(&self, before: OffsetDateTime) -> Result<u64> {
13961499 let conn = self.conn.lock().await;
1397- conn
1398- .execute(
1399- "DELETE FROM auth_attempt WHERE attempted_at < ?1",
1400- params![stamp(before)?],
1401- )
1402- .await
1403- .map_err(backend)
1500+ conn.execute(
1501+ "DELETE FROM auth_attempt WHERE attempted_at < ?1",
1502+ params![stamp(before)?],
1503+ )
1504+ .await
1505+ .map_err(backend)
14041506 }
14051507
14061508 // -- board -------------------------------------------------------------
@@ -1414,14 +1516,13 @@ impl Store for TursoStore {
14141516 ) -> Result<Column> {
14151517 let conn = self.conn.lock().await;
14161518 let id = Ulid::new().to_string();
1417- conn
1418- .execute(
1419- "INSERT INTO board_column (id, board_id, name, position, is_done) \
1519+ conn.execute(
1520+ "INSERT INTO board_column (id, board_id, name, position, is_done) \
14201521 VALUES (?1, ?2, ?3, ?4, ?5)",
1421- params![id.clone(), board_id, name, position, i64::from(is_done)],
1422- )
1423- .await
1424- .map_err(backend)?;
1522+ params![id.clone(), board_id, name, position, i64::from(is_done)],
1523+ )
1524+ .await
1525+ .map_err(backend)?;
14251526 drop(conn);
14261527 self.announce([Topic::Board]);
14271528 Ok(Column {
@@ -1500,6 +1601,20 @@ impl Store for TursoStore {
15001601 drop(rows);
15011602 let position = last + 1.0;
15021603
1604+ // A task always wears a tag, so one is chosen here when nobody
1605+ // named one: the board's default. The NOT NULL on `task.tag_id`
1606+ // makes choosing it the write's job, not an afterthought.
1607+ let mut rows = tx
1608+ .query(
1609+ "SELECT id FROM tag WHERE board_id = ?1 AND is_default = 1",
1610+ params![new.board_id],
1611+ )
1612+ .await?;
1613+ let default_tag = match rows.next().await? {
1614+ Some(row) => row.get::<String>(0)?,
1615+ None => return Ok(Err(StoreError::NotFound)),
1616+ };
1617+ drop(rows);
15031618 // The key's tail is the end of this task's own id (a ULID —
15041619 // Crockford-uppercase already, and the last chars are its random
15051620 // bits) rather than a per-board counter: a counter leaves visible
@@ -1512,8 +1627,8 @@ impl Store for TursoStore {
15121627 match tx
15131628 .execute(
15141629 "INSERT INTO task (id, board_id, parent_id, task_key, title, description, \
1515- column_id, deadline, position, created_by, created_at, updated_at) \
1516- VALUES (?1, ?2, ?11, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?10)",
1630+ column_id, tag_id, deadline, position, created_by, created_at, updated_at) \
1631+ VALUES (?1, ?2, ?11, ?3, ?4, ?5, ?6, ?12, ?7, ?8, ?9, ?10, ?10)",
15171632 params![
15181633 id.clone(),
15191634 new.board_id,
@@ -1525,7 +1640,8 @@ impl Store for TursoStore {
15251640 position,
15261641 new.created_by,
15271642 now.clone(),
1528- new.parent_id
1643+ new.parent_id,
1644+ default_tag.clone()
15291645 ],
15301646 )
15311647 .await
@@ -1539,8 +1655,8 @@ impl Store for TursoStore {
15391655 }
15401656 };
15411657 tx.execute(
1542- "INSERT INTO activity (id, task_id, actor_id, kind, detail, created_at) \
1543- VALUES (?1, ?2, ?3, ?4, '', ?5)",
1658+ "INSERT INTO activity (id, task_id, actor_id, subject_id, kind, detail, created_at) \
1659+ VALUES (?1, ?2, ?3, NULL, ?4, '', ?5)",
15441660 params![
15451661 activity_id.clone(),
15461662 id.clone(),
@@ -1593,6 +1709,7 @@ impl Store for TursoStore {
15931709 position,
15941710 done_at: None,
15951711 parent_id: new.parent_id.map(str::to_string),
1712+ tag: None,
15961713 },
15971714 activity_id,
15981715 transition: Transition {
@@ -1717,6 +1834,7 @@ impl Store for TursoStore {
17171834 position: row.get::<f64>(5).unwrap_or(0.0),
17181835 done_at: opt_stamp(&row, 6)?,
17191836 parent_id: Some(parent_id.to_string()),
1837+ tag: None,
17201838 });
17211839 }
17221840 Ok(out)
@@ -1924,8 +2042,8 @@ impl Store for TursoStore {
19242042 )
19252043 .await?;
19262044 tx.execute(
1927- "INSERT INTO activity (id, task_id, actor_id, kind, detail, created_at) \
1928- VALUES (?1, ?2, ?3, ?4, '', ?5)",
2045+ "INSERT INTO activity (id, task_id, actor_id, subject_id, kind, detail, created_at) \
2046+ VALUES (?1, ?2, ?3, NULL, ?4, '', ?5)",
19292047 params![
19302048 activity_id.clone(),
19312049 task_id,
@@ -1956,25 +2074,24 @@ impl Store for TursoStore {
19562074 let conn = self.conn.lock().await;
19572075 let id = Ulid::new().to_string();
19582076 let size = new.bytes.len() as i64;
1959- conn
1960- .execute(
1961- "INSERT INTO attachment (id, task_id, comment_id, file_name, mime_type, \
2077+ conn.execute(
2078+ "INSERT INTO attachment (id, task_id, comment_id, file_name, mime_type, \
19622079 size_bytes, bytes, uploaded_by, created_at) \
19632080 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
1964- params![
1965- id.clone(),
1966- new.task_id,
1967- new.comment_id,
1968- new.file_name,
1969- new.mime_type,
1970- size,
1971- new.bytes,
1972- new.uploaded_by,
1973- stamp(new.at)?
1974- ],
1975- )
1976- .await
1977- .map_err(backend)?;
2081+ params![
2082+ id.clone(),
2083+ new.task_id,
2084+ new.comment_id,
2085+ new.file_name,
2086+ new.mime_type,
2087+ size,
2088+ new.bytes,
2089+ new.uploaded_by,
2090+ stamp(new.at)?
2091+ ],
2092+ )
2093+ .await
2094+ .map_err(backend)?;
19782095 drop(conn);
19792096 self.announce([Topic::Task(new.task_id.to_string())]);
19802097 Ok(id)
@@ -2109,8 +2226,8 @@ impl Store for TursoStore {
21092226 for (kind, detail) in lines {
21102227 let id = Ulid::new().to_string();
21112228 tx.execute(
2112- "INSERT INTO activity (id, task_id, actor_id, kind, detail, created_at) \
2113- VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
2229+ "INSERT INTO activity (id, task_id, actor_id, subject_id, kind, detail, created_at) \
2230+ VALUES (?1, ?2, ?3, NULL, ?4, ?5, ?6)",
21142231 params![id.clone(), task_id, actor_id, kind, detail, stamp.clone()],
21152232 )
21162233 .await?;
@@ -2289,8 +2406,8 @@ impl Store for TursoStore {
22892406 .await?;
22902407
22912408 tx.execute(
2292- "INSERT INTO activity (id, task_id, actor_id, kind, detail, created_at) \
2293- VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
2409+ "INSERT INTO activity (id, task_id, actor_id, subject_id, kind, detail, created_at) \
2410+ VALUES (?1, ?2, ?3, NULL, ?4, ?5, ?6)",
22942411 params![
22952412 Ulid::new().to_string(),
22962413 task_id,
@@ -2413,8 +2530,8 @@ impl Store for TursoStore {
24132530 .await?;
24142531 let deleted_activity_id = Ulid::new().to_string();
24152532 tx.execute(
2416- "INSERT INTO activity (id, task_id, actor_id, kind, detail, created_at) \
2417- VALUES (?1, ?2, ?3, ?4, '', ?5)",
2533+ "INSERT INTO activity (id, task_id, actor_id, subject_id, kind, detail, created_at) \
2534+ VALUES (?1, ?2, ?3, NULL, ?4, '', ?5)",
24182535 params![
24192536 deleted_activity_id.clone(),
24202537 task_id,
@@ -2446,8 +2563,8 @@ impl Store for TursoStore {
24462563 continue;
24472564 }
24482565 tx.execute(
2449- "INSERT INTO activity (id, task_id, actor_id, kind, detail, created_at) \
2450- VALUES (?1, ?2, NULL, ?3, ?4, ?5)",
2566+ "INSERT INTO activity (id, task_id, actor_id, subject_id, kind, detail, created_at) \
2567+ VALUES (?1, ?2, NULL, NULL, ?3, ?4, ?5)",
24512568 params![
24522569 Ulid::new().to_string(),
24532570 blocked.clone(),
@@ -2599,27 +2716,28 @@ impl Store for TursoStore {
25992716 &self,
26002717 task_id: &str,
26012718 actor_id: Option<&str>,
2719+ subject_id: Option<&str>,
26022720 kind: &ActivityKind,
26032721 detail: &str,
26042722 at: OffsetDateTime,
26052723 ) -> Result<String> {
26062724 let conn = self.conn.lock().await;
26072725 let id = Ulid::new().to_string();
2608- conn
2609- .execute(
2610- "INSERT INTO activity (id, task_id, actor_id, kind, detail, created_at) \
2611- VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
2612- params![
2613- id.clone(),
2614- task_id,
2615- actor_id,
2616- kind.as_str(),
2617- detail,
2618- stamp(at)?
2619- ],
2620- )
2621- .await
2622- .map_err(backend)?;
2726+ conn.execute(
2727+ "INSERT INTO activity (id, task_id, actor_id, subject_id, kind, detail, created_at) \
2728+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
2729+ params![
2730+ id.clone(),
2731+ task_id,
2732+ actor_id,
2733+ subject_id,
2734+ kind.as_str(),
2735+ detail,
2736+ stamp(at)?
2737+ ],
2738+ )
2739+ .await
2740+ .map_err(backend)?;
26232741 drop(conn);
26242742 // Task-scoped: the task's own trail and the workspace feed both grew.
26252743 self.announce([Topic::Activity, Topic::Task(task_id.to_string())]);
@@ -2635,14 +2753,13 @@ impl Store for TursoStore {
26352753 ) -> Result<String> {
26362754 let conn = self.conn.lock().await;
26372755 let id = Ulid::new().to_string();
2638- conn
2639- .execute(
2640- "INSERT INTO activity (id, task_id, actor_id, kind, detail, created_at) \
2641- VALUES (?1, NULL, ?2, ?3, ?4, ?5)",
2642- params![id.clone(), actor_id, kind.as_str(), detail, stamp(at)?],
2643- )
2644- .await
2645- .map_err(backend)?;
2756+ conn.execute(
2757+ "INSERT INTO activity (id, task_id, actor_id, subject_id, kind, detail, created_at) \
2758+ VALUES (?1, NULL, ?2, NULL, ?3, ?4, ?5)",
2759+ params![id.clone(), actor_id, kind.as_str(), detail, stamp(at)?],
2760+ )
2761+ .await
2762+ .map_err(backend)?;
26462763 drop(conn);
26472764 // Workspace-wide, belonging to no task — the feed only.
26482765 self.announce([Topic::Activity]);
@@ -2696,10 +2813,7 @@ impl Store for TursoStore {
26962813 let sql = format!(
26972814 "SELECT {RULE_COLUMNS} FROM mail_rule WHERE board_id = ?1 ORDER BY created_at, rowid"
26982815 );
2699- let mut rows = conn
2700- .query(&sql, params![board_id])
2701- .await
2702- .map_err(backend)?;
2816+ let mut rows = conn.query(&sql, params![board_id]).await.map_err(backend)?;
27032817 let mut out = Vec::new();
27042818 while let Some(row) = rows.next().await.map_err(backend)? {
27052819 out.push(rule_from(&row)?);
@@ -2799,7 +2913,7 @@ impl Store for TursoStore {
27992913 match self
28002914 .one_row(
28012915 "SELECT activity.id, activity.task_id, task.board_id, activity.kind, \
2802- activity.actor_id, activity.detail, activity.created_at \
2916+ activity.actor_id, activity.subject_id, activity.detail, activity.created_at \
28032917 FROM activity JOIN task ON task.id = activity.task_id \
28042918 WHERE activity.id = ?1",
28052919 params![event_id],
@@ -2812,8 +2926,9 @@ impl Store for TursoStore {
28122926 board_id: text(&row, 2)?,
28132927 kind: ActivityKind::parse(&text(&row, 3)?),
28142928 actor_id: opt_text(&row, 4)?.unwrap_or_default(),
2815- detail: text(&row, 5)?,
2816- at: parse_stamp(&text(&row, 6)?)?,
2929+ subject_id: opt_text(&row, 5)?,
2930+ detail: text(&row, 6)?,
2931+ at: parse_stamp(&text(&row, 7)?)?,
28172932 }))),
28182933 None => Ok(None),
28192934 }
@@ -3187,14 +3302,13 @@ impl Store for TursoStore {
31873302
31883303 async fn requeue_send(&self, send_id: &str, at: OffsetDateTime) -> Result<()> {
31893304 let conn = self.conn.lock().await;
3190- conn
3191- .execute(
3192- "UPDATE mail_send SET state = 'pending', next_attempt_at = ?1 \
3305+ conn.execute(
3306+ "UPDATE mail_send SET state = 'pending', next_attempt_at = ?1 \
31933307 WHERE id = ?2 AND state IN ('failed', 'abandoned')",
3194- params![stamp(at)?, send_id],
3195- )
3196- .await
3197- .map_err(backend)?;
3308+ params![stamp(at)?, send_id],
3309+ )
3310+ .await
3311+ .map_err(backend)?;
31983312 drop(conn);
31993313 self.announce([Topic::Queue]);
32003314 Ok(())
@@ -3213,16 +3327,23 @@ impl Store for TursoStore {
32133327 ) -> Result<()> {
32143328 let conn = self.conn.lock().await;
32153329 let id = Ulid::new().to_string();
3216- conn
3217- .execute(
3218- "INSERT INTO mail_decision (id, rule_id, event_id, task_id, outcome, detail, \
3330+ conn.execute(
3331+ "INSERT INTO mail_decision (id, rule_id, event_id, task_id, outcome, detail, \
32193332 created_at) \
32203333 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7) \
32213334 ON CONFLICT (rule_id, event_id, task_id) DO NOTHING",
3222- params![id, rule_id, event_id, task_id, outcome.as_str(), detail, stamp(at)?],
3223- )
3224- .await
3225- .map_err(backend)?;
3335+ params![
3336+ id,
3337+ rule_id,
3338+ event_id,
3339+ task_id,
3340+ outcome.as_str(),
3341+ detail,
3342+ stamp(at)?
3343+ ],
3344+ )
3345+ .await
3346+ .map_err(backend)?;
32263347 drop(conn);
32273348 // A decision is what the rules page's decisions tab renders.
32283349 self.announce([Topic::Rules]);
@@ -3449,7 +3570,9 @@ impl Store for TursoStore {
34493570 FeedPage::Newest => {
34503571 vals.extend(filter_vals);
34513572 vals.push(i64::from(limit).into());
3452- format!("{SELECT} WHERE 1=1{filter_sql} ORDER BY a.created_at {base}, a.id {base} LIMIT ?")
3573+ format!(
3574+ "{SELECT} WHERE 1=1{filter_sql} ORDER BY a.created_at {base}, a.id {base} LIMIT ?"
3575+ )
34533576 }
34543577 FeedPage::Before(cursor) => {
34553578 // Further along in `dir`'s reading order: older when
@@ -3596,6 +3719,51 @@ impl Store for TursoStore {
35963719 recipients_from(&mut rows).await
35973720 }
35983721
3722+ async fn hold_batch(
3723+ &self,
3724+ task_id: &str,
3725+ recipient: &str,
3726+ until: OffsetDateTime,
3727+ cap: Duration,
3728+ ) -> Result<()> {
3729+ let conn = self.conn.lock().await;
3730+ // Read the rows and their birth moments first: the ceiling is per
3731+ // row — the oldest mail in the batch is the one whose patience runs
3732+ // out — and expressing that in SQL over RFC 3339 text would be a
3733+ // date-format trick rather than a calculation.
3734+ let mut rows = conn
3735+ .query(
3736+ "SELECT id, claimed_at FROM mail_send \
3737+ WHERE task_id = ?1 AND recipient = ?2 AND kind = 'rule' \
3738+ AND state = 'pending' AND attempts = 0 \
3739+ AND next_attempt_at IS NOT NULL",
3740+ params![task_id, recipient],
3741+ )
3742+ .await
3743+ .map_err(backend)?;
3744+ let mut held = Vec::new();
3745+ while let Some(row) = rows.next().await.map_err(backend)? {
3746+ let id = text(&row, 0)?;
3747+ let born = parse_stamp(&text(&row, 1)?)?;
3748+ held.push((id, born));
3749+ }
3750+ drop(rows);
3751+ for (id, born) in held {
3752+ let ceiling = born + cap;
3753+ let when = if until > ceiling { ceiling } else { until };
3754+ conn.execute(
3755+ "UPDATE mail_send SET next_attempt_at = ?1 \
3756+ WHERE id = ?2 AND state = 'pending' AND attempts = 0",
3757+ params![stamp(when)?, id],
3758+ )
3759+ .await
3760+ .map_err(backend)?;
3761+ }
3762+ drop(conn);
3763+ self.announce([Topic::Queue]);
3764+ Ok(())
3765+ }
3766+
35993767 async fn recipients_for_task_creator(&self, task_id: &str) -> Result<Vec<Recipient>> {
36003768 let conn = self.conn.lock().await;
36013769 let mut rows = conn
@@ -3609,6 +3777,268 @@ impl Store for TursoStore {
36093777 .map_err(backend)?;
36103778 recipients_from(&mut rows).await
36113779 }
3780+
3781+ async fn recipient(&self, user_id: &str) -> Result<Option<Recipient>> {
3782+ let conn = self.conn.lock().await;
3783+ let mut rows = conn
3784+ .query(
3785+ "SELECT u.id, u.email, u.display_name FROM user u \
3786+ WHERE u.id = ?1 AND u.role <> ?2",
3787+ params![user_id, Role::Viewer.as_str()],
3788+ )
3789+ .await
3790+ .map_err(backend)?;
3791+ Ok(recipients_from(&mut rows).await?.into_iter().next())
3792+ }
3793+
3794+ // -- tags --------------------------------------------------------------
3795+
3796+ async fn tags(&self, board_id: &str) -> Result<Vec<Tag>> {
3797+ let conn = self.conn.lock().await;
3798+ let mut rows = conn
3799+ .query(
3800+ "SELECT id, board_id, name, position, is_default FROM tag WHERE board_id = ?1 \
3801+ ORDER BY position",
3802+ params![board_id],
3803+ )
3804+ .await
3805+ .map_err(backend)?;
3806+ let mut out = Vec::new();
3807+ while let Some(row) = rows.next().await.map_err(backend)? {
3808+ out.push(Tag {
3809+ id: text(&row, 0)?,
3810+ board_id: text(&row, 1)?,
3811+ name: text(&row, 2)?,
3812+ position: row.get::<i64>(3).map_err(backend)?,
3813+ is_default: row.get::<i64>(4).map_err(backend)? != 0,
3814+ });
3815+ }
3816+ Ok(out)
3817+ }
3818+
3819+ async fn create_tag(&self, board_id: &str, name: &str, at: OffsetDateTime) -> Result<Tag> {
3820+ let id = Ulid::new().to_string();
3821+ let now = stamp(at)?;
3822+ let mut conn = self.tx_conn().await?;
3823+ let tx = conn
3824+ .transaction_with_behavior(TransactionBehavior::Immediate)
3825+ .await
3826+ .map_err(backend)?;
3827+
3828+ // A new tag lands at the end of the board's order. The name is the
3829+ // unique index's to police — a pre-read would only widen the race.
3830+ let written = async {
3831+ let mut rows = tx
3832+ .query(
3833+ "SELECT COALESCE(MAX(position), 0) FROM tag WHERE board_id = ?1",
3834+ params![board_id],
3835+ )
3836+ .await?;
3837+ let position = match rows.next().await? {
3838+ Some(row) => row.get::<i64>(0).unwrap_or(0) + 1,
3839+ None => 1,
3840+ };
3841+ drop(rows);
3842+ tx.execute(
3843+ "INSERT INTO tag (id, board_id, name, position, is_default, created_at) \
3844+ VALUES (?1, ?2, ?3, ?4, 0, ?5)",
3845+ params![id.clone(), board_id, name, position, now],
3846+ )
3847+ .await?;
3848+ Ok::<_, turso::Error>(position)
3849+ }
3850+ .await;
3851+
3852+ let position = match written {
3853+ Ok(position) => position,
3854+ Err(e) => {
3855+ let _ = tx.rollback().await;
3856+ return Err(if is_constraint_violation(&e) {
3857+ StoreError::Conflict("tag")
3858+ } else {
3859+ backend(e)
3860+ });
3861+ }
3862+ };
3863+ tx.commit().await.map_err(backend)?;
3864+
3865+ self.announce([Topic::Board, Topic::Tags]);
3866+ Ok(Tag {
3867+ id,
3868+ board_id: board_id.to_string(),
3869+ name: name.to_string(),
3870+ position,
3871+ is_default: false,
3872+ })
3873+ }
3874+
3875+ async fn rename_tag(&self, tag_id: &str, name: &str) -> Result<()> {
3876+ let conn = self.conn.lock().await;
3877+ let n = conn
3878+ .execute(
3879+ "UPDATE tag SET name = ?1 WHERE id = ?2",
3880+ params![name, tag_id],
3881+ )
3882+ .await
3883+ .map_err(|e| {
3884+ if is_constraint_violation(&e) {
3885+ StoreError::Conflict("tag")
3886+ } else {
3887+ backend(e)
3888+ }
3889+ })?;
3890+ if n == 0 {
3891+ return Err(StoreError::NotFound);
3892+ }
3893+ drop(conn);
3894+ self.announce([Topic::Board, Topic::Tags]);
3895+ Ok(())
3896+ }
3897+
3898+ async fn delete_tag(&self, tag_id: &str) -> Result<()> {
3899+ let mut conn = self.tx_conn().await?;
3900+ let tx = conn
3901+ .transaction_with_behavior(TransactionBehavior::Immediate)
3902+ .await
3903+ .map_err(backend)?;
3904+ // The default is the board's fallback, not a project anyone can
3905+ // retire: deleting it would leave its board's tasks nowhere to go.
3906+ // Any other tag's tasks move to that default, in the one write set:
3907+ // no task is ever seen pointing at a project that is not there.
3908+ let deleted = async {
3909+ let mut rows = tx
3910+ .query(
3911+ "SELECT board_id, is_default FROM tag WHERE id = ?1",
3912+ params![tag_id],
3913+ )
3914+ .await?;
3915+ let Some(row) = rows.next().await? else {
3916+ return Ok::<_, turso::Error>(Err(StoreError::NotFound));
3917+ };
3918+ let board_id: String = row.get(0)?;
3919+ let is_default: i64 = row.get(1)?;
3920+ drop(rows);
3921+ if is_default != 0 {
3922+ return Ok(Err(StoreError::Conflict("default_tag")));
3923+ }
3924+ tx.execute(
3925+ "UPDATE task SET tag_id = \
3926+ (SELECT id FROM tag WHERE board_id = ?1 AND is_default = 1) \
3927+ WHERE tag_id = ?2",
3928+ params![board_id, tag_id],
3929+ )
3930+ .await?;
3931+ tx.execute("DELETE FROM tag WHERE id = ?1", params![tag_id])
3932+ .await?;
3933+ Ok(Ok(()))
3934+ }
3935+ .await;
3936+ match deleted {
3937+ Ok(Ok(())) => {}
3938+ Ok(Err(refused)) => {
3939+ let _ = tx.rollback().await;
3940+ return Err(refused);
3941+ }
3942+ Err(e) => {
3943+ let _ = tx.rollback().await;
3944+ return Err(backend(e));
3945+ }
3946+ }
3947+ tx.commit().await.map_err(backend)?;
3948+ self.announce([Topic::Board, Topic::Tags]);
3949+ Ok(())
3950+ }
3951+
3952+ async fn move_tag(&self, tag_id: &str, up: bool) -> Result<()> {
3953+ let mut conn = self.tx_conn().await?;
3954+ let tx = conn
3955+ .transaction_with_behavior(TransactionBehavior::Immediate)
3956+ .await
3957+ .map_err(backend)?;
3958+ let written = async {
3959+ let mut rows = tx
3960+ .query(
3961+ "SELECT board_id, position FROM tag WHERE id = ?1",
3962+ params![tag_id],
3963+ )
3964+ .await?;
3965+ let Some(row) = rows.next().await? else {
3966+ return Ok::<_, turso::Error>(Err(StoreError::NotFound));
3967+ };
3968+ let board_id: String = row.get(0)?;
3969+ let position: i64 = row.get(1)?;
3970+ drop(rows);
3971+ let other = if up { position - 1 } else { position + 1 };
3972+ let mut rows = tx
3973+ .query(
3974+ "SELECT id FROM tag WHERE board_id = ?1 AND position = ?2",
3975+ params![board_id, other],
3976+ )
3977+ .await?;
3978+ let Some(neighbour) = rows.next().await? else {
3979+ // Already at that end of the order: nothing to swap, and that
3980+ // is not an error.
3981+ return Ok(Ok(()));
3982+ };
3983+ let neighbour_id: String = neighbour.get(0)?;
3984+ drop(rows);
3985+ tx.execute(
3986+ "UPDATE tag SET position = ?1 WHERE id = ?2",
3987+ params![position, neighbour_id],
3988+ )
3989+ .await?;
3990+ tx.execute(
3991+ "UPDATE tag SET position = ?1 WHERE id = ?2",
3992+ params![other, tag_id],
3993+ )
3994+ .await?;
3995+ Ok(Ok(()))
3996+ }
3997+ .await;
3998+ match written {
3999+ Ok(Ok(())) => {}
4000+ Ok(Err(refused)) => {
4001+ let _ = tx.rollback().await;
4002+ return Err(refused);
4003+ }
4004+ Err(e) => {
4005+ let _ = tx.rollback().await;
4006+ return Err(backend(e));
4007+ }
4008+ }
4009+ tx.commit().await.map_err(backend)?;
4010+ self.announce([Topic::Board, Topic::Tags]);
4011+ Ok(())
4012+ }
4013+
4014+ async fn set_task_tag(&self, task_id: &str, tag_id: &str) -> Result<()> {
4015+ // A tag not of this task's board is NotFound, not refused: the
4016+ // asker named a thing that is not one of this board's projects.
4017+ let known = self
4018+ .one_row(
4019+ "SELECT g.id FROM tag g JOIN task t ON t.board_id = g.board_id \
4020+ WHERE g.id = ?1 AND t.id = ?2 AND t.deleted_at IS NULL",
4021+ params![tag_id, task_id],
4022+ )
4023+ .await?;
4024+ if known.is_none() {
4025+ return Err(StoreError::NotFound);
4026+ }
4027+ let conn = self.conn.lock().await;
4028+ let n = conn
4029+ .execute(
4030+ "UPDATE task SET tag_id = ?1 WHERE id = ?2 AND deleted_at IS NULL",
4031+ params![tag_id, task_id],
4032+ )
4033+ .await
4034+ .map_err(backend)?;
4035+ if n == 0 {
4036+ return Err(StoreError::NotFound);
4037+ }
4038+ drop(conn);
4039+ self.announce([Topic::Board, Topic::Task(task_id.to_string()), Topic::Tags]);
4040+ Ok(())
4041+ }
36124042 }
36134043
36144044 #[async_trait]
@@ -3617,8 +4047,10 @@ impl DetailReads for TursoStore {
36174047 let row = self
36184048 .one_row(
36194049 "SELECT t.id, t.task_key, t.title, t.column_id, t.deadline, t.position, \
3620- t.done_at, t.description, t.board_id, b.workspace_id, t.parent_id \
3621- FROM task t JOIN board b ON b.id = t.board_id \
4050+ t.done_at, t.description, t.board_id, b.workspace_id, t.parent_id, \
4051+ t.tag_id, g.name \
4052+ FROM task t LEFT JOIN tag g ON g.id = t.tag_id \
4053+ JOIN board b ON b.id = t.board_id \
36224054 WHERE t.id = ?1 AND t.deleted_at IS NULL",
36234055 params![task_id],
36244056 )
@@ -3634,6 +4066,13 @@ impl DetailReads for TursoStore {
36344066 position: row.get::<f64>(5).map_err(backend)?,
36354067 done_at: opt_stamp(&row, 6)?,
36364068 parent_id: opt_text(&row, 10)?,
4069+ tag: match opt_text(&row, 11)? {
4070+ Some(id) => Some(TagChip {
4071+ id,
4072+ name: text(&row, 12)?,
4073+ }),
4074+ None => None,
4075+ },
36374076 },
36384077 description: text(&row, 7)?,
36394078 board_id: text(&row, 8)?,
@@ -3922,8 +4361,10 @@ impl BoardReads for TursoStore {
39224361 let conn = self.conn.lock().await;
39234362 let mut rows = conn
39244363 .query(
3925- "SELECT id, task_key, title, column_id, deadline, position, done_at, parent_id \
3926- FROM task WHERE board_id = ?1 AND deleted_at IS NULL",
4364+ "SELECT t.id, t.task_key, t.title, t.column_id, t.deadline, t.position, \
4365+ t.done_at, t.parent_id, t.tag_id, g.name \
4366+ FROM task t LEFT JOIN tag g ON g.id = t.tag_id \
4367+ WHERE t.board_id = ?1 AND t.deleted_at IS NULL",
39274368 params![board_id],
39284369 )
39294370 .await
@@ -3939,6 +4380,13 @@ impl BoardReads for TursoStore {
39394380 position: row.get::<f64>(5).map_err(backend)?,
39404381 done_at: opt_stamp(&row, 6)?,
39414382 parent_id: opt_text(&row, 7)?,
4383+ tag: match opt_text(&row, 8)? {
4384+ Some(id) => Some(TagChip {
4385+ id,
4386+ name: text(&row, 9)?,
4387+ }),
4388+ None => None,
4389+ },
39424390 });
39434391 }
39444392 Ok(out)
@@ -4209,47 +4657,3 @@ mod probe {
42094657 let _ = std::fs::remove_dir_all(&dir);
42104658 }
42114659 }
4212-
4213-#[cfg(test)]
4214-mod migration {
4215- use super::*;
4216-
4217- /// A migration that dies halfway leaves nothing behind — not a table it
4218- /// created, and not a version row saying it ran. 0005 drops `mail_send`
4219- /// before it renames the rebuilt table into place, so a migration that can
4220- /// only half-apply is a migration that can lose the mail ledger.
4221- #[tokio::test]
4222- async fn a_migration_that_fails_partway_leaves_nothing_behind() {
4223- let dir = std::env::temp_dir().join(format!("izlek-migration-{}", Ulid::new()));
4224- std::fs::create_dir_all(&dir).unwrap();
4225- let store = TursoStore::open(dir.join("izlek.db").to_str().unwrap())
4226- .await
4227- .unwrap();
4228- let before = store.schema_version().await.unwrap();
4229-
4230- let broken = "CREATE TABLE half_applied (id TEXT);\n\
4231- INSERT INTO no_such_table (id) VALUES ('x');";
4232- assert!(
4233- store.apply(before + 1, broken).await.is_err(),
4234- "the second statement cannot succeed"
4235- );
4236-
4237- assert_eq!(
4238- store.schema_version().await.unwrap(),
4239- before,
4240- "a failed migration is not recorded as applied"
4241- );
4242- assert!(
4243- store
4244- .one_row(
4245- "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'half_applied'",
4246- (),
4247- )
4248- .await
4249- .unwrap()
4250- .is_none(),
4251- "and the table its first statement created is rolled back with it"
4252- );
4253- let _ = std::fs::remove_dir_all(&dir);
4254- }
4255-}
crates/izlek-core/tests/fixtures/pre-collapse/0001_init.sqladded+391 -0
@@ -0,0 +1,391 @@
1+-- Izlek's schema, whole, in one file.
2+--
3+-- Plain versioned SQL applied at boot: Turso has no migration runner of its
4+-- own, and keeping the schema as SQL is what makes the store trait swappable.
5+-- Timestamps are RFC 3339 text in UTC. Ids are ULIDs as text — sortable by
6+-- creation, and Crockford-uppercase already, which is what lets a task key
7+-- borrow its tail.
8+--
9+-- This file is the whole schema, not the first link of a chain. Nothing has
10+-- been released, so a change to a table is made here, in the table, and the
11+-- database it describes is recreated — twenty migrations were collapsed into
12+-- this file once for that reason, and a twenty-first would start the same rot
13+-- over. The reasoning the old migrations carried is kept, on the tables it
14+-- explains. The day Izlek runs somewhere with data worth keeping, the next
15+-- change becomes 0002 and this note goes away.
16+
17+CREATE TABLE workspace (
18+ id TEXT PRIMARY KEY,
19+ name TEXT NOT NULL,
20+ created_at TEXT NOT NULL,
21+ -- Limits. Each states its consequence in the UI, not here. They are
22+ -- workspace content — an admin edits them, and no restart should be
23+ -- needed to raise an attachment ceiling.
24+ attachment_limit_bytes INTEGER NOT NULL DEFAULT 26214400,
25+ photo_limit_bytes INTEGER NOT NULL DEFAULT 2097152,
26+ -- JSON array of allowed extensions. An empty array means every type.
27+ allowed_file_types TEXT NOT NULL DEFAULT '[]',
28+ -- The single sender every mail in the workspace goes through, written by
29+ -- the admin in Settings rather than by whoever has a shell on the box: a
30+ -- three-person team has those be different people, and the second one is
31+ -- not always awake.
32+ --
33+ -- `smtp_password` holds ciphertext, never the typed string. The server
34+ -- has to present the password to the mail host on every send, so a
35+ -- one-way hash is impossible; instead `store::secret` seals it under a
36+ -- key kept in `izlek.key` beside this file, so a database copied for a
37+ -- backup does not carry a working credential with it. No field on
38+ -- `Workspace` exposes it — it is written by `Store::set_sender` and read
39+ -- by `Store::smtp_password`, which only the mailer calls.
40+ smtp_host TEXT,
41+ smtp_port INTEGER,
42+ smtp_username TEXT,
43+ smtp_password TEXT,
44+ smtp_from_name TEXT,
45+ smtp_from_address TEXT,
46+ -- The result of the last "send a test mail to myself", kept rather than
47+ -- shown once: an admin fills the sender in, presses the button, and comes
48+ -- back tomorrow wondering whether it ever worked. `smtp_test_error` is the
49+ -- mail server's own words, so the admin can act on them; the mailer builds
50+ -- its errors from what the server said, never from the credentials it sent.
51+ smtp_test_at TEXT,
52+ smtp_test_ms INTEGER,
53+ smtp_test_error TEXT,
54+ -- The address mail links point at, when the one the process was
55+ -- configured with is not the one people reach. A box behind a proxy
56+ -- answers on localhost and is known by a public name, and only an admin
57+ -- knows which — so it is workspace content, and `config/izlek.toml`'s
58+ -- `base_url` is what an empty one falls back to.
59+ public_url TEXT
60+);
61+
62+CREATE TABLE user (
63+ id TEXT PRIMARY KEY,
64+ workspace_id TEXT NOT NULL REFERENCES workspace(id),
65+ email TEXT NOT NULL,
66+ display_name TEXT NOT NULL,
67+ -- 'admin' | 'member' | 'viewer'
68+ role TEXT NOT NULL,
69+ -- NULL until the person picks a password on first sign-in. The admin
70+ -- creates the account with a name and an address and nothing else.
71+ password_hash TEXT,
72+ -- Whoever made this account, so the first-sign-in screen can greet the
73+ -- invited person by the inviter's name instead of reading their own name
74+ -- back to them. NULL for the first account, which nobody invited. A
75+ -- reference rather than a copied name, so a later rename is reflected.
76+ invited_by TEXT REFERENCES user(id),
77+ -- Display preferences. Stored data everywhere else stays UTC and
78+ -- language-neutral; these only change how a browser renders it for the
79+ -- one person signed in as this user, and nothing stored depends on them.
80+ timezone TEXT NOT NULL DEFAULT 'UTC',
81+ theme TEXT NOT NULL DEFAULT 'light',
82+ language TEXT NOT NULL DEFAULT 'en',
83+ ui TEXT NOT NULL DEFAULT 'instrument',
84+ -- The profile picture lives here as bytes, the way an attachment does:
85+ -- no filesystem path survives a backup or a move.
86+ photo BLOB,
87+ photo_mime TEXT,
88+ created_at TEXT NOT NULL,
89+ last_signed_in_at TEXT
90+);
91+CREATE UNIQUE INDEX user_email_unique ON user(workspace_id, email);
92+
93+-- One workspace, one owner. The singleton column is the whole point: the row
94+-- can exist at most once, so a second claim cannot race a first one.
95+CREATE TABLE workspace_owner (
96+ singleton INTEGER PRIMARY KEY,
97+ user_id TEXT NOT NULL REFERENCES user(id),
98+ claimed_at TEXT NOT NULL
99+);
100+
101+-- First sign-in / resend links. Only the hash is stored: the plaintext is
102+-- shown once when the admin creates or resends it.
103+CREATE TABLE signin_link (
104+ id TEXT PRIMARY KEY,
105+ user_id TEXT NOT NULL REFERENCES user(id),
106+ token_hash TEXT NOT NULL,
107+ created_at TEXT NOT NULL,
108+ expires_at TEXT NOT NULL,
109+ used_at TEXT
110+);
111+CREATE UNIQUE INDEX signin_link_token ON signin_link(token_hash);
112+
113+CREATE TABLE session (
114+ id TEXT PRIMARY KEY,
115+ user_id TEXT NOT NULL REFERENCES user(id),
116+ token_hash TEXT NOT NULL,
117+ created_at TEXT NOT NULL,
118+ expires_at TEXT NOT NULL,
119+ revoked_at TEXT
120+);
121+CREATE UNIQUE INDEX session_token ON session(token_hash);
122+CREATE INDEX session_by_user ON session(user_id);
123+
124+-- The rate-limit ledger: one row per attempt, pruned by age.
125+CREATE TABLE auth_attempt (
126+ id TEXT PRIMARY KEY,
127+ bucket TEXT NOT NULL,
128+ attempted_at TEXT NOT NULL
129+);
130+CREATE INDEX auth_attempt_by_bucket ON auth_attempt(bucket, attempted_at);
131+
132+CREATE TABLE board (
133+ id TEXT PRIMARY KEY,
134+ workspace_id TEXT NOT NULL REFERENCES workspace(id),
135+ name TEXT NOT NULL,
136+ -- The key prefix this board's tasks carry (`DZ-14`).
137+ task_prefix TEXT NOT NULL DEFAULT 'DZ',
138+ created_at TEXT NOT NULL
139+);
140+
141+CREATE TABLE board_column (
142+ id TEXT PRIMARY KEY,
143+ board_id TEXT NOT NULL REFERENCES board(id),
144+ name TEXT NOT NULL,
145+ position INTEGER NOT NULL,
146+ -- The column a finished task lands in; drives the "done Aug 14" card state.
147+ is_done INTEGER NOT NULL DEFAULT 0
148+);
149+
150+-- A task, and a subtask, which is the same thing with a parent.
151+--
152+-- `parent_id` is the whole of the subtask feature in this schema: a subtask
153+-- has every column a task has, so it carries assignees, a deadline, comments,
154+-- files, activity and mail exactly like anything else, and promoting one to
155+-- a task of its own is a single UPDATE rather than a move between tables.
156+--
157+-- Two rules the column cannot state itself, enforced in the store instead:
158+-- a parent must have `parent_id IS NULL` (one level, never a tree), and a
159+-- child sits on its parent's board. SQLite cannot ask, in a CHECK, whether
160+-- the row a foreign key points at has a NULL parent.
161+--
162+-- The board shows only rows with no parent; a subtask reaches its own detail
163+-- page through its parent's.
164+CREATE TABLE task (
165+ id TEXT PRIMARY KEY,
166+ board_id TEXT NOT NULL REFERENCES board(id),
167+ parent_id TEXT REFERENCES task(id),
168+ -- Human key from the mockups, e.g. DZ-14. The tail is the end of the
169+ -- task's own ULID rather than a per-board counter: a counter leaves
170+ -- visible gaps once tasks are deleted.
171+ task_key TEXT NOT NULL,
172+ title TEXT NOT NULL,
173+ description TEXT NOT NULL DEFAULT '',
174+ column_id TEXT NOT NULL REFERENCES board_column(id),
175+ deadline TEXT,
176+ position REAL NOT NULL DEFAULT 0,
177+ created_by TEXT NOT NULL REFERENCES user(id),
178+ created_at TEXT NOT NULL,
179+ updated_at TEXT NOT NULL,
180+ done_at TEXT,
181+ deleted_at TEXT
182+);
183+CREATE UNIQUE INDEX task_key_unique ON task(board_id, task_key);
184+CREATE INDEX task_by_column ON task(column_id);
185+CREATE INDEX task_by_parent ON task(parent_id);
186+
187+CREATE TABLE task_assignee (
188+ task_id TEXT NOT NULL REFERENCES task(id),
189+ user_id TEXT NOT NULL REFERENCES user(id),
190+ PRIMARY KEY (task_id, user_id)
191+);
192+
193+CREATE TABLE task_watcher (
194+ task_id TEXT NOT NULL REFERENCES task(id),
195+ user_id TEXT NOT NULL REFERENCES user(id),
196+ PRIMARY KEY (task_id, user_id)
197+);
198+
199+-- blocked_task_id is blocked by blocking_task_id. cleared_at is set when the
200+-- blocking task finishes, which is what the "you can start now" rule reads.
201+--
202+-- The CHECK is new: a task blocking itself was only ever stopped in
203+-- application code, and a row like that would make a card permanently and
204+-- unfixably blocked by its own existence.
205+CREATE TABLE task_dependency (
206+ blocked_task_id TEXT NOT NULL REFERENCES task(id),
207+ blocking_task_id TEXT NOT NULL REFERENCES task(id),
208+ created_at TEXT NOT NULL,
209+ cleared_at TEXT,
210+ PRIMARY KEY (blocked_task_id, blocking_task_id),
211+ CHECK (blocked_task_id <> blocking_task_id)
212+);
213+-- The primary key answers "what is this task waiting on"; the other
214+-- direction — "who is waiting on this one", which every finish and every
215+-- delete asks — has no prefix of it to use.
216+CREATE INDEX task_dependency_by_blocking ON task_dependency(blocking_task_id);
217+
218+CREATE TABLE comment (
219+ id TEXT PRIMARY KEY,
220+ task_id TEXT NOT NULL REFERENCES task(id),
221+ author_id TEXT NOT NULL REFERENCES user(id),
222+ body TEXT NOT NULL,
223+ created_at TEXT NOT NULL
224+);
225+CREATE INDEX comment_by_task ON comment(task_id);
226+
227+-- Attachments live in the database file, not on disk beside it.
228+--
229+-- Izlek is one process over one file, and a second place to keep state is a
230+-- second thing to back up, to lock, and to get out of step with the rows that
231+-- name it. And a path is exactly where an uploaded file name must never end
232+-- up: `../../etc` is a valid file name and a terrible path. Keeping the bytes
233+-- here means `file_name` is only ever a label printed on a chip, never
234+-- anything the server resolves.
235+CREATE TABLE attachment (
236+ id TEXT PRIMARY KEY,
237+ task_id TEXT NOT NULL REFERENCES task(id),
238+ comment_id TEXT REFERENCES comment(id),
239+ file_name TEXT NOT NULL,
240+ mime_type TEXT NOT NULL,
241+ size_bytes INTEGER NOT NULL,
242+ bytes BLOB NOT NULL,
243+ uploaded_by TEXT NOT NULL REFERENCES user(id),
244+ created_at TEXT NOT NULL
245+);
246+CREATE INDEX attachment_by_task ON attachment(task_id);
247+
248+-- Every move of a card from one column to another, written as a fact in the
249+-- same transaction as the move itself.
250+--
251+-- The mail rules trigger on the transition, not on the task's current column:
252+-- a card that goes Review -> Done -> Review has crossed into Done once, and
253+-- nothing recomputed from `task.column_id` afterwards can tell you that.
254+--
255+-- `from_column` deliberately carries no REFERENCES: a task created straight
256+-- into a column writes a transition with `from_column = ''`, meaning "created
257+-- into", so a rule watching that column fires for a new card and not only for
258+-- one dragged in later. No column's id is ever ''.
259+CREATE TABLE transition (
260+ id TEXT PRIMARY KEY,
261+ task_id TEXT NOT NULL REFERENCES task(id),
262+ from_column TEXT NOT NULL,
263+ to_column TEXT NOT NULL REFERENCES board_column(id),
264+ actor_id TEXT NOT NULL REFERENCES user(id),
265+ created_at TEXT NOT NULL
266+);
267+CREATE INDEX transition_by_task ON transition(task_id, created_at);
268+
269+-- A deletion that let other tasks go, recorded as a fact.
270+--
271+-- The unblocked rule has two causes and only one of them is a crossing: a
272+-- blocker can finish, or a blocker can be deleted. The crossing already has a
273+-- row in `transition`; the deletion had nowhere to be written, so a mail owed
274+-- because of one had no event to hang from and no way to be rebuilt on a
275+-- retry. This is that row.
276+--
277+-- `cause_key` and `cause_title` are copied rather than joined: the task they
278+-- name is deleted, and a mail sent an hour later still has to be able to say
279+-- which task it was.
280+CREATE TABLE freeing (
281+ id TEXT PRIMARY KEY,
282+ board_id TEXT NOT NULL REFERENCES board(id),
283+ cause_key TEXT NOT NULL,
284+ cause_title TEXT NOT NULL,
285+ actor_id TEXT NOT NULL REFERENCES user(id),
286+ created_at TEXT NOT NULL
287+);
288+CREATE INDEX freeing_by_board ON freeing(board_id, created_at);
289+
290+-- The activity strip in the task detail: who did what. `task_id` is nullable
291+-- because account and admin events — sign-ins, invites, role changes — have
292+-- no task to sit under, and still have to be loggable.
293+CREATE TABLE activity (
294+ id TEXT PRIMARY KEY,
295+ task_id TEXT REFERENCES task(id),
296+ actor_id TEXT REFERENCES user(id),
297+ kind TEXT NOT NULL,
298+ detail TEXT NOT NULL DEFAULT '',
299+ created_at TEXT NOT NULL
300+);
301+CREATE INDEX activity_by_task ON activity(task_id);
302+CREATE INDEX activity_recent ON activity(created_at);
303+
304+-- Mail rules are written only by the admin.
305+--
306+-- `trigger_kind` carries no CHECK on purpose: the set of triggers grows
307+-- without a schema change. `audience` does carry one, because those three
308+-- values are the only audiences the engine knows how to resolve.
309+CREATE TABLE mail_rule (
310+ id TEXT PRIMARY KEY,
311+ board_id TEXT NOT NULL REFERENCES board(id),
312+ trigger_kind TEXT NOT NULL,
313+ trigger_column TEXT REFERENCES board_column(id),
314+ subject TEXT NOT NULL,
315+ -- 'assignees' — the people the card points at; 'board' — everyone who can
316+ -- write on the board; 'creator' — whoever opened the card.
317+ audience TEXT NOT NULL CHECK (audience IN ('assignees', 'board', 'creator')),
318+ enabled INTEGER NOT NULL DEFAULT 1,
319+ -- Fold the task's own facts into the body instead of the subject line
320+ -- being all the recipient reads. Off by default.
321+ include_task_details INTEGER NOT NULL DEFAULT 0,
322+ created_at TEXT NOT NULL,
323+ -- Only a status rule names a column, and a status rule that names none
324+ -- watches every column. The check is here so a rule that names a column
325+ -- it could not act on cannot be stored at all.
326+ CHECK (trigger_column IS NULL OR trigger_kind = 'status')
327+);
328+CREATE INDEX mail_rule_by_board ON mail_rule(board_id);
329+
330+-- One row per mail owed, from the moment it is claimed until it is sent or
331+-- abandoned.
332+--
333+-- Three shapes share the table. A 'rule' send is owed to somebody because a
334+-- rule matched an event on a task, and carries all three. An 'invite' or a
335+-- 'notice' has none of them — a person is invited before they have a task, a
336+-- transition, or a rule to owe them anything — and carries its own subject
337+-- and body instead of getting them from `mail_rule`. The two CHECKs make the
338+-- shapes exclusive, so a half-built row cannot be stored.
339+--
340+-- `event_id` names a transition or a freeing without a foreign key: two
341+-- tables can cause a send, so the column cannot point at either and hold both.
342+CREATE TABLE mail_send (
343+ id TEXT PRIMARY KEY,
344+ rule_id TEXT REFERENCES mail_rule(id) ON DELETE CASCADE,
345+ event_id TEXT,
346+ task_id TEXT REFERENCES task(id),
347+ recipient TEXT NOT NULL,
348+ state TEXT NOT NULL CHECK (state IN ('pending', 'sent', 'failed', 'abandoned')),
349+ attempts INTEGER NOT NULL DEFAULT 0,
350+ last_error TEXT,
351+ claimed_at TEXT NOT NULL,
352+ next_attempt_at TEXT,
353+ sent_at TEXT,
354+ kind TEXT NOT NULL DEFAULT 'rule' CHECK (kind IN ('rule', 'invite', 'notice')),
355+ subject TEXT,
356+ body TEXT,
357+ CHECK ((kind = 'rule') = (rule_id IS NOT NULL AND event_id IS NOT NULL AND task_id IS NOT NULL)),
358+ CHECK ((kind IN ('invite', 'notice')) = (subject IS NOT NULL AND body IS NOT NULL))
359+);
360+CREATE UNIQUE INDEX mail_send_once ON mail_send(rule_id, event_id, task_id, recipient);
361+CREATE INDEX mail_send_owed ON mail_send(next_attempt_at);
362+CREATE INDEX mail_send_by_rule ON mail_send(rule_id, sent_at);
363+-- The task's own mail strip reads by task, which neither index above starts
364+-- with: both lead on `rule_id`, and an invite has none.
365+CREATE INDEX mail_send_by_task ON mail_send(task_id);
366+
367+-- What the mail engine decided, for every rule and every event, not just the
368+-- mails it sent.
369+--
370+-- `mail_send` only exists once a mail is owed and claimed; a card that moved
371+-- but matched no rule, a rule that was disabled, a task deleted before its
372+-- mail could go out — none of that left a trace. This is that trace, so "why
373+-- did nobody get mailed" has an answer that is not "look at the logs from
374+-- that day".
375+--
376+-- `task_id` carries no foreign key on purpose: a `task_gone` row exists
377+-- precisely because the task it names no longer does, and it has to keep
378+-- saying so afterwards.
379+CREATE TABLE mail_decision (
380+ id TEXT PRIMARY KEY,
381+ rule_id TEXT NOT NULL REFERENCES mail_rule(id) ON DELETE CASCADE,
382+ event_id TEXT NOT NULL,
383+ task_id TEXT NOT NULL,
384+ outcome TEXT NOT NULL CHECK (outcome IN
385+ ('owed', 'already_owed', 'no_recipients', 'not_matched', 'disabled', 'task_gone')),
386+ detail TEXT NOT NULL DEFAULT '',
387+ created_at TEXT NOT NULL
388+);
389+CREATE UNIQUE INDEX mail_decision_once ON mail_decision(rule_id, event_id, task_id);
390+CREATE INDEX mail_decision_recent ON mail_decision(created_at);
391+CREATE INDEX mail_decision_by_task ON mail_decision(task_id);
crates/izlek-core/migrations/0002_sender_check.sql → crates/izlek-core/tests/fixtures/pre-collapse/0002_sender_check.sqlrenamed+0 -0
crates/izlek-core/tests/store.rsmodified+1737 -194

Diff too large; view file

@@ -9,8 +9,8 @@ use std::path::PathBuf;
99 use izlek_core::Role;
1010 use izlek_core::auth::{Token, hash_password};
1111 use izlek_core::store::{
12- Audience, Event, MailOutcome, MailRule, NewAttachment, NewSender, NewUser, SendKind,
13- SendState, Store, StoreError, Trigger, TursoStore, User,
12+ Audience, Event, MailOutcome, MailRule, NewAttachment, NewSender, NewUser, SendKind, SendState,
13+ Store, StoreError, Trigger, TursoStore, User,
1414 };
1515 use time::{Duration, OffsetDateTime};
1616 use ulid::Ulid;
@@ -95,24 +95,19 @@ async fn member(store: &TursoStore, workspace_id: &str, email: &str, name: &str)
9595 }
9696
9797 #[tokio::test]
98-async fn migrations_apply_once_and_survive_reopen() {
98+async fn the_schema_is_created_once_and_survives_reopen() {
9999 let dir = std::env::temp_dir().join(format!("izlek-test-{}", Ulid::new()));
100100 std::fs::create_dir_all(&dir).unwrap();
101101 let path = dir.join("izlek.db").to_string_lossy().into_owned();
102102
103103 let first = TursoStore::open(&path).await.unwrap();
104- // Whatever the newest migration is — pinning the number here only means
105- // editing this line every time one is added, which tests the constant
106- // rather than the behaviour.
107- let applied = first.schema_version().await.unwrap();
108- assert!(applied >= 1, "no migration applied at all");
109104 claim(&first).await;
110105 drop(first);
111106
112- // Re-opening must not re-run a migration (0001's CREATE TABLE would fail)
113- // and must not lose what the first open wrote.
107+ // Re-opening a database that already has tables must not re-run the
108+ // schema (its CREATE TABLE would fail on the first one) and must not
109+ // lose what the first open wrote.
114110 let second = TursoStore::open(&path).await.unwrap();
115- assert_eq!(second.schema_version().await.unwrap(), applied);
116111 assert_eq!(second.workspace().await.unwrap().unwrap().name, "İzlek");
117112 drop(second);
118113 let _ = std::fs::remove_dir_all(&dir);
@@ -169,7 +164,15 @@ async fn subtasks_go_one_level_deep() {
169164 let board = scratch.store.board(&workspace).await.unwrap().unwrap();
170165 let column_id = column_named(&scratch.store, &workspace, "Backlog").await;
171166
172- let parent = add_task(&scratch.store, &workspace, "Backlog", "Parent", None, &admin).await;
167+ let parent = add_task(
168+ &scratch.store,
169+ &workspace,
170+ "Backlog",
171+ "Parent",
172+ None,
173+ &admin,
174+ )
175+ .await;
173176 let child = scratch
174177 .store
175178 .create_task(NewTask {
@@ -238,10 +241,22 @@ async fn a_task_cannot_be_its_own_parent() {
238241 async fn parenting_and_promoting_are_each_one_write() {
239242 let scratch = Scratch::open().await;
240243 let (workspace, admin) = claim(&scratch.store).await;
241- let parent = add_task(&scratch.store, &workspace, "Backlog", "Parent", None, &admin).await;
244+ let parent = add_task(
245+ &scratch.store,
246+ &workspace,
247+ "Backlog",
248+ "Parent",
249+ None,
250+ &admin,
251+ )
252+ .await;
242253 let loose = add_task(&scratch.store, &workspace, "Review", "Loose", None, &admin).await;
243254
244- scratch.store.set_parent(&loose, Some(&parent)).await.unwrap();
255+ scratch
256+ .store
257+ .set_parent(&loose, Some(&parent))
258+ .await
259+ .unwrap();
245260 let children = scratch.store.subtasks(&parent).await.unwrap();
246261 assert_eq!(children.len(), 1);
247262 assert_eq!(children[0].id, loose);
@@ -277,7 +292,15 @@ async fn a_parent_and_one_subtask(
277292 workspace: &str,
278293 admin: &str,
279294 ) -> (String, String) {
280- let parent = add_task(store, workspace, "Backlog", "Ship the exporter", None, admin).await;
295+ let parent = add_task(
296+ store,
297+ workspace,
298+ "Backlog",
299+ "Ship the exporter",
300+ None,
301+ admin,
302+ )
303+ .await;
281304 let board = store.board(workspace).await.unwrap().unwrap();
282305 let column_id = column_named(store, workspace, "Backlog").await;
283306 let child = store
@@ -328,7 +351,15 @@ async fn a_parent_does_not_finish_before_its_subtasks_do() {
328351 );
329352
330353 // The subtask finishing is what lets the parent through.
331- moved_to(&scratch.store, &workspace, &child, "Backlog", "Done", &admin).await;
354+ moved_to(
355+ &scratch.store,
356+ &workspace,
357+ &child,
358+ "Backlog",
359+ "Done",
360+ &admin,
361+ )
362+ .await;
332363 let recorded = scratch
333364 .store
334365 .move_task(&parent, &backlog, &done, &admin, OffsetDateTime::now_utc())
@@ -379,7 +410,15 @@ async fn a_subtask_finishes_on_its_own_account() {
379410 let (_parent, child) = a_parent_and_one_subtask(&scratch.store, &workspace, &admin).await;
380411
381412 // The rule is about a parent's parts, not about being somebody's part.
382- moved_to(&scratch.store, &workspace, &child, "Backlog", "Done", &admin).await;
413+ moved_to(
414+ &scratch.store,
415+ &workspace,
416+ &child,
417+ "Backlog",
418+ "Done",
419+ &admin,
420+ )
421+ .await;
383422 }
384423
385424 #[tokio::test]
@@ -395,7 +434,15 @@ async fn a_deleted_subtask_stops_holding_its_parent() {
395434 .delete_task(&child, &admin, OffsetDateTime::now_utc())
396435 .await
397436 .unwrap();
398- moved_to(&scratch.store, &workspace, &parent, "Backlog", "Done", &admin).await;
437+ moved_to(
438+ &scratch.store,
439+ &workspace,
440+ &parent,
441+ "Backlog",
442+ "Done",
443+ &admin,
444+ )
445+ .await;
399446 }
400447
401448 #[tokio::test]
@@ -405,7 +452,15 @@ async fn a_promoted_subtask_stops_holding_its_parent() {
405452 let (parent, child) = a_parent_and_one_subtask(&scratch.store, &workspace, &admin).await;
406453
407454 scratch.store.set_parent(&child, None).await.unwrap();
408- moved_to(&scratch.store, &workspace, &parent, "Backlog", "Done", &admin).await;
455+ moved_to(
456+ &scratch.store,
457+ &workspace,
458+ &parent,
459+ "Backlog",
460+ "Done",
461+ &admin,
462+ )
463+ .await;
409464 }
410465
411466 #[tokio::test]
@@ -424,7 +479,15 @@ async fn the_board_counts_subtasks_instead_of_carding_them() {
424479 assert_eq!(cards[0].subtask_label().as_deref(), Some("0/1"));
425480 assert!(cards[0].holds_on_subtasks());
426481
427- moved_to(&scratch.store, &workspace, &child, "Backlog", "Done", &admin).await;
482+ moved_to(
483+ &scratch.store,
484+ &workspace,
485+ &child,
486+ "Backlog",
487+ "Done",
488+ &admin,
489+ )
490+ .await;
428491 let board = load(&scratch.store, &workspace).await.unwrap().unwrap();
429492 let card = board
430493 .columns
@@ -453,7 +516,15 @@ async fn a_subtask_blocking_a_card_still_names_itself_on_it() {
453516 let scratch = Scratch::open().await;
454517 let (workspace, admin) = claim(&scratch.store).await;
455518 let (_parent, child) = a_parent_and_one_subtask(&scratch.store, &workspace, &admin).await;
456- let other = add_task(&scratch.store, &workspace, "Backlog", "Waiting", None, &admin).await;
519+ let other = add_task(
520+ &scratch.store,
521+ &workspace,
522+ "Backlog",
523+ "Waiting",
524+ None,
525+ &admin,
526+ )
527+ .await;
457528 scratch
458529 .store
459530 .add_dependency(&other, &child, OffsetDateTime::now_utc())
@@ -699,9 +770,9 @@ async fn many_concurrent_callers_never_see_concurrent_use_forbidden() {
699770 }
700771
701772 for task in tasks {
702- task.await
703- .unwrap()
704- .expect("concurrent store access must never surface Misuse(\"concurrent use forbidden\")");
773+ task.await.unwrap().expect(
774+ "concurrent store access must never surface Misuse(\"concurrent use forbidden\")",
775+ );
705776 }
706777
707778 drop(store);
@@ -784,7 +855,11 @@ async fn a_save_with_no_password_typed_keeps_the_stored_one() {
784855 from_name: "İzlek".into(),
785856 from_address: "izlek@izlek.sh".into(),
786857 };
787- scratch.store.set_sender(&ws_id, sender.clone()).await.unwrap();
858+ scratch
859+ .store
860+ .set_sender(&ws_id, sender.clone())
861+ .await
862+ .unwrap();
788863
789864 sender.port = 465;
790865 sender.password = None;
@@ -794,7 +869,12 @@ async fn a_save_with_no_password_typed_keeps_the_stored_one() {
794869 assert_eq!(ws.smtp_port, Some(465), "the edit did not land");
795870 assert!(ws.smtp_password_set, "the password was blanked by an edit");
796871 assert_eq!(
797- scratch.store.smtp_password(&ws_id).await.unwrap().as_deref(),
872+ scratch
873+ .store
874+ .smtp_password(&ws_id)
875+ .await
876+ .unwrap()
877+ .as_deref(),
798878 Some("keep-me")
799879 );
800880 }
@@ -812,12 +892,21 @@ async fn a_typed_password_replaces_the_stored_one() {
812892 from_name: "İzlek".into(),
813893 from_address: "izlek@izlek.sh".into(),
814894 };
815- scratch.store.set_sender(&ws_id, sender.clone()).await.unwrap();
895+ scratch
896+ .store
897+ .set_sender(&ws_id, sender.clone())
898+ .await
899+ .unwrap();
816900 sender.password = Some("the-new-one".into());
817901 scratch.store.set_sender(&ws_id, sender).await.unwrap();
818902
819903 assert_eq!(
820- scratch.store.smtp_password(&ws_id).await.unwrap().as_deref(),
904+ scratch
905+ .store
906+ .smtp_password(&ws_id)
907+ .await
908+ .unwrap()
909+ .as_deref(),
821910 Some("the-new-one")
822911 );
823912 }
@@ -846,7 +935,10 @@ async fn the_stored_password_is_not_the_plaintext_on_disk() {
846935
847936 let conn = raw_conn(&scratch).await;
848937 let mut rows = conn
849- .query("SELECT smtp_password FROM workspace WHERE id = ?1", turso::params![ws_id.clone()])
938+ .query(
939+ "SELECT smtp_password FROM workspace WHERE id = ?1",
940+ turso::params![ws_id.clone()],
941+ )
850942 .await
851943 .unwrap();
852944 let row = rows.next().await.unwrap().unwrap();
@@ -855,11 +947,19 @@ async fn the_stored_password_is_not_the_plaintext_on_disk() {
855947 !column.contains("a-very-secret-string"),
856948 "the plaintext is sitting in the column: {column}"
857949 );
858- assert!(column.starts_with("v1:"), "expected the sealed envelope, got: {column}");
950+ assert!(
951+ column.starts_with("v1:"),
952+ "expected the sealed envelope, got: {column}"
953+ );
859954
860955 // And the read path still gets the real password back.
861956 assert_eq!(
862- scratch.store.smtp_password(&ws_id).await.unwrap().as_deref(),
957+ scratch
958+ .store
959+ .smtp_password(&ws_id)
960+ .await
961+ .unwrap()
962+ .as_deref(),
863963 Some("a-very-secret-string")
864964 );
865965 }
@@ -921,7 +1021,12 @@ async fn a_password_that_will_not_decrypt_reads_back_as_none() {
9211021 .await
9221022 .unwrap();
9231023 assert_eq!(
924- scratch.store.smtp_password(&ws_id).await.unwrap().as_deref(),
1024+ scratch
1025+ .store
1026+ .smtp_password(&ws_id)
1027+ .await
1028+ .unwrap()
1029+ .as_deref(),
9251030 Some("a-fresh-password"),
9261031 "retyping the password heals a store that could not decrypt it"
9271032 );
@@ -942,7 +1047,12 @@ async fn the_database_and_key_file_are_owner_only() {
9421047 .permissions()
9431048 .mode()
9441049 & 0o777;
945- assert_eq!(mode, 0o600, "{} is not owner-only: {mode:o}", path.display());
1050+ assert_eq!(
1051+ mode,
1052+ 0o600,
1053+ "{} is not owner-only: {mode:o}",
1054+ path.display()
1055+ );
9461056 }
9471057 }
9481058
@@ -952,7 +1062,7 @@ async fn limits_round_trip_including_the_file_type_list() {
9521062 let types = vec!["png".to_string(), "pdf".to_string()];
9531063 scratch
9541064 .store
955- .set_limits(&ws_id, 10 * 1024 * 1024, 512 * 1024, &types)
1065+ .set_limits(&ws_id, 10 * 1024 * 1024, 512 * 1024, &types, 5)
9561066 .await
9571067 .unwrap();
9581068 let ws = scratch.store.workspace().await.unwrap().unwrap();
@@ -1119,11 +1229,26 @@ async fn email_change_persists_and_refuses_a_taken_address() {
11191229 .await
11201230 .unwrap();
11211231 // Case-folded the same way sign-in matches an address.
1122- assert!(store.user_by_email(&ws_id, "grace.new@izlek.sh").await.unwrap().is_some());
1123- assert!(store.user_by_email(&ws_id, "grace@izlek.sh").await.unwrap().is_none());
1232+ assert!(
1233+ store
1234+ .user_by_email(&ws_id, "grace.new@izlek.sh")
1235+ .await
1236+ .unwrap()
1237+ .is_some()
1238+ );
1239+ assert!(
1240+ store
1241+ .user_by_email(&ws_id, "grace@izlek.sh")
1242+ .await
1243+ .unwrap()
1244+ .is_none()
1245+ );
11241246
11251247 // Taken by the admin already claimed above.
1126- let err = store.set_email(&user_id, &ws_id, "ada@izlek.sh").await.unwrap_err();
1248+ let err = store
1249+ .set_email(&user_id, &ws_id, "ada@izlek.sh")
1250+ .await
1251+ .unwrap_err();
11271252 assert!(matches!(err, StoreError::Conflict("account")));
11281253 user_id
11291254 };
@@ -1650,7 +1775,11 @@ async fn adding_a_member_queues_the_mail_that_carries_the_link() {
16501775 .await
16511776 .unwrap();
16521777
1653- let queue = accounts.store().mail_queue(10, izlek_core::store::FeedPage::Newest).await.unwrap();
1778+ let queue = accounts
1779+ .store()
1780+ .mail_queue(10, izlek_core::store::FeedPage::Newest)
1781+ .await
1782+ .unwrap();
16541783 let queued = queue
16551784 .iter()
16561785 .find(|s| s.recipient == "grace@izlek.sh")
@@ -2356,7 +2485,10 @@ async fn count_and_filtered_keyset_walk_cover_exactly_the_filtered_set() {
23562485 .unwrap();
23572486 }
23582487
2359- let filter = ActivityFilter { actor: Some(admin.clone()), ..Default::default() };
2488+ let filter = ActivityFilter {
2489+ actor: Some(admin.clone()),
2490+ ..Default::default()
2491+ };
23602492 let total = store.count_activity(&filter).await.unwrap();
23612493 assert_eq!(total, 10);
23622494
@@ -2371,17 +2503,27 @@ async fn count_and_filtered_keyset_walk_cover_exactly_the_filtered_set() {
23712503 break;
23722504 }
23732505 let last = rows.last().unwrap();
2374- page = FeedPage::Before(FeedCursor { at: last.at, id: last.id.clone() });
2506+ page = FeedPage::Before(FeedCursor {
2507+ at: last.at,
2508+ id: last.id.clone(),
2509+ });
23752510 walked.extend(rows);
23762511 }
23772512 assert_eq!(walked.len(), 10);
2378- assert!(walked.iter().all(|r| r.actor_name.as_deref() == Some("Ada")));
2513+ assert!(
2514+ walked
2515+ .iter()
2516+ .all(|r| r.actor_name.as_deref() == Some("Ada"))
2517+ );
23792518
23802519 let preceding = store
23812520 .count_activity_preceding(
23822521 &filter,
23832522 Dir::Newest,
2384- Some(&FeedCursor { at: walked[3].at, id: walked[3].id.clone() }),
2523+ Some(&FeedCursor {
2524+ at: walked[3].at,
2525+ id: walked[3].id.clone(),
2526+ }),
23852527 )
23862528 .await
23872529 .unwrap();
@@ -2413,11 +2555,16 @@ async fn a_claimed_workspace_starts_with_four_named_columns() {
24132555 /// comes off the task's own id now, not a per-board counter, so exact keys
24142556 /// are no longer predictable — only the shape and per-board uniqueness are.
24152557 fn is_task_key_shaped(key: &str, prefix: &str) -> bool {
2416- let Some(tail) = key.strip_prefix(prefix).and_then(|rest| rest.strip_prefix('-')) else {
2558+ let Some(tail) = key
2559+ .strip_prefix(prefix)
2560+ .and_then(|rest| rest.strip_prefix('-'))
2561+ else {
24172562 return false;
24182563 };
24192564 (5..=7).contains(&tail.len())
2420- && tail.chars().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit())
2565+ && tail
2566+ .chars()
2567+ .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit())
24212568 }
24222569
24232570 #[tokio::test]
@@ -2432,7 +2579,10 @@ async fn tasks_get_key_tails_off_their_own_id_not_a_board_counter() {
24322579 let keys: Vec<&str> = board.cards().map(|card| card.task_key.as_str()).collect();
24332580 assert_eq!(keys.len(), 2);
24342581 for key in &keys {
2435- assert!(is_task_key_shaped(key, "DZ"), "key {key} is not shaped like DZ-<5..7 chars>");
2582+ assert!(
2583+ is_task_key_shaped(key, "DZ"),
2584+ "key {key} is not shaped like DZ-<5..7 chars>"
2585+ );
24362586 }
24372587 assert_ne!(keys[0], keys[1], "two tasks never share a key");
24382588 }
@@ -2487,7 +2637,12 @@ async fn a_card_carries_its_assignees_comments_and_dependency_keys() {
24872637 }
24882638
24892639 let board = board_of(store, &workspace).await;
2490- let blocked_key = board.cards().find(|card| card.id == blocked).unwrap().task_key.clone();
2640+ let blocked_key = board
2641+ .cards()
2642+ .find(|card| card.id == blocked)
2643+ .unwrap()
2644+ .task_key
2645+ .clone();
24912646 let card = board.cards().find(|card| card.id == blocking).unwrap();
24922647 assert_eq!(card.assignees.len(), 2);
24932648 assert_eq!(card.comment_count, 3);
@@ -2617,10 +2772,28 @@ async fn a_board_costs_six_queries_whatever_its_size() {
26172772 .unwrap();
26182773 }
26192774 }
2775+ // A tag rides the task query as a join: the sweep stays at six.
2776+ let board_meta = store.board(&workspace).await.unwrap().unwrap();
2777+ let tag = store
2778+ .create_tag(&board_meta.id, "shipping", OffsetDateTime::now_utc())
2779+ .await
2780+ .unwrap();
2781+ let tagged = previous.expect("the loop created tasks");
2782+ store.set_task_tag(&tagged, &tag.id).await.unwrap();
26202783
26212784 let big = CountingReads::new(store);
26222785 let board = load(&big, &workspace).await.unwrap().unwrap();
26232786 assert_eq!(board.task_count(), 40);
2787+ let tagged_card = board
2788+ .columns
2789+ .iter()
2790+ .flat_map(|column| column.cards.iter())
2791+ .find(|card| card.id == tagged)
2792+ .unwrap();
2793+ assert_eq!(
2794+ tagged_card.tag.as_ref().map(|t| t.name.as_str()),
2795+ Some("shipping")
2796+ );
26242797 assert_eq!(
26252798 big.count(),
26262799 6,
@@ -2628,99 +2801,339 @@ async fn a_board_costs_six_queries_whatever_its_size() {
26282801 );
26292802 }
26302803
2631-#[test]
2632-fn initials_fall_back_to_two_letters() {
2633- let person = |name: &str| Person {
2634- id: "u".into(),
2635- display_name: name.into(),
2636- has_photo: false,
2637- };
2638- assert_eq!(person("Mel Duarte").initials(), "MD");
2639- assert_eq!(person("Ada").initials(), "A");
2640- assert_eq!(person(" ").initials(), "?");
2641-}
2642-
2643-// -- task detail ------------------------------------------------------------
2804+// -- tags -------------------------------------------------------------------
26442805
2645-use izlek_core::detail::{
2646- ActivityEntry, ActivityKind, Comment, DependencyEdge, DetailReads, TaskFacts,
2647- load as load_detail,
2648-};
2806+#[tokio::test]
2807+async fn tags_are_created_in_order_renamed_moved_and_deleted() {
2808+ let (scratch, workspace, _admin) = workspace_with_admin().await;
2809+ let store = &scratch.store;
2810+ let board = store.board(&workspace).await.unwrap().unwrap();
2811+ let at = OffsetDateTime::now_utc();
26492812
2650-/// The same trick as [`CountingReads`], for the detail screen: the round trips
2651-/// one task costs must not follow how much it carries.
2652-struct CountingDetail<'a> {
2653- inner: &'a TursoStore,
2654- calls: AtomicUsize,
2655-}
2813+ let alpha = store.create_tag(&board.id, "alpha", at).await.unwrap();
2814+ let beta = store.create_tag(&board.id, "beta", at).await.unwrap();
2815+ let gamma = store.create_tag(&board.id, "gamma", at).await.unwrap();
2816+ assert_eq!((alpha.position, beta.position, gamma.position), (1, 2, 3));
26562817
2657-impl<'a> CountingDetail<'a> {
2658- fn new(inner: &'a TursoStore) -> Self {
2659- Self {
2660- inner,
2661- calls: AtomicUsize::new(0),
2662- }
2663- }
2818+ store.rename_tag(&beta.id, "beta2").await.unwrap();
2819+ assert_eq!(
2820+ tag_order(&store.tags(&board.id).await.unwrap()),
2821+ ["General", "alpha", "beta2", "gamma"]
2822+ );
26642823
2665- fn count(&self) -> usize {
2666- self.calls.load(Ordering::Relaxed)
2667- }
2824+ // Swapping moves one place, never to the far end.
2825+ store.move_tag(&beta.id, true).await.unwrap();
2826+ assert_eq!(
2827+ tag_order(&store.tags(&board.id).await.unwrap()),
2828+ ["General", "beta2", "alpha", "gamma"]
2829+ );
2830+ // A tag already at that end stays put: nothing to swap is not an error.
2831+ store.move_tag(&gamma.id, false).await.unwrap();
2832+ assert_eq!(
2833+ tag_order(&store.tags(&board.id).await.unwrap()),
2834+ ["General", "beta2", "alpha", "gamma"]
2835+ );
2836+ store.move_tag(&beta.id, true).await.unwrap();
2837+ assert_eq!(
2838+ tag_order(&store.tags(&board.id).await.unwrap()),
2839+ ["beta2", "General", "alpha", "gamma"]
2840+ );
2841+ store.move_tag(&alpha.id, true).await.unwrap();
2842+ assert_eq!(
2843+ tag_order(&store.tags(&board.id).await.unwrap()),
2844+ ["beta2", "alpha", "General", "gamma"]
2845+ );
26682846
2669- fn tick(&self) {
2670- self.calls.fetch_add(1, Ordering::Relaxed);
2671- }
2847+ store.delete_tag(&beta.id).await.unwrap();
2848+ assert_eq!(
2849+ tag_order(&store.tags(&board.id).await.unwrap()),
2850+ ["alpha", "General", "gamma"]
2851+ );
2852+ assert!(matches!(
2853+ store.delete_tag(&beta.id).await,
2854+ Err(StoreError::NotFound)
2855+ ));
26722856 }
26732857
2674-#[async_trait::async_trait]
2675-impl DetailReads for CountingDetail<'_> {
2676- async fn task(&self, task_id: &str) -> Result<Option<TaskFacts>, StoreError> {
2677- self.tick();
2678- self.inner.task(task_id).await
2679- }
2680-
2681- async fn columns_for_board(
2682- &self,
2683- board_id: &str,
2684- ) -> Result<Vec<izlek_core::Column>, StoreError> {
2685- self.tick();
2686- self.inner.columns_for_board(board_id).await
2687- }
2858+#[tokio::test]
2859+async fn a_boards_tags_have_unique_names() {
2860+ let (scratch, workspace, _admin) = workspace_with_admin().await;
2861+ let store = &scratch.store;
2862+ let board = store.board(&workspace).await.unwrap().unwrap();
2863+ let at = OffsetDateTime::now_utc();
26882864
2689- async fn assignees_for_task(&self, task_id: &str) -> Result<Vec<Person>, StoreError> {
2690- self.tick();
2691- self.inner.assignees_for_task(task_id).await
2692- }
2865+ store.create_tag(&board.id, "ops", at).await.unwrap();
2866+ assert!(
2867+ matches!(
2868+ store.create_tag(&board.id, "ops", at).await,
2869+ Err(StoreError::Conflict("tag"))
2870+ ),
2871+ "two tags with one name are one project spelled twice"
2872+ );
26932873
2694- async fn assignable_people(&self, workspace_id: &str) -> Result<Vec<Person>, StoreError> {
2695- self.tick();
2696- self.inner.assignable_people(workspace_id).await
2697- }
2874+ // The same name on another board is a different project.
2875+ let other = Scratch::open().await;
2876+ let (other_ws, _other_admin) = claim(&other.store).await;
2877+ let other_board = other.store.board(&other_ws).await.unwrap().unwrap();
2878+ other
2879+ .store
2880+ .create_tag(&other_board.id, "ops", at)
2881+ .await
2882+ .unwrap();
26982883
2699- async fn dependencies_for_task(
2700- &self,
2701- task_id: &str,
2702- ) -> Result<Vec<(bool, DependencyEdge)>, StoreError> {
2703- self.tick();
2704- self.inner.dependencies_for_task(task_id).await
2705- }
2884+ // A rename into a clash refuses the same way.
2885+ let ship = store.create_tag(&board.id, "ship", at).await.unwrap();
2886+ assert!(matches!(
2887+ store.rename_tag(&ship.id, "ops").await,
2888+ Err(StoreError::Conflict("tag"))
2889+ ));
2890+}
27062891
2707- async fn comments_for_task(&self, task_id: &str) -> Result<Vec<Comment>, StoreError> {
2708- self.tick();
2709- self.inner.comments_for_task(task_id).await
2710- }
2892+fn tag_order(tags: &[izlek_core::store::Tag]) -> Vec<&str> {
2893+ tags.iter().map(|t| t.name.as_str()).collect()
2894+}
27112895
2712- async fn files_for_task(
2713- &self,
2714- task_id: &str,
2715- ) -> Result<Vec<izlek_core::detail::FileLine>, StoreError> {
2716- self.tick();
2717- self.inner.files_for_task(task_id).await
2718- }
2896+fn card_of<'a>(
2897+ view: &'a izlek_core::board::BoardView,
2898+ task: &str,
2899+) -> &'a izlek_core::board::TaskCard {
2900+ view.columns
2901+ .iter()
2902+ .flat_map(|column| column.cards.iter())
2903+ .find(|card| card.id == task)
2904+ .unwrap()
2905+}
27192906
2720- async fn activity_for_task(&self, task_id: &str) -> Result<Vec<ActivityEntry>, StoreError> {
2721- self.tick();
2722- self.inner.activity_for_task(task_id).await
2723- }
2907+#[tokio::test]
2908+async fn deleting_a_tag_moves_its_tasks_to_the_default_and_a_foreign_tag_is_not_found() {
2909+ let (scratch, workspace, admin) = workspace_with_admin().await;
2910+ let store = &scratch.store;
2911+ let board = store.board(&workspace).await.unwrap().unwrap();
2912+ let tag = store
2913+ .create_tag(&board.id, "ops", OffsetDateTime::now_utc())
2914+ .await
2915+ .unwrap();
2916+ let task = add_task(store, &workspace, "Backlog", "tagged", None, &admin).await;
2917+
2918+ // The task came wearing the default; moving it to `ops` shows in the
2919+ // card and the detail alike.
2920+ let view = board_of(store, &workspace).await;
2921+ assert_eq!(
2922+ card_of(&view, &task).tag.as_ref().map(|t| t.name.as_str()),
2923+ Some("General")
2924+ );
2925+ store.set_task_tag(&task, &tag.id).await.unwrap();
2926+ let view = board_of(store, &workspace).await;
2927+ assert_eq!(
2928+ card_of(&view, &task).tag.as_ref().map(|t| t.name.as_str()),
2929+ Some("ops")
2930+ );
2931+ let detail = load_detail(store, &workspace, &task)
2932+ .await
2933+ .unwrap()
2934+ .unwrap();
2935+ assert_eq!(
2936+ detail.tag.as_ref().map(|t| t.id.as_str()),
2937+ Some(tag.id.as_str())
2938+ );
2939+
2940+ // A tag from another board — or one that never existed — is not found,
2941+ // not refused: it is not one of this board's projects at all.
2942+ let other = Scratch::open().await;
2943+ let (other_ws, _other_admin) = claim(&other.store).await;
2944+ let other_board = other.store.board(&other_ws).await.unwrap().unwrap();
2945+ let foreign = other
2946+ .store
2947+ .create_tag(&other_board.id, "foreign", OffsetDateTime::now_utc())
2948+ .await
2949+ .unwrap();
2950+ assert!(matches!(
2951+ store.set_task_tag(&task, &foreign.id).await,
2952+ Err(StoreError::NotFound)
2953+ ));
2954+ assert!(matches!(
2955+ store.set_task_tag(&task, "no-such-tag").await,
2956+ Err(StoreError::NotFound)
2957+ ));
2958+
2959+ // Deleting a worn tag leaves the task on the board's default, and the
2960+ // task survives.
2961+ store.delete_tag(&tag.id).await.unwrap();
2962+ let view = board_of(store, &workspace).await;
2963+ assert_eq!(
2964+ card_of(&view, &task).tag.as_ref().map(|t| t.name.as_str()),
2965+ Some("General")
2966+ );
2967+}
2968+
2969+#[tokio::test]
2970+async fn a_fresh_board_comes_with_a_default_tag_and_new_tasks_wear_it() {
2971+ let (scratch, workspace, admin) = workspace_with_admin().await;
2972+ let store = &scratch.store;
2973+ let board = store.board(&workspace).await.unwrap().unwrap();
2974+
2975+ let tags = store.tags(&board.id).await.unwrap();
2976+ assert_eq!(tags.len(), 1, "a claimed board seeds exactly one tag");
2977+ assert!(tags[0].is_default, "the seeded tag is the default");
2978+ assert_eq!((tags[0].name.as_str(), tags[0].position), ("General", 0));
2979+
2980+ // Nobody chose a tag; the task wears the board's default all the same.
2981+ let task = add_task(store, &workspace, "Backlog", "first", None, &admin).await;
2982+ let view = board_of(store, &workspace).await;
2983+ assert_eq!(
2984+ card_of(&view, &task).tag.as_ref().map(|t| t.name.as_str()),
2985+ Some("General")
2986+ );
2987+}
2988+
2989+#[tokio::test]
2990+async fn the_default_tag_cannot_be_deleted_but_renames_and_moves_like_any_other() {
2991+ let (scratch, workspace, _admin) = workspace_with_admin().await;
2992+ let store = &scratch.store;
2993+ let board = store.board(&workspace).await.unwrap().unwrap();
2994+ let default = &store.tags(&board.id).await.unwrap()[0];
2995+
2996+ assert!(matches!(
2997+ store.delete_tag(&default.id).await,
2998+ Err(StoreError::Conflict("default_tag"))
2999+ ));
3000+
3001+ store.rename_tag(&default.id, "Projects").await.unwrap();
3002+ store
3003+ .create_tag(&board.id, "alpha", OffsetDateTime::now_utc())
3004+ .await
3005+ .unwrap();
3006+ store.move_tag(&default.id, false).await.unwrap();
3007+ assert_eq!(
3008+ tag_order(&store.tags(&board.id).await.unwrap()),
3009+ ["alpha", "Projects"]
3010+ );
3011+}
3012+
3013+#[tokio::test]
3014+async fn a_board_cannot_hold_two_defaults_and_a_task_cannot_go_tagless() {
3015+ let (scratch, workspace, _admin) = workspace_with_admin().await;
3016+ let board = scratch.store.board(&workspace).await.unwrap().unwrap();
3017+
3018+ // Two defaults is a schema rule, so it is the schema that refuses —
3019+ // exercised raw, because the store's own writes never try it.
3020+ let conn = raw_conn(&scratch).await;
3021+ let _ = conn
3022+ .execute(
3023+ "INSERT INTO tag (id, board_id, name, position, is_default, created_at) \
3024+ VALUES ('t2', ?1, 'second', 9, 1, '2026-01-01T00:00:00Z')",
3025+ turso::params![board.id.clone()],
3026+ )
3027+ .await
3028+ .expect_err("a second default tag violates tag_one_default");
3029+
3030+ // And a task's tag_id is NOT NULL in the declared schema itself, not a
3031+ // habit of the write path.
3032+ let _ = conn
3033+ .execute(
3034+ "INSERT INTO task (id, board_id, task_key, title, column_id, tag_id, position, \
3035+ created_by, created_at, updated_at) \
3036+ VALUES ('tk', ?1, 'DZ-99', 'raw', (SELECT id FROM board_column LIMIT 1), NULL, 0, \
3037+ (SELECT id FROM user LIMIT 1), '2026-01-01T00:00:00Z', '2026-01-01T00:00:00Z')",
3038+ turso::params![board.id.clone()],
3039+ )
3040+ .await
3041+ .expect_err("task.tag_id is NOT NULL");
3042+}
3043+
3044+#[test]
3045+fn initials_fall_back_to_two_letters() {
3046+ let person = |name: &str| Person {
3047+ id: "u".into(),
3048+ display_name: name.into(),
3049+ has_photo: false,
3050+ };
3051+ assert_eq!(person("Mel Duarte").initials(), "MD");
3052+ assert_eq!(person("Ada").initials(), "A");
3053+ assert_eq!(person(" ").initials(), "?");
3054+}
3055+
3056+// -- task detail ------------------------------------------------------------
3057+
3058+use izlek_core::detail::{
3059+ ActivityEntry, ActivityKind, Comment, DependencyEdge, DetailReads, TaskFacts,
3060+ load as load_detail,
3061+};
3062+
3063+/// The same trick as [`CountingReads`], for the detail screen: the round trips
3064+/// one task costs must not follow how much it carries.
3065+struct CountingDetail<'a> {
3066+ inner: &'a TursoStore,
3067+ calls: AtomicUsize,
3068+}
3069+
3070+impl<'a> CountingDetail<'a> {
3071+ fn new(inner: &'a TursoStore) -> Self {
3072+ Self {
3073+ inner,
3074+ calls: AtomicUsize::new(0),
3075+ }
3076+ }
3077+
3078+ fn count(&self) -> usize {
3079+ self.calls.load(Ordering::Relaxed)
3080+ }
3081+
3082+ fn tick(&self) {
3083+ self.calls.fetch_add(1, Ordering::Relaxed);
3084+ }
3085+}
3086+
3087+#[async_trait::async_trait]
3088+impl DetailReads for CountingDetail<'_> {
3089+ async fn task(&self, task_id: &str) -> Result<Option<TaskFacts>, StoreError> {
3090+ self.tick();
3091+ self.inner.task(task_id).await
3092+ }
3093+
3094+ async fn columns_for_board(
3095+ &self,
3096+ board_id: &str,
3097+ ) -> Result<Vec<izlek_core::Column>, StoreError> {
3098+ self.tick();
3099+ self.inner.columns_for_board(board_id).await
3100+ }
3101+
3102+ async fn assignees_for_task(&self, task_id: &str) -> Result<Vec<Person>, StoreError> {
3103+ self.tick();
3104+ self.inner.assignees_for_task(task_id).await
3105+ }
3106+
3107+ async fn assignable_people(&self, workspace_id: &str) -> Result<Vec<Person>, StoreError> {
3108+ self.tick();
3109+ self.inner.assignable_people(workspace_id).await
3110+ }
3111+
3112+ async fn dependencies_for_task(
3113+ &self,
3114+ task_id: &str,
3115+ ) -> Result<Vec<(bool, DependencyEdge)>, StoreError> {
3116+ self.tick();
3117+ self.inner.dependencies_for_task(task_id).await
3118+ }
3119+
3120+ async fn comments_for_task(&self, task_id: &str) -> Result<Vec<Comment>, StoreError> {
3121+ self.tick();
3122+ self.inner.comments_for_task(task_id).await
3123+ }
3124+
3125+ async fn files_for_task(
3126+ &self,
3127+ task_id: &str,
3128+ ) -> Result<Vec<izlek_core::detail::FileLine>, StoreError> {
3129+ self.tick();
3130+ self.inner.files_for_task(task_id).await
3131+ }
3132+
3133+ async fn activity_for_task(&self, task_id: &str) -> Result<Vec<ActivityEntry>, StoreError> {
3134+ self.tick();
3135+ self.inner.activity_for_task(task_id).await
3136+ }
27243137
27253138 async fn family_for_task(
27263139 &self,
@@ -2830,7 +3243,6 @@ async fn a_dependency_that_would_close_a_circle_is_refused() {
28303243 Err(StoreError::Cycle)
28313244 ));
28323245
2833- // The refusal wrote nothing.
28343246 let detail = load_detail(store, &workspace, &c).await.unwrap().unwrap();
28353247 assert!(detail.blocked_by.is_empty());
28363248 }
@@ -2987,7 +3399,11 @@ async fn saving_a_task_records_only_what_changed() {
29873399 )
29883400 .await
29893401 .unwrap();
2990- assert_eq!(ids, Vec::<String>::new(), "a save that changed nothing writes nothing");
3402+ assert_eq!(
3403+ ids,
3404+ Vec::<String>::new(),
3405+ "a save that changed nothing writes nothing"
3406+ );
29913407 let detail = load_detail(store, &workspace, &task)
29923408 .await
29933409 .unwrap()
@@ -3078,6 +3494,7 @@ async fn a_task_detail_costs_nine_queries_whatever_it_carries() {
30783494 .record_activity(
30793495 &heavy,
30803496 Some(&person.id),
3497+ None,
30813498 &ActivityKind::Moved,
30823499 "to Review",
30833500 now,
@@ -3104,10 +3521,7 @@ async fn a_task_detail_costs_nine_queries_whatever_it_carries() {
31043521 assert_eq!(detail.subtasks.len(), 20);
31053522 assert!(detail.parent.is_none());
31063523 assert!(
3107- detail
3108- .subtasks
3109- .iter()
3110- .all(|part| part.assignees.len() == 1),
3524+ detail.subtasks.iter().all(|part| part.assignees.len() == 1),
31113525 "a subtask row carries who holds it"
31123526 );
31133527 // Twenty comments (each its own Commented line), twenty moves, plus the
@@ -3561,7 +3975,7 @@ async fn a_rule_is_one_sentence_and_starts_live() {
35613975 "You can start now",
35623976 Audience::Assignees,
35633977 OffsetDateTime::now_utc(),
3564- false,
3978+ false,
35653979 )
35663980 .await
35673981 .expect("an unblocked rule is whole without a column");
@@ -3924,7 +4338,7 @@ async fn deleting_a_rule_takes_its_ledger_with_it() {
39244338
39254339 // -- the engine ------------------------------------------------------------
39264340
3927-use izlek_core::mail::{Engine, MailError, Mailer, Outgoing, backoff};
4341+use izlek_core::mail::{Engine, MailError, Mailer, Outgoing, Report, backoff};
39284342 use std::sync::Mutex;
39294343
39304344 /// A mail server that remembers instead of sending, and refuses when told to.
@@ -3965,8 +4379,16 @@ impl Mailer for Remembering {
39654379 }
39664380 }
39674381
3968-/// A store shared between the tests and an engine.
4382+/// A store shared between the tests and an engine, with no quiet window: a
4383+/// trigger is a mail, sent the moment it is owed. That is what every test
4384+/// below the batching ones is about, and it is what `mail_batch_minutes = 0`
4385+/// means. The batching tests open theirs with `waiting`.
39694386 async fn shared() -> (PathBuf, Arc<TursoStore>, String, String) {
4387+ waiting(0).await
4388+}
4389+
4390+/// The same, with a quiet window of `minutes` on the workspace.
4391+async fn waiting(minutes: u32) -> (PathBuf, Arc<TursoStore>, String, String) {
39704392 let dir = std::env::temp_dir().join(format!("izlek-test-{}", Ulid::new()));
39714393 std::fs::create_dir_all(&dir).unwrap();
39724394 let store = Arc::new(
@@ -3975,6 +4397,17 @@ async fn shared() -> (PathBuf, Arc<TursoStore>, String, String) {
39754397 .unwrap(),
39764398 );
39774399 let (workspace, admin) = claim(&store).await;
4400+ let limits = store.workspace().await.unwrap().unwrap();
4401+ store
4402+ .set_limits(
4403+ &workspace,
4404+ limits.attachment_limit_bytes,
4405+ limits.photo_limit_bytes,
4406+ &limits.allowed_file_types,
4407+ minutes,
4408+ )
4409+ .await
4410+ .unwrap();
39784411 (dir, store, workspace, admin)
39794412 }
39804413
@@ -4293,7 +4726,7 @@ async fn you_can_start_now_waits_for_the_last_blocker() {
42934726 "You can start now",
42944727 Audience::Assignees,
42954728 now,
4296- false,
4729+ false,
42974730 )
42984731 .await
42994732 .unwrap();
@@ -4365,7 +4798,7 @@ async fn a_deleted_blocker_also_says_you_can_start_now() {
43654798 "You can start now",
43664799 Audience::Assignees,
43674800 now,
4368- false,
4801+ false,
43694802 )
43704803 .await
43714804 .unwrap();
@@ -4431,7 +4864,7 @@ async fn a_delete_that_leaves_somebody_still_waiting_mails_nobody() {
44314864 "You can start now",
44324865 Audience::Assignees,
44334866 now,
4434- false,
4867+ false,
44354868 )
44364869 .await
44374870 .unwrap();
@@ -4478,7 +4911,7 @@ async fn a_mail_owed_by_a_delete_is_rebuilt_from_the_delete_on_a_retry() {
44784911 "You can start now",
44794912 Audience::Assignees,
44804913 now,
4481- false,
4914+ false,
44824915 )
44834916 .await
44844917 .unwrap();
@@ -4551,7 +4984,10 @@ async fn a_rule_that_owed_nobody_still_says_so() {
45514984 let transition = moved_to(&store, &workspace, &task, "Backlog", "Done", &mate).await;
45524985 engine.on_transition(&transition).await.unwrap();
45534986
4554- let decisions = store.recent_mail_decisions(10, izlek_core::store::FeedPage::Newest).await.unwrap();
4987+ let decisions = store
4988+ .recent_mail_decisions(10, izlek_core::store::FeedPage::Newest)
4989+ .await
4990+ .unwrap();
45554991 let row = decisions
45564992 .iter()
45574993 .find(|d| d.rule_id == rule.id && d.task_id == task)
@@ -4573,7 +5009,10 @@ async fn a_rule_that_did_not_match_leaves_a_reason() {
45735009 let transition = moved_to(&store, &workspace, &task, "Backlog", "Review", &admin).await;
45745010 engine.on_transition(&transition).await.unwrap();
45755011
4576- let decisions = store.recent_mail_decisions(10, izlek_core::store::FeedPage::Newest).await.unwrap();
5012+ let decisions = store
5013+ .recent_mail_decisions(10, izlek_core::store::FeedPage::Newest)
5014+ .await
5015+ .unwrap();
45775016 let row = decisions
45785017 .iter()
45795018 .find(|d| d.rule_id == rule.id && d.task_id == task)
@@ -4603,7 +5042,10 @@ async fn a_deleted_task_still_leaves_a_task_gone_row() {
46035042 assert_eq!(report, Default::default());
46045043 assert!(mailer.sent().is_empty());
46055044
4606- let decisions = store.recent_mail_decisions(10, izlek_core::store::FeedPage::Newest).await.unwrap();
5045+ let decisions = store
5046+ .recent_mail_decisions(10, izlek_core::store::FeedPage::Newest)
5047+ .await
5048+ .unwrap();
46075049 let row = decisions
46085050 .iter()
46095051 .find(|d| d.rule_id == rule.id && d.task_id == task)
@@ -4670,7 +5112,7 @@ async fn a_rule_round_trips_every_word_the_board_speaks() {
46705112 "A word the board speaks",
46715113 Audience::Assignees,
46725114 OffsetDateTime::now_utc(),
4673- false,
5115+ false,
46745116 )
46755117 .await
46765118 .unwrap();
@@ -4703,20 +5145,19 @@ async fn updating_a_rule_leaves_its_identity_and_ledger_alone() {
47035145 let now = OffsetDateTime::now_utc();
47045146 scratch
47055147 .store
4706- .record_mail_decision(
4707- &rule.id,
4708- &transition.id,
4709- &task,
4710- MailOutcome::Owed,
4711- "",
4712- now,
4713- )
5148+ .record_mail_decision(&rule.id, &transition.id, &task, MailOutcome::Owed, "", now)
47145149 .await
47155150 .unwrap();
47165151
47175152 scratch
47185153 .store
4719- .update_mail_rule(&rule.id, &Trigger::Unblocked, "New subject", Audience::Board, false)
5154+ .update_mail_rule(
5155+ &rule.id,
5156+ &Trigger::Unblocked,
5157+ "New subject",
5158+ Audience::Board,
5159+ false,
5160+ )
47205161 .await
47215162 .unwrap();
47225163
@@ -4728,7 +5169,11 @@ async fn updating_a_rule_leaves_its_identity_and_ledger_alone() {
47285169 assert_eq!(updated.enabled, rule.enabled);
47295170 assert_eq!(updated.created_at, rule.created_at);
47305171
4731- let decisions = scratch.store.recent_mail_decisions(10, izlek_core::store::FeedPage::Newest).await.unwrap();
5172+ let decisions = scratch
5173+ .store
5174+ .recent_mail_decisions(10, izlek_core::store::FeedPage::Newest)
5175+ .await
5176+ .unwrap();
47325177 assert!(
47335178 decisions.iter().any(|d| d.rule_id == rule.id),
47345179 "the pre-existing decision no longer joins to the rule"
@@ -4778,7 +5223,10 @@ async fn a_rules_creator_audience_names_who_opened_the_card() {
47785223 .await
47795224 .unwrap();
47805225 assert_eq!(
4781- creators.iter().map(|p| p.user_id.as_str()).collect::<Vec<_>>(),
5226+ creators
5227+ .iter()
5228+ .map(|p| p.user_id.as_str())
5229+ .collect::<Vec<_>>(),
47825230 [admin.as_str()]
47835231 );
47845232
@@ -4839,7 +5287,9 @@ async fn a_file_goes_into_the_database_file_and_comes_back_byte_for_byte() {
48395287
48405288 // Bytes that are not text and are not valid UTF-8, because an attachment
48415289 // is not a string and the column it lives in must not treat it as one.
4842- let bytes: Vec<u8> = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a, 0xff, 0x00, 0xfe];
5290+ let bytes: Vec<u8> = vec![
5291+ 0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a, 0xff, 0x00, 0xfe,
5292+ ];
48435293 let id = store
48445294 .add_attachment(NewAttachment {
48455295 task_id: &task,
@@ -5006,7 +5456,14 @@ async fn the_queue_shows_what_is_owed_and_not_what_is_done() {
50065456 let now = OffsetDateTime::now_utc();
50075457
50085458 let pending = store
5009- .claim_send(&rule.id, &transition.id, &task, "pending@izlek.sh", now, now)
5459+ .claim_send(
5460+ &rule.id,
5461+ &transition.id,
5462+ &task,
5463+ "pending@izlek.sh",
5464+ now,
5465+ now,
5466+ )
50105467 .await
50115468 .unwrap()
50125469 .unwrap();
@@ -5029,7 +5486,14 @@ async fn the_queue_shows_what_is_owed_and_not_what_is_done() {
50295486 store.record_send_accepted(&sent.id, now).await.unwrap();
50305487
50315488 let abandoned = store
5032- .claim_send(&rule.id, &transition.id, &task, "abandoned@izlek.sh", now, now)
5489+ .claim_send(
5490+ &rule.id,
5491+ &transition.id,
5492+ &task,
5493+ "abandoned@izlek.sh",
5494+ now,
5495+ now,
5496+ )
50335497 .await
50345498 .unwrap()
50355499 .unwrap();
@@ -5038,7 +5502,10 @@ async fn the_queue_shows_what_is_owed_and_not_what_is_done() {
50385502 .await
50395503 .unwrap();
50405504
5041- let queue = store.mail_queue(10, izlek_core::store::FeedPage::Newest).await.unwrap();
5505+ let queue = store
5506+ .mail_queue(10, izlek_core::store::FeedPage::Newest)
5507+ .await
5508+ .unwrap();
50425509 let ids: Vec<&str> = queue.iter().map(|s| s.id.as_str()).collect();
50435510 assert!(ids.contains(&pending.id.as_str()));
50445511 assert!(ids.contains(&failed.id.as_str()));
@@ -5063,7 +5530,10 @@ async fn an_invite_mail_is_owed_without_a_rule() {
50635530 let found = owed.iter().find(|s| s.id == invite.id).unwrap();
50645531 assert_eq!(found.rule_id, None);
50655532
5066- let queue = store.mail_queue(10, izlek_core::store::FeedPage::Newest).await.unwrap();
5533+ let queue = store
5534+ .mail_queue(10, izlek_core::store::FeedPage::Newest)
5535+ .await
5536+ .unwrap();
50675537 let found = queue.iter().find(|s| s.id == invite.id).unwrap();
50685538 assert_eq!(found.rule_id, None);
50695539 }
@@ -5083,7 +5553,10 @@ async fn an_invite_mail_with_no_sender_is_held_not_failed() {
50835553 assert_eq!(report.held, 1);
50845554 assert_eq!(report.sent, 0);
50855555
5086- let queue = store.mail_queue(10, izlek_core::store::FeedPage::Newest).await.unwrap();
5556+ let queue = store
5557+ .mail_queue(10, izlek_core::store::FeedPage::Newest)
5558+ .await
5559+ .unwrap();
50875560 let held = queue
50885561 .iter()
50895562 .find(|s| s.recipient == "newcomer@izlek.sh")
@@ -5128,10 +5601,7 @@ async fn two_passes_over_one_owed_mail_send_it_once() {
51285601 // request's pass and the sweep's.
51295602 let request = Engine::new(store.clone(), mailer.clone(), "https://izlek.sh");
51305603 let sweep = Engine::new(store.clone(), mailer.clone(), "https://izlek.sh");
5131- let (a, b) = tokio::join!(
5132- request.deliver_owed(now, 10),
5133- sweep.deliver_owed(now, 10),
5134- );
5604+ let (a, b) = tokio::join!(request.deliver_owed(now, 10), sweep.deliver_owed(now, 10),);
51355605 let (a, b) = (a.unwrap(), b.unwrap());
51365606
51375607 let sent = mailer.sent.lock().unwrap().len();
@@ -5249,13 +5719,14 @@ async fn the_activity_feed_is_the_whole_workspace_newest_first() {
52495719 let t0 = OffsetDateTime::now_utc();
52505720
52515721 store
5252- .record_activity(&task_a, Some(&admin), &ActivityKind::Created, "", t0)
5722+ .record_activity(&task_a, Some(&admin), None, &ActivityKind::Created, "", t0)
52535723 .await
52545724 .unwrap();
52555725 store
52565726 .record_activity(
52575727 &task_b,
52585728 Some(&other),
5729+ None,
52595730 &ActivityKind::Retitled,
52605731 "new title",
52615732 t0 + Duration::seconds(1),
@@ -5263,7 +5734,15 @@ async fn the_activity_feed_is_the_whole_workspace_newest_first() {
52635734 .await
52645735 .unwrap();
52655736
5266- let feed = store.recent_activity(10, izlek_core::store::FeedPage::Newest, izlek_core::store::Dir::Newest, &izlek_core::store::ActivityFilter::default()).await.unwrap();
5737+ let feed = store
5738+ .recent_activity(
5739+ 10,
5740+ izlek_core::store::FeedPage::Newest,
5741+ izlek_core::store::Dir::Newest,
5742+ &izlek_core::store::ActivityFilter::default(),
5743+ )
5744+ .await
5745+ .unwrap();
52675746 // Two "created" lines came free with the two tasks; the two just recorded
52685747 // sit newest first, ahead of both of those.
52695748 assert_eq!(feed.len(), 4);
@@ -5299,13 +5778,29 @@ async fn keyset_paging_covers_every_activity_row_once() {
52995778 }
53005779 let _ = workspace;
53015780
5302- let whole = store.recent_activity(100, FeedPage::Newest, izlek_core::store::Dir::Newest, &izlek_core::store::ActivityFilter::default()).await.unwrap();
5781+ let whole = store
5782+ .recent_activity(
5783+ 100,
5784+ FeedPage::Newest,
5785+ izlek_core::store::Dir::Newest,
5786+ &izlek_core::store::ActivityFilter::default(),
5787+ )
5788+ .await
5789+ .unwrap();
53035790 assert_eq!(whole.len(), 23);
53045791
53055792 let mut walked = Vec::new();
53065793 let mut page = FeedPage::Newest;
53075794 loop {
5308- let rows = store.recent_activity(7, page, izlek_core::store::Dir::Newest, &izlek_core::store::ActivityFilter::default()).await.unwrap();
5795+ let rows = store
5796+ .recent_activity(
5797+ 7,
5798+ page,
5799+ izlek_core::store::Dir::Newest,
5800+ &izlek_core::store::ActivityFilter::default(),
5801+ )
5802+ .await
5803+ .unwrap();
53095804 if rows.is_empty() {
53105805 break;
53115806 }
@@ -5329,7 +5824,7 @@ async fn an_account_event_rides_the_feed_without_a_task() {
53295824 let t0 = OffsetDateTime::now_utc();
53305825
53315826 store
5332- .record_activity(&task, Some(&admin), &ActivityKind::Created, "", t0)
5827+ .record_activity(&task, Some(&admin), None, &ActivityKind::Created, "", t0)
53335828 .await
53345829 .unwrap();
53355830 store
@@ -5342,7 +5837,15 @@ async fn an_account_event_rides_the_feed_without_a_task() {
53425837 .await
53435838 .unwrap();
53445839
5345- let feed = store.recent_activity(10, izlek_core::store::FeedPage::Newest, izlek_core::store::Dir::Newest, &izlek_core::store::ActivityFilter::default()).await.unwrap();
5840+ let feed = store
5841+ .recent_activity(
5842+ 10,
5843+ izlek_core::store::FeedPage::Newest,
5844+ izlek_core::store::Dir::Newest,
5845+ &izlek_core::store::ActivityFilter::default(),
5846+ )
5847+ .await
5848+ .unwrap();
53465849 // The sign-in sits newest with no task on it; the task's own lines below
53475850 // still name theirs.
53485851 assert_eq!(feed[0].kind, ActivityKind::SignedIn);
@@ -5440,7 +5943,7 @@ async fn an_assignment_mails_the_assignees_minus_the_actor() {
54405943 "You were assigned",
54415944 Audience::Assignees,
54425945 OffsetDateTime::now_utc(),
5443- false,
5946+ false,
54445947 )
54455948 .await
54465949 .unwrap();
@@ -5453,6 +5956,7 @@ async fn an_assignment_mails_the_assignees_minus_the_actor() {
54535956 .record_activity(
54545957 &task,
54555958 Some(&admin),
5959+ None,
54565960 &ActivityKind::Assigned,
54575961 "Emre",
54585962 OffsetDateTime::now_utc(),
@@ -5477,31 +5981,175 @@ async fn an_assignment_mails_the_assignees_minus_the_actor() {
54775981 }
54785982
54795983 #[tokio::test]
5480-async fn a_creator_audience_rule_mails_the_creator_and_nobody_when_the_creator_commented() {
5984+async fn assigning_one_person_mails_that_person_not_every_assignee() {
54815985 let (dir, store, workspace, admin) = shared().await;
5482- let mate = member(&store, &workspace, "emre@izlek.sh", "Emre").await;
5986+ let first = member(&store, &workspace, "grace@izlek.sh", "Grace").await;
5987+ let second = member(&store, &workspace, "emre@izlek.sh", "Emre").await;
5988+ let third = member(&store, &workspace, "linus@izlek.sh", "Linus").await;
54835989 let task = add_task(&store, &workspace, "Backlog", "Ship it", None, &admin).await;
5990+ store.assign_task(&task, &first).await.unwrap();
5991+ store.assign_task(&task, &second).await.unwrap();
5992+ store.assign_task(&task, &third).await.unwrap();
54845993 let board = store.board(&workspace).await.unwrap().unwrap();
54855994 store
54865995 .create_mail_rule(
54875996 &board.id,
5488- &Trigger::Commented,
5489- "A comment landed",
5490- Audience::Creator,
5997+ &Trigger::Assigned,
5998+ "You were assigned",
5999+ Audience::Assignees,
54916000 OffsetDateTime::now_utc(),
5492- false,
6001+ false,
54936002 )
54946003 .await
54956004 .unwrap();
54966005
54976006 let mailer = Remembering::taking_everything();
54986007 let engine = Engine::new(store.clone(), mailer.clone(), "https://izlek.sh");
5499-
6008+ // Ada assigns Yusuf to a card that already carries three people: the line
6009+ // is about Yusuf, so Yusuf is the audience — not the three already there.
6010+ let fourth = member(&store, &workspace, "yusuf@izlek.sh", "Yusuf").await;
6011+ let activity_id = store
6012+ .record_activity(
6013+ &task,
6014+ Some(&admin),
6015+ Some(&fourth),
6016+ &ActivityKind::Assigned,
6017+ "Yusuf",
6018+ OffsetDateTime::now_utc(),
6019+ )
6020+ .await
6021+ .unwrap();
6022+ let event = activity_event(&store, &activity_id).await;
6023+
6024+ let report = engine.on_activity(&event).await.unwrap();
6025+ assert_eq!(report.sent, 1, "one assignment, one mail");
6026+ let sent = mailer.sent();
6027+ assert_eq!(sent.len(), 1);
6028+ assert_eq!(sent[0].to, "yusuf@izlek.sh");
6029+ let _ = std::fs::remove_dir_all(&dir);
6030+}
6031+
6032+#[tokio::test]
6033+async fn an_unassignment_mails_the_person_removed_not_the_rest() {
6034+ let (dir, store, workspace, admin) = shared().await;
6035+ let staying = member(&store, &workspace, "grace@izlek.sh", "Grace").await;
6036+ let leaving = member(&store, &workspace, "emre@izlek.sh", "Emre").await;
6037+ let task = add_task(&store, &workspace, "Backlog", "Ship it", None, &admin).await;
6038+ store.assign_task(&task, &staying).await.unwrap();
6039+ store.assign_task(&task, &leaving).await.unwrap();
6040+ let board = store.board(&workspace).await.unwrap().unwrap();
6041+ store
6042+ .create_mail_rule(
6043+ &board.id,
6044+ &Trigger::Unassigned,
6045+ "You were unassigned",
6046+ Audience::Assignees,
6047+ OffsetDateTime::now_utc(),
6048+ false,
6049+ )
6050+ .await
6051+ .unwrap();
6052+
6053+ let mailer = Remembering::taking_everything();
6054+ let engine = Engine::new(store.clone(), mailer.clone(), "https://izlek.sh");
6055+ store.unassign_task(&task, &leaving).await.unwrap();
6056+ let activity_id = store
6057+ .record_activity(
6058+ &task,
6059+ Some(&admin),
6060+ Some(&leaving),
6061+ &ActivityKind::Unassigned,
6062+ "Emre",
6063+ OffsetDateTime::now_utc(),
6064+ )
6065+ .await
6066+ .unwrap();
6067+ let event = activity_event(&store, &activity_id).await;
6068+
6069+ let report = engine.on_activity(&event).await.unwrap();
6070+ assert_eq!(report.sent, 1, "one removal, one mail");
6071+ let sent = mailer.sent();
6072+ assert_eq!(sent.len(), 1);
6073+ assert_eq!(
6074+ sent[0].to, "emre@izlek.sh",
6075+ "the mail is for the one removed"
6076+ );
6077+ let _ = std::fs::remove_dir_all(&dir);
6078+}
6079+
6080+#[tokio::test]
6081+async fn a_rule_whose_line_has_no_subject_still_mails_every_assignee() {
6082+ let (dir, store, workspace, admin) = shared().await;
6083+ let first = member(&store, &workspace, "grace@izlek.sh", "Grace").await;
6084+ let second = member(&store, &workspace, "emre@izlek.sh", "Emre").await;
6085+ let task = add_task(&store, &workspace, "Backlog", "Ship it", None, &admin).await;
6086+ store.assign_task(&task, &first).await.unwrap();
6087+ store.assign_task(&task, &second).await.unwrap();
6088+ let board = store.board(&workspace).await.unwrap().unwrap();
6089+ store
6090+ .create_mail_rule(
6091+ &board.id,
6092+ &Trigger::Commented,
6093+ "There was movement",
6094+ Audience::Assignees,
6095+ OffsetDateTime::now_utc(),
6096+ false,
6097+ )
6098+ .await
6099+ .unwrap();
6100+
6101+ let mailer = Remembering::taking_everything();
6102+ let engine = Engine::new(store.clone(), mailer.clone(), "https://izlek.sh");
6103+ // A comment has no subject: the audience stays the whole assignee list,
6104+ // minus the actor, exactly as before the subject column existed.
6105+ let activity_id = store
6106+ .record_activity(
6107+ &task,
6108+ Some(&admin),
6109+ None,
6110+ &ActivityKind::Commented,
6111+ "",
6112+ OffsetDateTime::now_utc(),
6113+ )
6114+ .await
6115+ .unwrap();
6116+ let event = activity_event(&store, &activity_id).await;
6117+
6118+ let report = engine.on_activity(&event).await.unwrap();
6119+ assert_eq!(report.sent, 2, "both assignees, the old breadth");
6120+ let mut to: Vec<_> = mailer.sent().iter().map(|m| m.to.clone()).collect();
6121+ to.sort();
6122+ assert_eq!(to, vec!["emre@izlek.sh", "grace@izlek.sh"]);
6123+ let _ = std::fs::remove_dir_all(&dir);
6124+}
6125+
6126+#[tokio::test]
6127+async fn a_creator_audience_rule_mails_the_creator_and_nobody_when_the_creator_commented() {
6128+ let (dir, store, workspace, admin) = shared().await;
6129+ let mate = member(&store, &workspace, "emre@izlek.sh", "Emre").await;
6130+ let task = add_task(&store, &workspace, "Backlog", "Ship it", None, &admin).await;
6131+ let board = store.board(&workspace).await.unwrap().unwrap();
6132+ store
6133+ .create_mail_rule(
6134+ &board.id,
6135+ &Trigger::Commented,
6136+ "A comment landed",
6137+ Audience::Creator,
6138+ OffsetDateTime::now_utc(),
6139+ false,
6140+ )
6141+ .await
6142+ .unwrap();
6143+
6144+ let mailer = Remembering::taking_everything();
6145+ let engine = Engine::new(store.clone(), mailer.clone(), "https://izlek.sh");
6146+
55006147 // Emre comments on Ada's task: Ada, the creator, gets mailed.
55016148 let commented_by_mate = store
55026149 .record_activity(
55036150 &task,
55046151 Some(&mate),
6152+ None,
55056153 &ActivityKind::Commented,
55066154 "",
55076155 OffsetDateTime::now_utc(),
@@ -5521,6 +6169,7 @@ async fn a_creator_audience_rule_mails_the_creator_and_nobody_when_the_creator_c
55216169 .record_activity(
55226170 &task,
55236171 Some(&admin),
6172+ None,
55246173 &ActivityKind::Commented,
55256174 "",
55266175 OffsetDateTime::now_utc(),
@@ -5532,7 +6181,10 @@ async fn a_creator_audience_rule_mails_the_creator_and_nobody_when_the_creator_c
55326181 assert_eq!(report, Default::default());
55336182 assert_eq!(mailer.sent().len(), 1, "no second mail went out");
55346183
5535- let decisions = store.recent_mail_decisions(10, izlek_core::store::FeedPage::Newest).await.unwrap();
6184+ let decisions = store
6185+ .recent_mail_decisions(10, izlek_core::store::FeedPage::Newest)
6186+ .await
6187+ .unwrap();
55366188 let row = decisions
55376189 .iter()
55386190 .find(|d| d.event_id == commented_by_creator)
@@ -5554,6 +6206,7 @@ async fn a_created_activity_does_not_fire_a_status_rule() {
55546206 .record_activity(
55556207 &task,
55566208 Some(&admin),
6209+ None,
55576210 &ActivityKind::Created,
55586211 "",
55596212 OffsetDateTime::now_utc(),
@@ -5566,7 +6219,10 @@ async fn a_created_activity_does_not_fire_a_status_rule() {
55666219 assert_eq!(report, Default::default());
55676220 assert!(mailer.sent().is_empty());
55686221
5569- let decisions = store.recent_mail_decisions(10, izlek_core::store::FeedPage::Newest).await.unwrap();
6222+ let decisions = store
6223+ .recent_mail_decisions(10, izlek_core::store::FeedPage::Newest)
6224+ .await
6225+ .unwrap();
55706226 let row = decisions
55716227 .iter()
55726228 .find(|d| d.rule_id == rule.id && d.task_id == task)
@@ -5609,7 +6265,14 @@ async fn decisions_and_sends_for_task_read_only_that_tasks_own_rows() {
56096265 .unwrap()
56106266 .unwrap();
56116267 store
5612- .claim_send(&rule.id, &other_transition.id, &other_task, "emre@izlek.sh", now, now)
6268+ .claim_send(
6269+ &rule.id,
6270+ &other_transition.id,
6271+ &other_task,
6272+ "emre@izlek.sh",
6273+ now,
6274+ now,
6275+ )
56136276 .await
56146277 .unwrap();
56156278
@@ -5658,10 +6321,17 @@ async fn requeuing_a_send_puts_it_back_in_play_but_leaves_a_sent_one_alone() {
56586321 assert!(reread_failed.next_attempt_at.is_some_and(|at| at <= now));
56596322
56606323 let reread_sent = sends.iter().find(|s| s.id == sent.id).unwrap();
5661- assert_eq!(reread_sent.state, SendState::Sent, "a sent send is untouched");
6324+ assert_eq!(
6325+ reread_sent.state,
6326+ SendState::Sent,
6327+ "a sent send is untouched"
6328+ );
56626329
56636330 let owed = store.sends_owed(now, 10).await.unwrap();
5664- assert!(owed.iter().any(|s| s.id == failed.id), "the requeued send is now due");
6331+ assert!(
6332+ owed.iter().any(|s| s.id == failed.id),
6333+ "the requeued send is now due"
6334+ );
56656335 }
56666336
56676337 #[tokio::test]
@@ -5723,7 +6393,10 @@ async fn the_engine_delivers_a_notice_that_owes_no_rule() {
57236393 .sends_owed(now + Duration::hours(2), 10)
57246394 .await
57256395 .unwrap();
5726- assert!(owed.is_empty(), "a delivered notice is no longer owed: {owed:?}");
6396+ assert!(
6397+ owed.is_empty(),
6398+ "a delivered notice is no longer owed: {owed:?}"
6399+ );
57276400 std::fs::remove_dir_all(dir).ok();
57286401 }
57296402
@@ -5750,8 +6423,16 @@ async fn a_tasks_activity_reads_newest_first() {
57506423 );
57516424 // Creation is the oldest thing that ever happens to a task, so it is last
57526425 // now; a comment — the most recent act here — leads.
5753- assert_eq!(activity.first().map(|line| line.kind.clone()), Some(ActivityKind::Commented), "{activity:?}");
5754- assert_eq!(activity.last().map(|line| line.kind.clone()), Some(ActivityKind::Created), "{activity:?}");
6426+ assert_eq!(
6427+ activity.first().map(|line| line.kind.clone()),
6428+ Some(ActivityKind::Commented),
6429+ "{activity:?}"
6430+ );
6431+ assert_eq!(
6432+ activity.last().map(|line| line.kind.clone()),
6433+ Some(ActivityKind::Created),
6434+ "{activity:?}"
6435+ );
57556436 }
57566437
57576438 /// A status rule with no column watches the whole board: every crossing fires
@@ -5786,7 +6467,9 @@ async fn a_status_rule_with_no_column_fires_on_every_crossing() {
57866467
57876468 let sent = mailer.sent();
57886469 assert_eq!(
5789- sent.iter().filter(|mail| mail.subject == "It moved").count(),
6470+ sent.iter()
6471+ .filter(|mail| mail.subject == "It moved")
6472+ .count(),
57906473 2,
57916474 "both crossings fired the every-column rule: {sent:?}"
57926475 );
@@ -5942,7 +6625,9 @@ async fn every_kind_of_write_announces_its_surface() {
59426625 .unwrap();
59436626
59446627 let seen = announced(&mut rx);
5945- for topic in ["board", "task", "members", "queue", "rules", "settings", "activity"] {
6628+ for topic in [
6629+ "board", "task", "members", "queue", "rules", "settings", "activity",
6630+ ] {
59466631 assert!(
59476632 seen.iter().any(|k| k == topic),
59486633 "no {topic} announcement; heard {seen:?}"
@@ -6056,7 +6741,12 @@ async fn the_next_due_moment_is_the_earliest_one() {
60566741 .await
60576742 .unwrap();
60586743 store
6059- .queue_notice("soon@izlek.sh", "Sooner", "body", now + Duration::minutes(5))
6744+ .queue_notice(
6745+ "soon@izlek.sh",
6746+ "Sooner",
6747+ "body",
6748+ now + Duration::minutes(5),
6749+ )
60606750 .await
60616751 .unwrap();
60626752
@@ -6085,21 +6775,32 @@ async fn a_sender_check_is_recorded_apart_from_a_test_and_cleared_on_edit() {
60856775 from_name: "İzlek".into(),
60866776 from_address: "izlek@izlek.sh".into(),
60876777 };
6088- store.set_sender(&workspace, sender("smtp.one.test")).await.unwrap();
6778+ store
6779+ .set_sender(&workspace, sender("smtp.one.test"))
6780+ .await
6781+ .unwrap();
60896782
60906783 // A login that worked, and a mail that did not: both true at once, and
60916784 // neither may be rendered as the other.
60926785 store
60936786 .record_sender_check(
60946787 &workspace,
6095- izlek_core::store::SenderCheck { at: now, took_ms: 120, error: None },
6788+ izlek_core::store::SenderCheck {
6789+ at: now,
6790+ took_ms: 120,
6791+ error: None,
6792+ },
60966793 )
60976794 .await
60986795 .unwrap();
60996796 store
61006797 .record_sender_test(
61016798 &workspace,
6102- izlek_core::store::SenderTest { at: now, took_ms: 0, error: Some("550 not allowed".into()) },
6799+ izlek_core::store::SenderTest {
6800+ at: now,
6801+ took_ms: 0,
6802+ error: Some("550 not allowed".into()),
6803+ },
61036804 )
61046805 .await
61056806 .unwrap();
@@ -6115,8 +6816,850 @@ async fn a_sender_check_is_recorded_apart_from_a_test_and_cleared_on_edit() {
61156816 );
61166817
61176818 // Point it at a different server: what was known is now about nothing.
6118- store.set_sender(&workspace, sender("smtp.two.test")).await.unwrap();
6819+ store
6820+ .set_sender(&workspace, sender("smtp.two.test"))
6821+ .await
6822+ .unwrap();
61196823 let ws = store.workspace().await.unwrap().unwrap();
6120- assert!(ws.sender_check.is_none(), "a stale handshake survived an edit");
6824+ assert!(
6825+ ws.sender_check.is_none(),
6826+ "a stale handshake survived an edit"
6827+ );
61216828 assert!(ws.sender_test.is_none(), "a stale test survived an edit");
61226829 }
6830+
6831+// ---------------------------------------------------------------------------
6832+// izlek reconcile — bringing a database of the OLD shape onto the declared
6833+// schema. These tests carry the user's rule (2026-08-31): a table alteration
6834+// owes both a proof that the alteration holds and a proof that reconcile
6835+// carries a live-shaped database across it.
6836+// ---------------------------------------------------------------------------
6837+
6838+/// Builds a database at the PRE-COLLAPSE schema — the shape İzlek was actually
6839+/// deployed with, kept verbatim in `tests/fixtures/` — and fills it with the
6840+/// kinds of row a live workspace holds, blobs included.
6841+async fn live_shaped_database() -> (PathBuf, String) {
6842+ let dir = std::env::temp_dir().join(format!("izlek-reconcile-{}", Ulid::new()));
6843+ std::fs::create_dir_all(&dir).unwrap();
6844+ let path = dir.join("izlek.db").to_str().unwrap().to_string();
6845+
6846+ let db = turso::Builder::new_local(&path).build().await.unwrap();
6847+ let conn = db.connect().unwrap();
6848+ conn.execute("PRAGMA foreign_keys = ON", ()).await.unwrap();
6849+ conn.execute_batch(include_str!("fixtures/pre-collapse/0001_init.sql"))
6850+ .await
6851+ .unwrap();
6852+ conn.execute_batch(include_str!("fixtures/pre-collapse/0002_sender_check.sql"))
6853+ .await
6854+ .unwrap();
6855+
6856+ let now = "2026-08-30T12:00:00Z";
6857+ let mut sql = String::new();
6858+ sql.push_str(&format!(
6859+ "INSERT INTO workspace (id, name, created_at) VALUES ('W1', 'Dizey', '{now}');"
6860+ ));
6861+ for (id, email, name) in [
6862+ ("U1", "one@example.com", "One"),
6863+ ("U2", "two@example.com", "Two"),
6864+ ] {
6865+ sql.push_str(&format!(
6866+ "INSERT INTO user (id, workspace_id, email, display_name, role, created_at) \
6867+ VALUES ('{id}', 'W1', '{email}', '{name}', 'member', '{now}');"
6868+ ));
6869+ }
6870+ sql.push_str(&format!(
6871+ "INSERT INTO workspace_owner (singleton, user_id, claimed_at) VALUES (1, 'U1', '{now}');"
6872+ ));
6873+ // Two boards, so a task landing on the WRONG board's default tag is
6874+ // visible rather than accidentally correct.
6875+ for b in ["B1", "B2"] {
6876+ sql.push_str(&format!(
6877+ "INSERT INTO board (id, workspace_id, name, created_at) VALUES ('{b}', 'W1', '{b}', '{now}');"
6878+ ));
6879+ sql.push_str(&format!(
6880+ "INSERT INTO board_column (id, board_id, name, position, is_done) \
6881+ VALUES ('C{b}', '{b}', 'Backlog', 0, 0);"
6882+ ));
6883+ }
6884+ for (t, b) in [("T1", "B1"), ("T2", "B1"), ("T3", "B2")] {
6885+ sql.push_str(&format!(
6886+ "INSERT INTO task (id, board_id, task_key, title, column_id, created_by, created_at, updated_at) \
6887+ VALUES ('{t}', '{b}', '{t}', 'a task', 'C{b}', 'U1', '{now}', '{now}');"
6888+ ));
6889+ sql.push_str(&format!(
6890+ "INSERT INTO task_assignee (task_id, user_id) VALUES ('{t}', 'U2');"
6891+ ));
6892+ sql.push_str(&format!(
6893+ "INSERT INTO activity (id, task_id, actor_id, kind, detail, created_at) \
6894+ VALUES ('A{t}', '{t}', 'U1', 'created', '', '{now}');"
6895+ ));
6896+ }
6897+ // A soft-deleted task still belongs to a tag afterwards.
6898+ sql.push_str(&format!(
6899+ "INSERT INTO task (id, board_id, task_key, title, column_id, created_by, created_at, updated_at, deleted_at) \
6900+ VALUES ('T4', 'B2', 'T4', 'gone', 'CB2', 'U1', '{now}', '{now}', '{now}');"
6901+ ));
6902+ conn.execute_batch(&sql).await.unwrap();
6903+
6904+ // A blob, because an attachment that survives as NULL would pass a row
6905+ // count and lose the user's file.
6906+ let bytes: Vec<u8> = (0u8..=255).cycle().take(5000).collect();
6907+ conn.execute(
6908+ "INSERT INTO attachment (id, task_id, file_name, mime_type, size_bytes, bytes, uploaded_by, created_at) \
6909+ VALUES ('F1', 'T1', 'a.bin', 'application/octet-stream', ?1, ?2, 'U1', ?3)",
6910+ turso::params![bytes.len() as i64, bytes.clone(), now],
6911+ )
6912+ .await
6913+ .unwrap();
6914+
6915+ (dir, path)
6916+}
6917+
6918+async fn scalar(path: &str, sql: &str) -> i64 {
6919+ let db = turso::Builder::new_local(path).build().await.unwrap();
6920+ let conn = db.connect().unwrap();
6921+ let mut rows = conn.query(sql, ()).await.unwrap();
6922+ rows.next().await.unwrap().unwrap().get::<i64>(0).unwrap()
6923+}
6924+
6925+fn backups_beside(dir: &PathBuf) -> Vec<String> {
6926+ let mut found: Vec<String> = std::fs::read_dir(dir)
6927+ .unwrap()
6928+ .filter_map(|e| e.ok())
6929+ .map(|e| e.file_name().to_string_lossy().to_string())
6930+ .filter(|n| n.contains(".backup-") && !n.ends_with("-wal") && !n.ends_with("-shm"))
6931+ .collect();
6932+ found.sort();
6933+ found
6934+}
6935+
6936+#[tokio::test]
6937+async fn reconcile_carries_a_live_shaped_database_onto_the_declared_schema() {
6938+ let (dir, path) = live_shaped_database().await;
6939+
6940+ izlek_core::store::reconcile(
6941+ &path,
6942+ izlek_core::store::ReconcileOptions {
6943+ dry_run: false,
6944+ yes: true,
6945+ auto: true,
6946+ },
6947+ )
6948+ .await
6949+ .expect("reconcile refused a database of the shape we actually deployed");
6950+
6951+ let db = turso::Builder::new_local(&path).build().await.unwrap();
6952+ let conn = db.connect().unwrap();
6953+
6954+ // The schema is now the declared one, exactly.
6955+ let after = izlek_core::store::schema::fingerprint(&conn).await.unwrap();
6956+ let declared = izlek_core::store::schema::declared_fingerprint().await.unwrap();
6957+ assert_eq!(after, declared, "the rebuilt schema is not the declared one");
6958+
6959+ // Nothing was dropped on the floor.
6960+ assert_eq!(scalar(&path, "SELECT COUNT(*) FROM user").await, 2);
6961+ assert_eq!(scalar(&path, "SELECT COUNT(*) FROM board").await, 2);
6962+ assert_eq!(scalar(&path, "SELECT COUNT(*) FROM task").await, 4);
6963+ assert_eq!(scalar(&path, "SELECT COUNT(*) FROM task_assignee").await, 3);
6964+ assert_eq!(scalar(&path, "SELECT COUNT(*) FROM activity").await, 3);
6965+
6966+ // Every task wears its OWN board's default tag — the step no schema diff
6967+ // could have derived.
6968+ assert_eq!(
6969+ scalar(&path, "SELECT COUNT(*) FROM task WHERE tag_id IS NULL").await,
6970+ 0,
6971+ "a task came out of the rebuild with no tag"
6972+ );
6973+ assert_eq!(
6974+ scalar(
6975+ &path,
6976+ "SELECT COUNT(*) FROM task t JOIN tag g ON g.id = t.tag_id \
6977+ WHERE g.board_id = t.board_id AND g.is_default = 1",
6978+ )
6979+ .await,
6980+ 4,
6981+ "a task was given another board's tag"
6982+ );
6983+ assert_eq!(
6984+ scalar(&path, "SELECT COUNT(*) FROM tag").await,
6985+ 2,
6986+ "each board owes exactly one default tag"
6987+ );
6988+
6989+ // The blob survived byte for byte.
6990+ assert_eq!(
6991+ scalar(&path, "SELECT length(bytes) FROM attachment WHERE id = 'F1'").await,
6992+ 5000
6993+ );
6994+ assert_eq!(
6995+ scalar(
6996+ &path,
6997+ "SELECT COUNT(*) FROM attachment WHERE id = 'F1' AND hex(substr(bytes, 1, 4)) = '00010203'",
6998+ )
6999+ .await,
7000+ 1,
7001+ "the attachment's bytes changed in the rebuild"
7002+ );
7003+
7004+ // The quiet window is a column the old shape never had: a workspace that
7005+ // crosses over gets the declared default rather than a NULL the app would
7006+ // have to read around.
7007+ assert_eq!(
7008+ scalar(&path, "SELECT mail_batch_minutes FROM workspace WHERE id = 'W1'").await,
7009+ 5,
7010+ "the workspace came across without a quiet window"
7011+ );
7012+
7013+ // And the references all still point at something.
7014+ let mut broken = conn.query("PRAGMA foreign_key_check", ()).await.unwrap();
7015+ assert!(
7016+ broken.next().await.unwrap().is_none(),
7017+ "the rebuilt database has dangling references"
7018+ );
7019+
7020+ // The original is beside it, still holding the old shape.
7021+ let backups = backups_beside(&dir);
7022+ assert_eq!(backups.len(), 1, "the rebuild did not keep a backup");
7023+ let backup = dir.join(&backups[0]).to_str().unwrap().to_string();
7024+ assert_eq!(
7025+ scalar(
7026+ &backup,
7027+ "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'tag'",
7028+ )
7029+ .await,
7030+ 0,
7031+ "the backup is not the old-shaped database we started from"
7032+ );
7033+ assert_eq!(
7034+ scalar(&backup, "SELECT COUNT(*) FROM task").await,
7035+ 4,
7036+ "the backup lost rows"
7037+ );
7038+
7039+ let _ = std::fs::remove_dir_all(&dir);
7040+}
7041+
7042+#[tokio::test]
7043+async fn reconciling_a_database_that_already_matches_changes_nothing() {
7044+ let scratch = Scratch::open().await;
7045+ let path = scratch.dir.join("izlek.db").to_str().unwrap().to_string();
7046+
7047+ izlek_core::store::reconcile(
7048+ &path,
7049+ izlek_core::store::ReconcileOptions {
7050+ dry_run: false,
7051+ yes: true,
7052+ auto: true,
7053+ },
7054+ )
7055+ .await
7056+ .expect("reconcile refused a current database");
7057+
7058+ assert!(
7059+ backups_beside(&scratch.dir).is_empty(),
7060+ "a database that needed nothing was backed up anyway"
7061+ );
7062+}
7063+
7064+#[tokio::test]
7065+async fn opening_a_stale_database_repairs_it() {
7066+ let (dir, path) = live_shaped_database().await;
7067+
7068+ // The boot path: no flag, no prompt — the store comes up on a database of
7069+ // the old shape, having repaired it on the way.
7070+ let store = TursoStore::open(&path)
7071+ .await
7072+ .expect("the store would not open a database it was supposed to repair");
7073+ drop(store);
7074+
7075+ let db = turso::Builder::new_local(&path).build().await.unwrap();
7076+ let conn = db.connect().unwrap();
7077+ assert_eq!(
7078+ izlek_core::store::schema::fingerprint(&conn).await.unwrap(),
7079+ izlek_core::store::schema::declared_fingerprint().await.unwrap(),
7080+ );
7081+ assert_eq!(scalar(&path, "SELECT COUNT(*) FROM task").await, 4);
7082+ assert_eq!(backups_beside(&dir).len(), 1);
7083+
7084+ // Opening it again finds it current and leaves it alone.
7085+ let store = TursoStore::open(&path).await.unwrap();
7086+ drop(store);
7087+ assert_eq!(
7088+ backups_beside(&dir).len(),
7089+ 1,
7090+ "a second open rebuilt a database that already matched"
7091+ );
7092+
7093+ let _ = std::fs::remove_dir_all(&dir);
7094+}
7095+
7096+#[tokio::test]
7097+async fn two_repairs_leave_two_backups() {
7098+ let (dir, path) = live_shaped_database().await;
7099+ let opts = || izlek_core::store::ReconcileOptions {
7100+ dry_run: false,
7101+ yes: true,
7102+ auto: true,
7103+ };
7104+
7105+ izlek_core::store::reconcile(&path, opts()).await.unwrap();
7106+ assert_eq!(backups_beside(&dir).len(), 1);
7107+
7108+ // Put the database back to the old shape and repair it again: the first
7109+ // backup must still be there. He keeps every one of them.
7110+ let db = turso::Builder::new_local(&path).build().await.unwrap();
7111+ let conn = db.connect().unwrap();
7112+ conn.execute("DROP TABLE tag_stub_check", ()).await.ok();
7113+ conn.execute("CREATE TABLE stray (id TEXT PRIMARY KEY)", ())
7114+ .await
7115+ .unwrap();
7116+ drop(conn);
7117+ drop(db);
7118+
7119+ izlek_core::store::reconcile(&path, opts()).await.unwrap();
7120+ let backups = backups_beside(&dir);
7121+ assert_eq!(
7122+ backups.len(),
7123+ 2,
7124+ "the second repair overwrote the first backup: {backups:?}"
7125+ );
7126+
7127+ let _ = std::fs::remove_dir_all(&dir);
7128+}
7129+/// The other half of the alteration: a database that ALREADY carries the
7130+/// quiet window keeps the number its admin set, rather than being handed the
7131+/// default a fresh workspace gets.
7132+#[tokio::test]
7133+async fn a_rebuild_keeps_a_window_the_admin_already_set() {
7134+ let scratch = Scratch::open().await;
7135+ let path = scratch.dir.join("izlek.db").to_str().unwrap().to_string();
7136+ let (workspace, _) = claim(&scratch.store).await;
7137+ let limits = scratch.store.workspace().await.unwrap().unwrap();
7138+ scratch
7139+ .store
7140+ .set_limits(
7141+ &workspace,
7142+ limits.attachment_limit_bytes,
7143+ limits.photo_limit_bytes,
7144+ &limits.allowed_file_types,
7145+ 17,
7146+ )
7147+ .await
7148+ .unwrap();
7149+
7150+ // Something the declared schema does not know about: enough to make the
7151+ // database stale, so the rebuild actually runs.
7152+ let db = turso::Builder::new_local(&path).build().await.unwrap();
7153+ let conn = db.connect().unwrap();
7154+ conn.execute("CREATE TABLE stray (id TEXT PRIMARY KEY)", ())
7155+ .await
7156+ .unwrap();
7157+ drop(conn);
7158+ drop(db);
7159+
7160+ izlek_core::store::reconcile(
7161+ &path,
7162+ izlek_core::store::ReconcileOptions {
7163+ dry_run: false,
7164+ yes: true,
7165+ auto: true,
7166+ },
7167+ )
7168+ .await
7169+ .unwrap();
7170+
7171+ assert_eq!(
7172+ scalar(&path, "SELECT mail_batch_minutes FROM workspace").await,
7173+ 17,
7174+ "the rebuild reset a window the admin had chosen"
7175+ );
7176+ assert_eq!(
7177+ scalar(
7178+ &path,
7179+ "SELECT COUNT(*) FROM sqlite_master WHERE name = 'stray'",
7180+ )
7181+ .await,
crates/izlek-web/src/board.rsmodified+48 -3
@@ -214,6 +214,11 @@ fn valid_sort(sort: Option<&str>) -> &'static str {
214214 _ => "deadline",
215215 }
216216 }
217+/// The `?tag=` filter: an id only counts while it names a tag on this
218+/// board — a stale or hand-edited query string falls back to all.
219+fn valid_tag(tag: Option<&str>, tags: &[izlek_core::store::Tag]) -> Option<String> {
220+ tag.and_then(|id| tags.iter().find(|t| t.id == id).map(|t| t.id.clone()))
221+}
217222
218223 /// `deadline` is the order [`izlek_core::board::load`] already hands back
219224 /// (soonest first); the other two re-order in place here so core stays free
@@ -228,7 +233,12 @@ fn sort_column_cards(cards: &mut [TaskCard], sort: &str) {
228233 }
229234
230235 /// The whole column list.
231-async fn board_columns(cx: &Cx, sort: String) -> Result {
236+async fn board_columns(
237+ cx: &Cx,
238+ sort: String,
239+ tag_filter: Option<String>,
240+ default_tag_id: Option<&str>,
241+) -> Result {
232242 let user = match require_user(cx).await {
233243 Ok(user) => user,
234244 Err(refusal) => {
@@ -251,6 +261,11 @@ async fn board_columns(cx: &Cx, sort: String) -> Result {
251261 };
252262 for column in &mut view_data.columns {
253263 sort_column_cards(&mut column.cards, &sort);
264+ if let Some(tag_id) = &tag_filter {
265+ column
266+ .cards
267+ .retain(|card| card.tag.as_ref().is_some_and(|tag| tag.id == *tag_id));
268+ }
254269 }
255270 let today = OffsetDateTime::now_utc().date();
256271 let may_write = user.role.can_write_tasks();
@@ -262,7 +277,7 @@ async fn board_columns(cx: &Cx, sort: String) -> Result {
262277 .collect();
263278 let mut columns = Vec::new();
264279 for column in view_data.columns {
265- columns.push(render_column(cx, column, today, may_write, &all_columns, lang).await?);
280+ columns.push(render_column(cx, column, today, may_write, &all_columns, default_tag_id, lang).await?);
266281 }
267282
268283 view! {
@@ -277,6 +292,7 @@ async fn render_column(
277292 today: Date,
278293 may_write: bool,
279294 all_columns: &[(String, String)],
295+ default_tag_id: Option<&str>,
280296 lang: Lang,
281297 ) -> Result {
282298 let column_id = column.column.id;
@@ -295,6 +311,7 @@ async fn render_column(
295311 &column_id,
296312 may_write,
297313 all_columns,
314+ default_tag_id,
298315 lang,
299316 )
300317 .await?,
@@ -327,6 +344,7 @@ async fn render_card(
327344 column_id: &str,
328345 may_write: bool,
329346 all_columns: &[(String, String)],
347+ default_tag_id: Option<&str>,
330348 lang: Lang,
331349 ) -> Result {
332350 let blocks = card.blocks.len();
@@ -381,6 +399,11 @@ async fn render_card(
381399 <span data-tick=(dated.then_some("")) class=(class!("card-deadline", "card-deadline-overdue" if overdue, "card-deadline-none" if !dated))>
382400 (deadline)
383401 </span>
402+ if let Some(tag) = &card.tag {
403+ if Some(tag.id.as_str()) != default_tag_id {
404+ <span class="card-tag">(tag.name.clone())</span>
405+ }
406+ }
384407 if let Some(parts) = subtasks.clone() {
385408 <span class=(class!("card-subtasks", "card-subtasks-open" if subtasks_open))>(format!("{parts} \u{2630}"))</span>
386409 }
@@ -509,6 +532,7 @@ struct BoardQuery {
509532 sort: Option<String>,
510533 confirm: Option<String>,
511534 new: Option<String>,
535+ tag: Option<String>,
512536 }
513537
514538 /// The noun a sort key shows in the `<select>` — terse, no explainer.
@@ -535,6 +559,10 @@ pub async fn board_page(cx: &Cx, user: &User) -> Result {
535559 <main class="scaffold-note"><p>(t(lang, Key::SomethingWentWrong))</p></main>
536560 };
537561 };
562+ let tags = {
563+ let store = accounts(cx).store().clone();
564+ store.tags(&view_data.board.id).await?
565+ };
538566 let today = OffsetDateTime::now_utc().date();
539567 let overdue = view_data.overdue_count(today);
540568 let blocked = view_data.blocked_count();
@@ -567,6 +595,8 @@ pub async fn board_page(cx: &Cx, user: &User) -> Result {
567595 // an open task wins and `new` is ignored.
568596 let open_new = may_write && query.new.is_some() && open_task.is_none();
569597 let sort = valid_sort(query.sort.as_deref()).to_string();
598+ let tag_filter = valid_tag(query.tag.as_deref(), &tags);
599+ let default_tag_id = tags.iter().find(|tag| tag.is_default).map(|tag| tag.id.as_str());
570600 let refusal = match (query.on.as_deref(), query.refusal.as_deref()) {
571601 (Some("create_task") | Some("move_card"), Some(code)) => Refusal::from_code(code),
572602 _ => None,
@@ -598,6 +628,20 @@ pub async fn board_page(cx: &Cx, user: &User) -> Result {
598628 <path d="M4 6l4 4 4-4"></path>
599629 </svg>
600630 </form>
631+ <form class="field-box field-box-sort" method="get" action="/">
632+ <span class="field-text">(t(lang, Key::Project))</span>
633+ <select class="status-select" name="tag" data-autosubmit="">
634+ <option value="" selected=(tag_filter.is_none())>(t(lang, Key::AllTags))</option>
635+ for tag in &tags {
636+ <option value=(tag.id.clone()) selected=(tag_filter.as_deref() == Some(tag.id.as_str()))>(tag.name.clone())</option>
637+ }
638+ </select>
639+ <svg class="glyph" width="14" height="14" viewBox="0 0 16 16" fill="none"
640+ stroke="currentColor" stroke-width="1.5" stroke-linecap="round"
641+ stroke-linejoin="round" aria-hidden="true">
642+ <path d="M4 6l4 4 4-4"></path>
643+ </svg>
644+ </form>
601645 <div class="spacer"></div>
602646 if overdue > 0 { <span class="chip chip-overdue">(format!("{overdue} {}", t(lang, Key::Overdue)))</span> }
603647 if blocked > 0 { <span class="chip chip-blocked">(format!("{blocked} {}", t(lang, Key::Blocked)))</span> }
@@ -607,7 +651,7 @@ pub async fn board_page(cx: &Cx, user: &User) -> Result {
607651 }
608652 <main class="board-stage">
609653 <div class="board-columns">
610- (board_columns(cx, sort.clone()).await?)
654+ (board_columns(cx, sort.clone(), tag_filter.clone(), default_tag_id).await?)
611655 </div>
612656 </main>
613657 if let Some(task_id) = &open_task {
@@ -644,6 +688,7 @@ mod sort_tests {
644688 blocks: Vec::new(),
645689 subtask_total: 0,
646690 subtask_done: 0,
691+ tag: None,
647692 }
648693 }
649694
crates/izlek-web/src/detail.rsmodified+65 -0
@@ -88,6 +88,9 @@ pub struct DetailSnapshot {
8888 pub attachment_limit_mb: u64,
8989 pub notifications: Vec<NotificationLine>,
9090 pub may_administer: bool,
91+ /// Every tag on this workspace's board, in the admin's hand-set order —
92+ /// the tag field reads both its options and its current value from here.
93+ pub tags: Vec<izlek_core::store::Tag>,
9194 }
9295
9396 /// One send's fate, joined to the sends of its decision's event.
@@ -360,6 +363,13 @@ async fn load_snapshot(
360363 linkable.sort_by(|a, b| a.id.cmp(&b.id));
361364 }
362365
366+ // The tag field's options: every tag on the board, in the admin's
367+ // hand-set order. A workspace with no board yet has no tags either.
368+ let tags = match store.board(&user.workspace_id).await? {
369+ Some(board) => store.tags(&board.id).await?,
370+ None => Vec::new(),
371+ };
372+
363373 let may_write = user.role.can_write_tasks();
364374 let may_administer = user.role.can_administer();
365375 let lang = Lang::from_code(&user.language);
@@ -446,6 +456,7 @@ async fn load_snapshot(
446456 allowed_file_types,
447457 attachment_limit_mb,
448458 notifications,
459+ tags,
449460 may_administer,
450461 me: Me::from(&user),
451462 today: OffsetDateTime::now_utc().date(),
@@ -515,6 +526,34 @@ async fn save_task(cx: &Cx, Form(input): Form<SaveTaskForm>) -> Redirect {
515526 redirect(cx, None)
516527 }
517528
529+#[derive(Deserialize)]
530+struct SetTaskTagForm {
531+ task_id: String,
532+ tag_id: String,
533+}
534+
535+/// Files a task under a tag. A Viewer can read tags but not set them; the
536+/// tag has to be this workspace board's own. No activity is recorded and no
537+/// mail follows — re-labeling a card is not a thing anybody needs told
538+/// about.
539+#[route(POST "/api/set_task_tag")]
540+async fn set_task_tag(cx: &Cx, Form(input): Form<SetTaskTagForm>) -> Redirect {
541+ let (actor, _) = match writer_and_task(cx, &input.task_id).await {
542+ Ok(pair) => pair,
543+ Err(refusal) => return redirect(cx, Some(refusal)),
544+ };
545+ let store = accounts(cx).store().clone();
546+ let Some(board) = store.board(&actor.workspace_id).await? else {
547+ return redirect(cx, Some(Refusal::Unavailable));
548+ };
549+ let tags = store.tags(&board.id).await?;
550+ if !tags.iter().any(|tag| tag.id == input.tag_id) {
551+ return redirect(cx, Some(Refusal::NotFound));
552+ }
553+ store.set_task_tag(&input.task_id, &input.tag_id).await?;
554+ redirect(cx, None)
555+}
556+
518557 /// Puts someone on a task. A Viewer can neither do this nor be the target.
519558 #[route(POST "/api/assign")]
520559 async fn assign(cx: &Cx, Form(input): Form<PersonForm>) -> Redirect {
@@ -542,6 +581,7 @@ async fn assign(cx: &Cx, Form(input): Form<PersonForm>) -> Redirect {
542581 .record_activity(
543582 &input.task_id,
544583 Some(&actor.id),
584+ Some(&person.id),
545585 &ActivityKind::Assigned,
546586 &person.display_name,
547587 OffsetDateTime::now_utc(),
@@ -573,6 +613,7 @@ async fn unassign(cx: &Cx, Form(input): Form<PersonForm>) -> Redirect {
573613 .record_activity(
574614 &input.task_id,
575615 Some(&actor.id),
616+ Some(&person.id),
576617 &ActivityKind::Unassigned,
577618 &person.display_name,
578619 OffsetDateTime::now_utc(),
@@ -611,6 +652,7 @@ async fn link_tasks(cx: &Cx, Form(input): Form<LinkForm>) -> Redirect {
611652 .record_activity(
612653 &input.task_id,
613654 Some(&actor.id),
655+ None,
614656 &ActivityKind::Linked,
615657 &other.row.task_key,
616658 now,
@@ -644,6 +686,7 @@ async fn unlink_tasks(cx: &Cx, Form(input): Form<LinkForm>) -> Redirect {
644686 .record_activity(
645687 &input.task_id,
646688 Some(&actor.id),
689+ None,
647690 &ActivityKind::Unlinked,
648691 &other.row.task_key,
649692 now,
@@ -742,6 +785,7 @@ async fn set_parent(cx: &Cx, Form(input): Form<ParentForm>) -> Redirect {
742785 .record_activity(
743786 &input.task_id,
744787 Some(&actor.id),
788+ None,
745789 &kind,
746790 &other_key,
747791 OffsetDateTime::now_utc(),
@@ -852,6 +896,7 @@ async fn delete_file(cx: &Cx, Form(input): Form<FileIdForm>) -> Redirect {
852896 .record_activity(
853897 &attachment.task_id,
854898 Some(&user.id),
899+ None,
855900 &izlek_core::detail::ActivityKind::FileRemoved,
856901 &attachment.file_name,
857902 time::OffsetDateTime::now_utc(),
@@ -1694,6 +1739,7 @@ pub async fn task_modal(cx: &Cx, task_id: &str, confirm_delete: bool, tab: Tab)
16941739 allowed_file_types,
16951740 attachment_limit_mb: _,
16961741 notifications,
1742+ tags,
16971743 may_administer: _,
16981744 } = snapshot;
16991745 let lang = Lang::from_code(&me.language);
@@ -1828,6 +1874,25 @@ pub async fn task_modal(cx: &Cx, task_id: &str, confirm_delete: bool, tab: Tab)
18281874 </span>
18291875 }
18301876 </div>
1877+ <div class="detail-field detail-field-tag">
1878+ <span class="detail-label">(t(lang, Key::Project))</span>
1879+ if may_write {
1880+ <form class="status-form" method="post" action="/api/set_task_tag">
1881+ <input type="hidden" name="task_id" value=(detail.id.clone())>
1882+ <select class="status-select" name="tag_id" data-autosubmit="">
1883+ for tag in &tags {
1884+ <option value=(tag.id.clone()) selected=(Some(tag.id.as_str()) == detail.tag.as_ref().map(|t| t.id.as_str()))>(tag.name.clone())</option>
1885+ }
1886+ </select>
1887+ </form>
1888+ } else {
1889+ <span class="field-box">
1890+ <span class="field-text">(
1891+ detail.tag.as_ref().map(|tag| tag.name.clone()).unwrap_or_default()
1892+ )</span>
1893+ </span>
1894+ }
1895+ </div>
18311896 <div class="detail-field">
18321897 <span class="detail-label">(t(lang, Key::Deadline))</span>
18331898 (deadline_control(cx, &detail, today, may_write, lang).await?)
crates/izlek-web/src/files.rsmodified+1 -0
@@ -424,6 +424,7 @@ async fn upload(
424424 .record_activity(
425425 &task_id,
426426 Some(&user.id),
427+ None,
427428 &izlek_core::detail::ActivityKind::FileAdded,
428429 &label,
429430 OffsetDateTime::now_utc(),
crates/izlek-web/src/i18n.rsmodified+55 -0
@@ -102,10 +102,23 @@ pub enum Key {
102102 // Topbar nav / chrome shared by board.rs, rules.rs, logs.rs, settings.rs.
103103 NavBoard,
104104 NavMailRules,
105+ NavTags,
105106 NavLogs,
106107 NavSettings,
107108 AdminOnly,
108109
110+ // tags.rs — Project/AllTags also serve board.rs's filter and detail.rs.
111+ NewTag,
112+ NameLabel,
113+ AddTag,
114+ SaveTag,
115+ EditThisTag,
116+ DeleteThisTag,
117+ MoveTagUp,
118+ MoveTagDown,
119+ Project,
120+ AllTags,
121+
109122 // settings.rs
110123 YourProfile,
111124 Remove,
@@ -329,6 +342,13 @@ pub enum Key {
329342 Oldest,
330343 From,
331344 To,
345+ // people.rs
346+ TasksOpenLabel,
347+ TasksDoneLabel,
348+ TasksCreatedLabel,
349+ CommentsLabel,
350+ RecentActivity,
351+ MailBatchLabel,
332352 }
333353
334354 /// The lone templated phrase — a name in the middle reads worse as two
@@ -497,6 +517,29 @@ pub fn t(lang: Lang, key: Key) -> &'static str {
497517 (AdminOnly, En) => "Admin only",
498518 (AdminOnly, Tr) => "Sadece yönetici",
499519
520+ (NavTags, En) => "Tags",
521+ (NavTags, Tr) => "Etiketler",
522+ (NewTag, En) => "New tag",
523+ (NewTag, Tr) => "Yeni etiket",
524+ (NameLabel, En) => "NAME",
525+ (NameLabel, Tr) => "İSİM",
526+ (AddTag, En) => "Add tag",
527+ (AddTag, Tr) => "Etiket ekle",
528+ (SaveTag, En) => "Save tag",
529+ (SaveTag, Tr) => "Etiketi kaydet",
530+ (EditThisTag, En) => "Edit this tag",
531+ (EditThisTag, Tr) => "Bu etiketi düzenle",
532+ (DeleteThisTag, En) => "Delete this tag",
533+ (DeleteThisTag, Tr) => "Bu etiketi sil",
534+ (MoveTagUp, En) => "Move up",
535+ (MoveTagUp, Tr) => "Yukarı taşı",
536+ (MoveTagDown, En) => "Move down",
537+ (MoveTagDown, Tr) => "Aşağı taşı",
538+ (Project, En) => "Project",
539+ (Project, Tr) => "Proje",
540+ (AllTags, En) => "All",
541+ (AllTags, Tr) => "Tümü",
542+
500543 (YourProfile, En) => "Your profile",
501544 (YourProfile, Tr) => "Profilin",
502545 (Remove, En) => "Remove",
@@ -936,6 +979,18 @@ pub fn t(lang: Lang, key: Key) -> &'static str {
936979 (From, Tr) => "Başlangıç",
937980 (To, En) => "To",
938981 (To, Tr) => "Bitiş",
982+ (TasksOpenLabel, En) => "Open tasks",
983+ (TasksOpenLabel, Tr) => "Açık görevler",
984+ (TasksDoneLabel, En) => "Done tasks",
985+ (TasksDoneLabel, Tr) => "Biten görevler",
986+ (TasksCreatedLabel, En) => "Tasks created",
987+ (TasksCreatedLabel, Tr) => "Oluşturulan görevler",
988+ (CommentsLabel, En) => "Comments",
989+ (CommentsLabel, Tr) => "Yorumlar",
990+ (RecentActivity, En) => "Recent activity",
991+ (RecentActivity, Tr) => "Son etkinlik",
992+ (MailBatchLabel, En) => "Mail delay (minutes)",
993+ (MailBatchLabel, Tr) => "Posta gecikmesi (dakika)",
939994 }
940995 }
941996
crates/izlek-web/src/layout.rsmodified+11 -5
@@ -124,6 +124,7 @@ pub async fn user_menu(cx: &Cx, me: &crate::detail::Me, lang: Lang) -> Result {
124124 <div class="user-menu-name">(me.display_name.clone())</div>
125125 <div class="user-menu-email">(me.email.clone())</div>
126126 <div class="user-menu-role">(t(lang, role_key))</div>
127+ <a class="user-menu-item" href=(format!("/people/{}", me.id))>(t(lang, Key::YourProfile))</a>
127128 <form class="user-menu-item-form" method="post" action="/api/sign_out" data-hard="">
128129 <button class="user-menu-item" type="submit">(t(lang, Key::SignOut))</button>
129130 </form>
@@ -132,23 +133,25 @@ pub async fn user_menu(cx: &Cx, me: &crate::detail::Me, lang: Lang) -> Result {
132133 }
133134 }
134135
135-/// The four signed-in pages, as the topbar nav links between them.
136+/// The five signed-in pages, as the topbar nav links between them.
136137 #[derive(Clone, Copy, PartialEq)]
137138 pub enum NavPage {
138139 Board,
139140 Rules,
140141 Logs,
142+ Tags,
141143 Settings,
142144 }
143145
144146 impl NavPage {
145- const ALL: [Self; 4] = [Self::Board, Self::Rules, Self::Logs, Self::Settings];
147+ const ALL: [Self; 5] = [Self::Board, Self::Rules, Self::Logs, Self::Tags, Self::Settings];
146148
147149 fn href(self) -> &'static str {
148150 match self {
149151 Self::Board => "/",
150152 Self::Rules => "/rules",
151153 Self::Logs => "/logs",
154+ Self::Tags => "/tags",
152155 Self::Settings => "/settings",
153156 }
154157 }
@@ -158,13 +161,14 @@ impl NavPage {
158161 Self::Board => Key::NavBoard,
159162 Self::Rules => Key::NavMailRules,
160163 Self::Logs => Key::NavLogs,
164+ Self::Tags => Key::NavTags,
161165 Self::Settings => Key::NavSettings,
162166 }
163167 }
164168 }
165169
166-/// The topbar's page nav, shared by every signed-in page: the four pages
167-/// with the current one marked, the admin-only ones (rules, logs) shown
170+/// The topbar's page nav, shared by every signed-in page: the five pages
171+/// with the current one marked, the admin-only ones (rules, logs, tags) shown
168172 /// only to roles that can administer. Plain `<a>`s — the soft-nav forwarder
169173 /// swaps them like any same-origin link, so `data-hard` stays off.
170174 pub async fn topbar_nav(cx: &Cx, active: NavPage, role: izlek_core::Role, lang: Lang) -> Result {
@@ -172,7 +176,7 @@ pub async fn topbar_nav(cx: &Cx, active: NavPage, role: izlek_core::Role, lang:
172176 cx =>
173177 <nav class="topbar-nav-links">
174178 for page in NavPage::ALL {
175- if role.can_administer() || !matches!(page, NavPage::Rules | NavPage::Logs) {
179+ if role.can_administer() || !matches!(page, NavPage::Rules | NavPage::Logs | NavPage::Tags) {
176180 <a
177181 class=(if page == active { "topbar-nav topbar-nav-on" } else { "topbar-nav" })
178182 href=(page.href())
@@ -637,7 +641,9 @@ pub async fn live_script(cx: &Cx) -> Result {
637641 var path = window.location.pathname; \
638642 if (path === '/logs') { return topic !== 'board' && topic !== 'task'; } \
639643 if (path === '/rules') { return topic === 'rules' || topic === 'members'; } \
644+ if (path === '/tags') { return topic === 'tags' || topic === 'members'; } \
640645 if (path === '/settings') { return topic === 'settings' || topic === 'members'; } \
646+ if (path.indexOf('/people/') === 0) { return topic === 'members'; } \
641647 return topic === 'board' || topic === 'task' || topic === 'members'; \
642648 } \
643649 try { \
crates/izlek-web/src/lib.rsmodified+2 -0
@@ -13,9 +13,11 @@ pub mod layout;
1313 pub mod live;
1414 pub mod logs;
1515 pub mod pages;
16+pub mod people;
1617 pub mod photo;
1718 pub mod rules;
1819 pub mod server;
1920 pub mod settings;
2021 pub mod sheet;
2122 pub mod smtp;
23+pub mod tags;
crates/izlek-web/src/live.rsmodified+3 -1
@@ -56,7 +56,9 @@ pub struct Shutdown(pub tokio::sync::watch::Receiver<bool>);
5656 /// moved, because being told is itself knowing something about the queue.
5757 fn may_hear(topic: &Topic, admin: bool) -> bool {
5858 match topic {
59- Topic::Board | Topic::Task(_) | Topic::Members => true,
59+ // Tags ride with the board: every member sees a card's tag, so being
60+ // told the tags moved tells them nothing they cannot already read.
61+ Topic::Board | Topic::Task(_) | Topic::Members | Topic::Tags => true,
6062 Topic::Queue | Topic::Rules | Topic::Settings | Topic::Activity => admin,
6163 }
6264 }
crates/izlek-web/src/main.rsmodified+37 -0
@@ -13,6 +13,43 @@ async fn healthz() -> Result<&'static str> {
1313
1414 #[tokio::main]
1515 async fn main() {
16+ let args: Vec<String> = std::env::args().collect();
17+ if args.get(1).map(|s| s.as_str()) == Some("reconcile") {
18+ let mut dry_run = false;
19+ let mut yes = false;
20+ for arg in &args[2..] {
21+ match arg.as_str() {
22+ "--dry-run" => dry_run = true,
23+ "--yes" => yes = true,
24+ _ => {
25+ eprintln!("izlek reconcile: unknown option {arg}");
26+ std::process::exit(2);
27+ }
28+ }
29+ }
30+ let config = match izlek_core::Config::load() {
31+ Ok(config) => config,
32+ Err(problem) => {
33+ eprintln!("izlek: {problem}");
34+ std::process::exit(2);
35+ }
36+ };
37+ if let Err(problem) = izlek_core::store::reconcile(
38+ &config.database.to_string_lossy(),
39+ izlek_core::store::ReconcileOptions {
40+ dry_run,
41+ yes,
42+ auto: false,
43+ },
44+ )
45+ .await
46+ {
47+ eprintln!("izlek reconcile: {problem}");
48+ std::process::exit(1);
49+ }
50+ return;
51+ }
52+
1653 // config/izlek.toml is read here, before anything is opened, and written with
1754 // development defaults if it is not there yet. A broken key stops the
1855 // boot with its name in the message: the failure this prevents is not an
crates/izlek-web/src/people.rsadded+171 -0
@@ -0,0 +1,171 @@
1+//! A member's profile: who they are, and what they have done here. Any
2+//! signed-in member of the workspace may read it, and nothing on the page
3+//! writes — the one editor a profile has stays where it already lives, on
4+//! `/settings?section=profile`, which the page links to for its own person
5+//! and nowhere else. A stranger and a missing id read the same: the router's
6+//! own not-found, never a `403` — `photo.rs` keeps the same rule for bytes.
7+
8+use topcoat::Result;
9+use topcoat::context::Cx;
10+use topcoat::router::error::not_found;
11+use topcoat::router::{page, path_param};
12+use topcoat::view::view;
13+
14+use izlek_core::detail::ActivityKind;
15+use izlek_core::store::{ActivityFilter, Dir, FeedPage};
16+
17+use crate::i18n::{Key, Lang, t};
18+use crate::server::{accounts, require_user};
19+
20+path_param!(user_id);
21+
22+/// The account line the members table renders, read the same way here: a
23+/// named state (owner, invited) while there is nothing newer to say, and the
24+/// last-seen day once there is.
25+fn account_line(lang: Lang, is_owner: bool, has_signed_in: bool, last_day: Option<String>) -> String {
26+ if is_owner {
27+ t(lang, Key::OwnerStatus).to_string()
28+ } else if !has_signed_in {
29+ t(lang, Key::InvitedStatus).to_string()
30+ } else if let Some(day) = last_day {
31+ crate::i18n::last_seen_label(lang, &day)
32+ } else {
33+ t(lang, Key::ActiveStatus).to_string()
34+ }
35+}
36+
37+/// The verb a feed line opens with. The task kinds read through
38+/// [`crate::i18n::activity_kind_word`]; the account kinds are not all in that
39+/// table and would fall through as raw tokens (`profile_saved`), so the ones
40+/// with a translated word take it here.
41+fn kind_word(lang: Lang, kind: &ActivityKind) -> String {
42+ match kind {
43+ ActivityKind::WorkspaceClaimed => t(lang, Key::ActWorkspaceClaimed).into(),
44+ ActivityKind::Joined => t(lang, Key::ActJoined).into(),
45+ ActivityKind::SignedIn => t(lang, Key::ActSignedIn).into(),
46+ ActivityKind::SignedOut => t(lang, Key::ActSignedOut).into(),
47+ ActivityKind::PasswordChanged => t(lang, Key::ActPasswordChanged).into(),
48+ ActivityKind::ProfileSaved => t(lang, Key::ActProfileSaved).into(),
49+ ActivityKind::SenderSaved => t(lang, Key::ActSenderSaved).into(),
50+ ActivityKind::LimitsSaved => t(lang, Key::ActLimitsSaved).into(),
51+ ActivityKind::TestMailSent => t(lang, Key::ActTestMailSent).into(),
52+ ActivityKind::MessageSent => t(lang, Key::ActMessageSent).into(),
53+ other => crate::i18n::activity_kind_word(lang, other.as_str()),
54+ }
55+}
56+
57+/// A person's page. `/people/{user_id}`.
58+#[page("/people/{user_id}")]
59+async fn people_page(cx: &Cx) -> Result {
60+ let user = match require_user(cx).await {
61+ Ok(user) => user,
62+ Err(_) => return Err(not_found().into()),
63+ };
64+ let lang = Lang::from_code(&user.language);
65+ let store = accounts(cx).store().clone();
66+ let target_id: &str = path_param::<UserId>(cx);
67+ let Some(person) = store.user(target_id).await? else {
68+ return Err(not_found().into());
69+ };
70+ if person.workspace_id != user.workspace_id {
71+ return Err(not_found().into());
72+ }
73+
74+ let zone = izlek_core::detail::parse_zone(&user.timezone);
75+ let mine = person.id == user.id;
76+ let who = izlek_core::board::Person {
77+ id: person.id.clone(),
78+ display_name: person.display_name.clone(),
79+ has_photo: person.has_photo,
80+ };
81+ let is_owner = store
82+ .owner()
83+ .await?
84+ .is_some_and(|owner| owner.id == person.id);
85+ let account = account_line(
86+ lang,
87+ is_owner,
88+ person.has_signed_in(),
89+ person
90+ .last_signed_in_at
91+ .map(|at| izlek_core::board::day_label(at.to_offset(zone).date())),
92+ );
93+ let role_key = match person.role {
94+ izlek_core::Role::Admin => Key::RoleAdminOption,
95+ izlek_core::Role::Member => Key::RoleMemberOption,
96+ izlek_core::Role::Viewer => Key::RoleViewerOption,
97+ };
98+ let stats = store.user_stats(&person.id).await?;
99+ // A short list, not the feed: the newest few lines are enough to see what
100+ // the person has been near lately; the whole trail already has a page.
101+ let feed = store
102+ .recent_activity(
103+ 8,
104+ FeedPage::Newest,
105+ Dir::Newest,
106+ &ActivityFilter { actor: Some(person.id.clone()), ..Default::default() },
107+ )
108+ .await?;
109+
110+ view! {
111+ cx =>
112+ <header class="topbar">
113+ (crate::layout::mark(cx).await?)
114+ (crate::layout::topbar_nav(cx, crate::layout::NavPage::Settings, user.role, lang).await?)
115+ <div class="spacer"></div>
116+ (crate::layout::user_menu(cx, &crate::detail::Me::from(&user), lang).await?)
117+ </header>
118+
119+ <main class="people-shell">
120+ <section class="panel" id="profile">
121+ <div class="panel-head">
122+ (crate::layout::avatar(cx, &who, "avatar-lg").await?)
123+ <h2 class="panel-title">(person.display_name.clone())</h2>
124+ <span class="chip chip-role">(t(lang, role_key))</span>
125+ if mine {
126+ <a class="quiet" href="/settings?section=profile">(t(lang, Key::EditLabel))</a>
127+ }
128+ </div>
129+ <div class="panel-body">
130+ <p>(person.email.clone())</p>
131+ <p>(account)</p>
132+ </div>
133+ </section>
134+
135+ <section class="panel">
136+ <div class="panel-body">
137+ <dl class="people-stats">
138+ <div><dt>(t(lang, Key::TasksOpenLabel))</dt><dd>(stats.assigned_open)</dd></div>
139+ <div><dt>(t(lang, Key::TasksDoneLabel))</dt><dd>(stats.assigned_done)</dd></div>
140+ <div><dt>(t(lang, Key::TasksCreatedLabel))</dt><dd>(stats.created)</dd></div>
141+ <div><dt>(t(lang, Key::CommentsLabel))</dt><dd>(stats.comments)</dd></div>
142+ </dl>
143+ </div>
144+ </section>
145+
146+ <section class="panel">
147+ <div class="panel-head">
148+ <h2 class="panel-title">(t(lang, Key::RecentActivity))</h2>
149+ </div>
150+ <div class="panel-body">
151+ if feed.is_empty() {
152+ <p>(t(lang, Key::NothingYet))</p>
153+ }
154+ <ul class="people-feed">
155+ for line in feed {
156+ <li>
157+ <span>(kind_word(lang, &line.kind))</span>
158+ if let Some(title) = line.title {
159+ <span>(title)</span>
160+ }
161+ <span class="people-feed-day">(izlek_core::board::day_label(line.at.to_offset(zone).date()))</span>
162+ </li>
163+ }
164+ </ul>
165+ </div>
166+ </section>
167+ </main>
168+
169+ (crate::layout::escape_script(cx).await?)
170+ }
171+}
crates/izlek-web/src/server.rsmodified+6 -0
@@ -357,6 +357,8 @@ pub enum Refusal {
357357 NotAnImage,
358358 /// A rule with no subject line: the mail it sends would arrive blank.
359359 EmptySubject,
360+ /// A tag with no name is not a tag the board can show.
361+ EmptyTag,
360362 /// A message with no body: there is nothing for the recipient to read.
361363 EmptyBody,
362364 /// The date field did not hold a date.
@@ -419,6 +421,7 @@ impl Refusal {
419421 }
420422 Refusal::NotAnImage => "That is not an image.".to_string(),
421423 Refusal::EmptySubject => "Give the rule a subject line.".to_string(),
424+ Refusal::EmptyTag => "Give the tag a name.".to_string(),
422425 Refusal::EmptyBody => "Write something first.".to_string(),
423426 Refusal::BadDeadline => "That is not a date.".to_string(),
424427 Refusal::Cycle => "That link would put this task behind itself.".to_string(),
@@ -477,6 +480,7 @@ impl Refusal {
477480 // language off of, so it falls back to English like the rest.
478481 Refusal::BadSender(_) => self.message(),
479482 Refusal::EmptySubject => "Kurala bir konu ver.".to_string(),
483+ Refusal::EmptyTag => "Etikete bir ad ver.".to_string(),
480484 Refusal::EmptyBody => "Önce bir şey yaz.".to_string(),
481485 Refusal::Rejected => "Bu işe yaramadı.".to_string(),
482486 Refusal::RateLimited => {
@@ -526,6 +530,7 @@ impl Refusal {
526530 "file-type" => Refusal::FileTypeNotAllowed,
527531 "not-an-image" => Refusal::NotAnImage,
528532 "empty-subject" => Refusal::EmptySubject,
533+ "empty-tag" => Refusal::EmptyTag,
529534 "empty-body" => Refusal::EmptyBody,
530535 "bad-deadline" => Refusal::BadDeadline,
531536 "cycle" => Refusal::Cycle,
@@ -581,6 +586,7 @@ impl Refusal {
581586 Refusal::FileTypeNotAllowed => "file-type",
582587 Refusal::NotAnImage => "not-an-image",
583588 Refusal::EmptySubject => "empty-subject",
589+ Refusal::EmptyTag => "empty-tag",
584590 Refusal::EmptyBody => "empty-body",
585591 Refusal::BadDeadline => "bad-deadline",
586592 Refusal::Cycle => "cycle",
crates/izlek-web/src/settings.rsmodified+26 -5
@@ -39,6 +39,9 @@ use crate::server::{Refusal, accounts, mail, require_admin, require_user};
3939 /// one (per the settings lane's note there).
4040 pub const WIDEST_ATTACHMENT_MB: u64 = 500;
4141 pub const WIDEST_PHOTO_MB: u64 = 20;
42+/// The longest a notification may be held waiting for the rest of its
43+/// workflow. Two hours is already far past the point where a mail is news.
44+pub const LONGEST_BATCH_MINUTES: u32 = 120;
4245
4346 const MB: u64 = 1024 * 1024;
4447
@@ -277,6 +280,7 @@ struct SaveLimitsForm {
277280 attachment_limit_mb: u64,
278281 photo_limit_mb: u64,
279282 allowed_file_types: String,
283+ mail_batch_minutes: u32,
280284 }
281285
282286 /// Changes the workspace's limits. Admin-only, checked here.
@@ -297,6 +301,7 @@ async fn save_limits(
297301 || input.photo_limit_mb == 0
298302 || input.attachment_limit_mb > WIDEST_ATTACHMENT_MB
299303 || input.photo_limit_mb > WIDEST_PHOTO_MB
304+ || input.mail_batch_minutes > LONGEST_BATCH_MINUTES
300305 {
301306 return Ok(saved_or_refused("save_limits", Some(Refusal::BadLimit)));
302307 }
@@ -310,6 +315,7 @@ async fn save_limits(
310315 input.attachment_limit_mb * MB,
311316 input.photo_limit_mb * MB,
312317 &types,
318+ input.mail_batch_minutes,
313319 )
314320 .await;
315321 let refusal = match outcome {
@@ -926,7 +932,7 @@ async fn members_now(cx: &Cx, asking: &User) -> Result<Vec<Member>> {
926932 .collect())
927933 }
928934
929-async fn limits_now(cx: &Cx, workspace_id: &str) -> Result<(u64, u64, Vec<String>)> {
935+async fn limits_now(cx: &Cx, workspace_id: &str) -> Result<(u64, u64, Vec<String>, u32)> {
930936 let workspace = accounts(cx)
931937 .store()
932938 .workspace()
@@ -937,6 +943,7 @@ async fn limits_now(cx: &Cx, workspace_id: &str) -> Result<(u64, u64, Vec<String
937943 workspace.attachment_limit_bytes / MB,
938944 workspace.photo_limit_bytes / MB,
939945 workspace.allowed_file_types,
946+ workspace.mail_batch_minutes,
940947 ))
941948 }
942949
@@ -1171,8 +1178,8 @@ async fn settings_page(cx: &Cx) -> Result {
11711178 None
11721179 };
11731180 let (limits, allowed_types) = if administers {
1174- let (attachment, photo, types) = limits_now(cx, &user.workspace_id).await?;
1175- (Some((attachment, photo)), types)
1181+ let (attachment, photo, types, batch) = limits_now(cx, &user.workspace_id).await?;
1182+ (Some((attachment, photo, batch)), types)
11761183 } else {
11771184 (None, Vec::new())
11781185 };
@@ -1466,7 +1473,9 @@ async fn settings_page(cx: &Cx) -> Result {
14661473 </section>
14671474 }
14681475
1469- if section == Section::Limits && let Some((attachment_limit_mb, photo_limit_mb)) = limits {
1476+ if section == Section::Limits
1477+ && let Some((attachment_limit_mb, photo_limit_mb, mail_batch_minutes)) = limits
1478+ {
14701479 <section class="panel" id="limits">
14711480 <div class="panel-head">
14721481 <h2 class="panel-title">(t(lang, Key::WorkspaceLimits))</h2>
@@ -1499,6 +1508,18 @@ async fn settings_page(cx: &Cx) -> Result {
14991508 >
15001509 </label>
15011510 </div>
1511+ <label class="field">
1512+ <span class="field-label">(t(lang, Key::MailBatchLabel))</span>
1513+ <input
1514+ class="field-input"
1515+ type="number"
1516+ name="mail_batch_minutes"
1517+ min="0"
1518+ max=(LONGEST_BATCH_MINUTES.to_string())
1519+ value=(mail_batch_minutes.to_string())
1520+ required=""
1521+ >
1522+ </label>
15021523 <label class="field">
15031524 <span class="field-label">(t(lang, Key::AllowedFileTypesLabel))</span>
15041525 <input
@@ -1558,7 +1579,7 @@ async fn settings_page(cx: &Cx) -> Result {
15581579 <td class="member-col-name member-name">
15591580 <span class="member-name-row">
15601581 (crate::layout::avatar(cx, &member_person, "avatar-sm").await?)
1561- (member.display_name.clone())
1582+ <a href=(format!("/people/{}", member.id))>(member.display_name.clone())</a>
15621583 if member.is_you {
15631584 <span class="member-you">(t(lang, Key::You))</span>
15641585 }
crates/izlek-web/src/tags.rsadded+364 -0
@@ -0,0 +1,364 @@
1+//! Task tags, ported from `izlek-web/src/rules.rs` onto topcoat's
2+//! server-rendered pages.
3+//!
4+//! The screen is the admin's, and so is every call behind it: a tag renames
5+//! what every member sees on the board and in the task modal, so writing one
6+//! is not something a Member may do even if they reach the endpoint directly.
7+//! The chip in the artboard says "Admin only"; the guard is in the handlers.
8+//!
9+//! There is no client-side signal here to hold which row is being edited —
10+//! every topcoat page is rendered fresh, server-side, on every request. Which
11+//! tag (if any) is open for editing rides `?edit=<tag_id>` on `/tags`
12+//! itself: the row renders as the rename form server-side instead of the
13+//! display row, no script required.
14+//!
15+//! The board's default tag ships no delete control: the store refuses the
16+//! delete anyway (every task falls back to it), and a control that cannot
17+//! act is not drawn.
18+
19+use std::sync::Arc;
20+
21+use serde::{Deserialize, Serialize};
22+use topcoat::Result;
23+use topcoat::context::Cx;
24+use topcoat::router::content::{Form, Json};
25+use topcoat::router::request::headers;
26+use topcoat::router::{HeaderName, StatusCode, header, page, query_params, route};
27+use topcoat::view::view;
28+
29+use izlek_core::store::{Store, Tag, User};
30+
31+use crate::i18n::{Key, Lang, t};
32+use crate::server::{Refusal, accounts, refusal_of, require_admin};
33+
34+/// One tag as the screen reads it: a name, an order and whether it is the
35+/// default every task wears when nothing else is chosen.
36+#[derive(Clone, Debug, Serialize)]
37+struct TagLine {
38+ id: String,
39+ name: String,
40+ position: i64,
41+ is_default: bool,
42+}
43+
44+/// Every tag on the workspace's own board, in the admin's hand-set order.
45+async fn tags_of(
46+ store: &Arc<dyn Store>,
47+ user: &User,
48+) -> std::result::Result<Vec<TagLine>, Refusal> {
49+ let Some(board) = store
50+ .board(&user.workspace_id)
51+ .await
52+ .map_err(|_| Refusal::Unavailable)?
53+ else {
54+ return Err(Refusal::Unavailable);
55+ };
56+ Ok(store
57+ .tags(&board.id)
58+ .await
59+ .map_err(|_| Refusal::Unavailable)?
60+ .into_iter()
61+ .map(|tag| TagLine {
62+ id: tag.id,
63+ name: tag.name,
64+ position: tag.position,
65+ is_default: tag.is_default,
66+ })
67+ .collect())
68+}
69+
70+/// The admin's store, once the tag id has been shown to name a tag on this
71+/// workspace's own board.
72+///
73+/// A tag id is opaque and arrives from the browser, so "not yours" and "not a
74+/// tag" are the same answer: neither tells the caller whether the id exists
75+/// somewhere else.
76+async fn tag_of_this_workspace(
77+ cx: &Cx,
78+ tag_id: &str,
79+) -> std::result::Result<(Arc<dyn Store>, User, Tag), Refusal> {
80+ let user = require_admin(cx).await?;
81+ let store = accounts(cx).store().clone();
82+ let board = store
83+ .board(&user.workspace_id)
84+ .await
85+ .map_err(|_| Refusal::Unavailable)?
86+ .ok_or(Refusal::Unavailable)?;
87+ let tag = store
88+ .tags(&board.id)
89+ .await
90+ .map_err(|_| Refusal::Unavailable)?
91+ .into_iter()
92+ .find(|tag| tag.id == tag_id)
93+ .ok_or(Refusal::NotFound)?;
94+ Ok((store, user, tag))
95+}
96+
97+/// The page a browser without script is sent back to on a 303: the page the
98+/// form was posted from, or home when there is no `Referer` to read.
99+fn back_to(cx: &Cx) -> String {
100+ headers(cx)
101+ .get(header::REFERER)
102+ .and_then(|value| value.to_str().ok())
103+ .unwrap_or("/")
104+ .to_string()
105+}
106+
107+/// A 303 to [`back_to`], carrying `refusal` as the body for
108+/// `crate::server::carry_refusal_on_redirect` to read and copy onto the query.
109+type Redirect = Result<(StatusCode, [(HeaderName, String); 1], Json<Option<Refusal>>)>;
110+
111+fn redirect(cx: &Cx, refusal: Option<Refusal>) -> Redirect {
112+ Ok((
113+ StatusCode::SEE_OTHER,
114+ [(header::LOCATION, back_to(cx))],
115+ Json(refusal),
116+ ))
117+}
118+
119+#[derive(Deserialize)]
120+struct CreateTagForm {
121+ name: String,
122+}
123+
124+/// Writes one tag. A duplicate name is the store's `Conflict`, which lands
125+/// here like every other store error: the admin sees "something went wrong"
126+/// and the list still shows the tag they collide with.
127+#[route(POST "/api/create_tag")]
128+async fn create_tag(cx: &Cx, Form(input): Form<CreateTagForm>) -> Redirect {
129+ let user = match require_admin(cx).await {
130+ Ok(user) => user,
131+ Err(refusal) => return redirect(cx, Some(refusal)),
132+ };
133+ let name = input.name.trim().to_string();
134+ if name.is_empty() {
135+ return redirect(cx, Some(Refusal::EmptyTag));
136+ }
137+ let store = accounts(cx).store().clone();
138+ let board = match store.board(&user.workspace_id).await {
139+ Ok(Some(board)) => board,
140+ _ => return redirect(cx, Some(Refusal::Unavailable)),
141+ };
142+ if store
143+ .create_tag(&board.id, &name, time::OffsetDateTime::now_utc())
144+ .await
145+ .is_err()
146+ {
147+ return redirect(cx, Some(Refusal::Unavailable));
148+ }
149+ redirect(cx, None)
150+}
151+
152+#[derive(Deserialize)]
153+struct RenameTagForm {
154+ tag_id: String,
155+ name: String,
156+}
157+
158+/// Rewrites a tag's name in place, guarded exactly like the rest — the tag
159+/// itself has to be this workspace's, or an id from elsewhere could be
160+/// renamed by an admin who never owned it.
161+#[route(POST "/api/rename_tag")]
162+async fn rename_tag(cx: &Cx, Form(input): Form<RenameTagForm>) -> Redirect {
163+ let (store, _, _) = match tag_of_this_workspace(cx, &input.tag_id).await {
164+ Ok(triple) => triple,
165+ Err(refusal) => return redirect(cx, Some(refusal)),
166+ };
167+ let name = input.name.trim().to_string();
168+ if name.is_empty() {
169+ return redirect(cx, Some(Refusal::EmptyTag));
170+ }
171+ if store.rename_tag(&input.tag_id, &name).await.is_err() {
172+ return redirect(cx, Some(Refusal::Unavailable));
173+ }
174+ redirect(cx, None)
175+}
176+
177+#[derive(Deserialize)]
178+struct DeleteTagForm {
179+ tag_id: String,
180+}
181+
182+/// Removes a tag. The store refuses to delete the default — every task
183+/// without a tag wears it — and that refusal lands here as "unavailable";
184+/// the row itself ships no delete control in the first place.
185+#[route(POST "/api/delete_tag")]
186+async fn delete_tag(cx: &Cx, Form(input): Form<DeleteTagForm>) -> Redirect {
187+ let (store, _, _) = match tag_of_this_workspace(cx, &input.tag_id).await {
188+ Ok(triple) => triple,
189+ Err(refusal) => return redirect(cx, Some(refusal)),
190+ };
191+ if store.delete_tag(&input.tag_id).await.is_err() {
192+ return redirect(cx, Some(Refusal::Unavailable));
193+ }
194+ redirect(cx, None)
195+}
196+
197+#[derive(Deserialize)]
198+struct MoveTagForm {
199+ tag_id: String,
200+ direction: String,
201+}
202+
203+/// Steps a tag up or down the board's hand-set order. A move off either end
204+/// is the store's no-op, not an error; a direction that is neither word is a
205+/// form gone wrong, and does nothing.
206+#[route(POST "/api/move_tag")]
207+async fn move_tag(cx: &Cx, Form(input): Form<MoveTagForm>) -> Redirect {
208+ let (store, _, _) = match tag_of_this_workspace(cx, &input.tag_id).await {
209+ Ok(triple) => triple,
210+ Err(refusal) => return redirect(cx, Some(refusal)),
211+ };
212+ let up = match input.direction.as_str() {
213+ "up" => true,
214+ "down" => false,
215+ _ => return redirect(cx, None),
216+ };
217+ if store.move_tag(&input.tag_id, up).await.is_err() {
218+ return redirect(cx, Some(Refusal::Unavailable));
219+ }
220+ redirect(cx, None)
221+}
222+
223+/// Which tag (if any) `/tags` renders open for editing.
224+#[query_params(error = redirect("/tags"))]
225+struct TagsQuery {
226+ edit: Option<String>,
227+}
228+
229+/// The "New tag" control and the form inside it. A `<details>` rather than
230+/// anything script-driven, so a browser with no script can still open it and
231+/// post the form.
232+async fn composer(cx: &Cx, refusal: Option<&Refusal>, lang: Lang) -> Result {
233+ view! {
234+ cx =>
235+ <details class="tag-new">
236+ <summary class="tag-new-open">(t(lang, Key::NewTag))</summary>
237+ <form class="tag-form" method="post" action="/api/create_tag">
238+ <label class="tag-field">
239+ <span class="field-label">(t(lang, Key::NameLabel))</span>
240+ <input class="field-input" type="text" name="name" maxlength="60" required="">
241+ </label>
242+ <div class="panel-foot">
243+ if let Some(refusal) = refusal {
244+ <span class="field-error">(refusal.message_in(lang))</span>
245+ }
246+ <button class="primary" type="submit">(t(lang, Key::AddTag))</button>
247+ </div>
248+ </form>
249+ </details>
250+ }
251+}
252+
253+/// One tag's row: the rename form in place of it when `editing`, its display
254+/// otherwise. The default tag draws no delete form — the store would refuse
255+/// it, and a control that cannot act is not drawn.
256+async fn tag_row(cx: &Cx, tag: &TagLine, editing: bool, refusal: Option<&Refusal>, lang: Lang) -> Result {
257+ if editing {
258+ return view! {
259+ cx =>
260+ <div class="tag-row">
261+ <form class="tag-form" method="post" action="/api/rename_tag">
262+ <input type="hidden" name="tag_id" value=(tag.id.clone())>
263+ <label class="tag-field">
264+ <span class="field-label">(t(lang, Key::NameLabel))</span>
265+ <input class="field-input" type="text" name="name" maxlength="60" required="" value=(tag.name.clone())>
266+ </label>
267+ <div class="panel-foot">
268+ if let Some(refusal) = refusal {
269+ <span class="field-error">(refusal.message_in(lang))</span>
270+ }
271+ <a class="quiet" href="/tags">(t(lang, Key::Cancel))</a>
272+ <button class="primary" type="submit">(t(lang, Key::SaveTag))</button>
273+ </div>
274+ </form>
275+ </div>
276+ };
277+ }
278+
279+ view! {
280+ cx =>
281+ <div class="tag-row">
282+ <span class="tag-name">(tag.name.clone())</span>
283+
284+ <a class="quiet" href=(format!("/tags?edit={}", tag.id)) title=(t(lang, Key::EditThisTag))>(t(lang, Key::EditLabel))</a>
285+
286+ <form method="post" action="/api/move_tag">
287+ <input type="hidden" name="tag_id" value=(tag.id.clone())>
288+ <input type="hidden" name="direction" value="up">
289+ <button class="quiet" type="submit" title=(t(lang, Key::MoveTagUp)) aria-label=(t(lang, Key::MoveTagUp))>("\u{2191}")</button>
290+ </form>
291+ <form method="post" action="/api/move_tag">
292+ <input type="hidden" name="tag_id" value=(tag.id.clone())>
293+ <input type="hidden" name="direction" value="down">
294+ <button class="quiet" type="submit" title=(t(lang, Key::MoveTagDown)) aria-label=(t(lang, Key::MoveTagDown))>("\u{2193}")</button>
295+ </form>
296+
297+ if !tag.is_default {
298+ <form method="post" action="/api/delete_tag">
299+ <input type="hidden" name="tag_id" value=(tag.id.clone())>
300+ <button class="quiet quiet-danger" type="submit" title=(t(lang, Key::DeleteThisTag))>(t(lang, Key::Delete))</button>
301+ </form>
302+ }
303+ </div>
304+ }
305+}
306+
307+#[page("/tags")]
308+async fn tags_page(cx: &Cx) -> Result {
309+ let user = match require_admin(cx).await {
310+ Ok(user) => user,
311+ Err(refusal) => {
312+ return view! {
313+ <main class="scaffold-note">
314+ <p>(refusal.message())</p>
315+ <p><a href="/">(t(Lang::En, Key::BackToBoard))</a></p>
316+ </main>
317+ };
318+ }
319+ };
320+ let lang = Lang::from_code(&user.language);
321+ let store = accounts(cx).store().clone();
322+ let tags = match tags_of(&store, &user).await {
323+ Ok(tags) => tags,
324+ Err(refusal) => {
325+ return view! {
326+ <main class="scaffold-note">
327+ <p>(refusal.message_in(lang))</p>
328+ <p><a href="/">(t(lang, Key::BackToBoard))</a></p>
329+ </main>
330+ };
331+ }
332+ };
333+ let edit_id = query_params::<TagsQuery>(cx)?.edit.clone();
334+ let create_refusal = refusal_of(cx, "create_tag");
335+ let rename_refusal = refusal_of(cx, "rename_tag");
336+
337+ view! {
338+ <header class="topbar">
339+ (crate::layout::mark(cx).await?)
340+ (crate::layout::topbar_nav(cx, crate::layout::NavPage::Tags, user.role, lang).await?)
341+ <div class="spacer"></div>
342+ (crate::layout::user_menu(cx, &crate::detail::Me::from(&user), lang).await?)
343+ </header>
344+
345+ <div class="settings-shell">
346+ <main class="settings-stage">
347+ <div class="settings-head">
348+ <h1 class="settings-title">(t(lang, Key::NavTags))</h1>
349+ <span class="chip chip-admin">(t(lang, Key::AdminOnly))</span>
350+ </div>
351+
352+ (composer(cx, create_refusal.as_ref(), lang).await?)
353+
354+ <div class="tag-list">
355+ for tag in &tags {
356+ (tag_row(cx, tag, edit_id.as_deref() == Some(tag.id.as_str()), rename_refusal.as_ref(), lang).await?)
357+ }
358+ </div>
359+ </main>
360+ (crate::dropdown::dropdown_script(cx).await?)
361+ (crate::layout::escape_script(cx).await?)
362+ </div>
363+ }
364+}
crates/izlek-web/tests/http.rsmodified+357 -0
@@ -2477,6 +2477,7 @@ async fn a_member_who_posts_new_limits_anyway_is_refused() {
24772477 ("attachment_limit_mb", "400"),
24782478 ("photo_limit_mb", "19"),
24792479 ("allowed_file_types", "png"),
2480+ ("mail_batch_minutes", "5"),
24802481 ],
24812482 )
24822483 .await;
@@ -2508,6 +2509,7 @@ async fn an_admin_changes_the_limits_and_they_stay_changed() {
25082509 ("attachment_limit_mb", "10"),
25092510 ("photo_limit_mb", "1"),
25102511 ("allowed_file_types", ".PNG, png, pdf"),
2512+ ("mail_batch_minutes", "5"),
25112513 ],
25122514 )
25132515 .await;
@@ -2544,6 +2546,7 @@ async fn a_limit_outside_what_the_disk_should_promise_is_refused() {
25442546 ("attachment_limit_mb", attachment),
25452547 ("photo_limit_mb", photo),
25462548 ("allowed_file_types", ""),
2549+ ("mail_batch_minutes", "5"),
25472550 ],
25482551 )
25492552 .await;
@@ -2575,6 +2578,7 @@ async fn a_file_type_that_is_not_an_extension_is_refused() {
25752578 ("attachment_limit_mb", "25"),
25762579 ("photo_limit_mb", "2"),
25772580 ("allowed_file_types", "../etc/passwd"),
2581+ ("mail_batch_minutes", "5"),
25782582 ],
25792583 )
25802584 .await;
@@ -4112,6 +4116,7 @@ async fn a_file_past_the_workspace_limit_is_refused_before_it_is_kept() {
41124116 ("attachment_limit_mb", "1"),
41134117 ("photo_limit_mb", "2"),
41144118 ("allowed_file_types", ""),
4119+ ("mail_batch_minutes", "5"),
41154120 ],
41164121 )
41174122 .await;
@@ -4165,6 +4170,7 @@ async fn a_file_type_off_the_list_is_refused() {
41654170 ("attachment_limit_mb", "25"),
41664171 ("photo_limit_mb", "2"),
41674172 ("allowed_file_types", "png"),
4173+ ("mail_batch_minutes", "5"),
41684174 ],
41694175 )
41704176 .await;
@@ -5347,6 +5353,7 @@ async fn a_photo_over_the_workspace_limit_is_refused_and_stores_nothing() {
53475353 ("attachment_limit_mb", "25"),
53485354 ("photo_limit_mb", "1"),
53495355 ("allowed_file_types", ""),
5356+ ("mail_batch_minutes", "5"),
53505357 ],
53515358 )
53525359 .await;
@@ -7304,6 +7311,220 @@ async fn a_member_may_not_check_the_sender() {
73047311 assert_ne!(answer.body, "null", "a member was allowed to dial the server");
73057312 }
73067313
7314+// --- tags -------------------------------------------------------------------
7315+
7316+/// Makes a tag over HTTP and hands the store row back — the tests need the
7317+/// id, and the mutation itself is still a real post.
7318+async fn a_tag(app: &App, cookie: &str, name: &str) -> izlek_core::store::Tag {
7319+ let answer = app.post("/api/create_tag", Some(cookie), &[("name", name)]).await;
7320+ assert_eq!(answer.body, "null", "the tag was refused: {}", answer.body);
7321+ let workspace_id = app.workspace_id().await;
7322+ let board = app
7323+ .store
7324+ .board(&workspace_id)
7325+ .await
7326+ .unwrap()
7327+ .expect("no board");
7328+ app.store
7329+ .tags(&board.id)
7330+ .await
7331+ .unwrap()
7332+ .into_iter()
7333+ .find(|tag| tag.name == name)
7334+ .expect("the new tag is not on the board")
7335+}
7336+
7337+#[tokio::test]
7338+async fn a_non_admin_cannot_create_rename_delete_or_move_a_tag() {
7339+ let app = App::open().await;
7340+ let admin_cookie = admin(&app).await;
7341+ let member = invited(&app, &admin_cookie, "mem@izlek.sh", "Mem Ber", Role::Member).await;
7342+
7343+ let create = app.post("/api/create_tag", Some(&member), &[("name", "Sneak")]).await;
7344+ assert!(create.body.contains("Forbidden"), "{}", create.body);
7345+ let rename = app
7346+ .post(
7347+ "/api/rename_tag",
7348+ Some(&member),
7349+ &[("tag_id", "t1"), ("name", "Sneak")],
7350+ )
7351+ .await;
7352+ assert!(rename.body.contains("Forbidden"), "{}", rename.body);
7353+ let delete = app.post("/api/delete_tag", Some(&member), &[("tag_id", "t1")]).await;
7354+ assert!(delete.body.contains("Forbidden"), "{}", delete.body);
7355+ let move_it = app
7356+ .post(
7357+ "/api/move_tag",
7358+ Some(&member),
7359+ &[("tag_id", "t1"), ("direction", "up")],
7360+ )
7361+ .await;
7362+ assert!(move_it.body.contains("Forbidden"), "{}", move_it.body);
7363+}
7364+
7365+#[tokio::test]
7366+async fn a_viewer_cannot_set_a_task_tag() {
7367+ let app = App::open().await;
7368+ let admin_cookie = admin(&app).await;
7369+ let viewer = invited(&app, &admin_cookie, "hush@izlek.sh", "Hush Rao", Role::Viewer).await;
7370+ let column = first_column(&app).await;
7371+ let task = a_task(&app, &admin_cookie, &column, "Label me not").await;
7372+ let aurora = a_tag(&app, &admin_cookie, "Aurora").await;
7373+
7374+ let answer = app
7375+ .post(
7376+ "/api/set_task_tag",
7377+ Some(&viewer),
7378+ &[("task_id", &task), ("tag_id", &aurora.id)],
7379+ )
7380+ .await;
7381+ assert!(answer.body.contains("Forbidden"), "{}", answer.body);
7382+}
7383+
7384+#[tokio::test]
7385+async fn the_task_modal_lists_every_tag_and_names_the_current_one() {
7386+ let app = App::open().await;
7387+ let admin_cookie = admin(&app).await;
7388+ let column = first_column(&app).await;
7389+ let task = a_task(&app, &admin_cookie, &column, "Sort into color").await;
7390+ let aurora = a_tag(&app, &admin_cookie, "Aurora").await;
7391+
7392+ let workspace_id = app.workspace_id().await;
7393+ let board = app
7394+ .store
7395+ .board(&workspace_id)
7396+ .await
7397+ .unwrap()
7398+ .expect("no board");
7399+ let default_id = app
7400+ .store
7401+ .tags(&board.id)
7402+ .await
7403+ .unwrap()
7404+ .into_iter()
7405+ .find(|tag| tag.is_default)
7406+ .expect("no default tag")
7407+ .id;
7408+ let selected = |html: &str, id: &str| html.contains(&format!(r#"value="{id}" selected"#));
7409+
7410+ let page = String::from_utf8(
7411+ app.get(&format!("/?task={task}"), Some(&admin_cookie)).await.bytes,
7412+ )
7413+ .unwrap();
7414+ assert!(page.contains(r#"name="tag_id""#), "no tag field in the modal: {page}");
7415+ assert!(page.contains("General"), "the default tag is not offered: {page}");
7416+ assert!(page.contains("Aurora"), "the new tag is not offered: {page}");
7417+ assert!(selected(&page, &default_id), "the current tag is not named: {page}");
7418+ assert!(!selected(&page, &aurora.id), "an unchosen tag reads as current: {page}");
7419+
7420+ let switched = app
7421+ .post(
7422+ "/api/set_task_tag",
7423+ Some(&admin_cookie),
7424+ &[("task_id", &task), ("tag_id", &aurora.id)],
7425+ )
7426+ .await;
7427+ assert_eq!(switched.body, "null", "the switch was refused: {}", switched.body);
7428+
7429+ let page = String::from_utf8(
7430+ app.get(&format!("/?task={task}"), Some(&admin_cookie)).await.bytes,
7431+ )
7432+ .unwrap();
7433+ assert!(selected(&page, &aurora.id), "the switch did not name Aurora: {page}");
7434+ assert!(!selected(&page, &default_id), "the old tag still reads current: {page}");
7435+}
7436+
7437+#[tokio::test]
7438+async fn the_board_tag_filter_narrows_cards_and_an_unknown_tag_falls_back_to_all() {
7439+ let app = App::open().await;
7440+ let admin_cookie = admin(&app).await;
7441+ let column = first_column(&app).await;
7442+ let first = a_task(&app, &admin_cookie, &column, "Aurora work").await;
7443+ let second = a_task(&app, &admin_cookie, &column, "Boreal work").await;
7444+ let aurora = a_tag(&app, &admin_cookie, "Aurora").await;
7445+ let boreal = a_tag(&app, &admin_cookie, "Boreal").await;
7446+
7447+ let switched = app
7448+ .post(
7449+ "/api/set_task_tag",
7450+ Some(&admin_cookie),
7451+ &[("task_id", &second), ("tag_id", &boreal.id)],
7452+ )
7453+ .await;
7454+ assert_eq!(switched.body, "null", "the switch was refused: {}", switched.body);
7455+
7456+ let tagged = app
7457+ .post(
7458+ "/api/set_task_tag",
7459+ Some(&admin_cookie),
7460+ &[("task_id", &first), ("tag_id", &aurora.id)],
7461+ )
7462+ .await;
7463+ assert_eq!(tagged.body, "null", "the first switch was refused: {}", tagged.body);
7464+
7465+ let filtered = String::from_utf8(
7466+ app.get(&format!("/?tag={}", aurora.id), Some(&admin_cookie))
7467+ .await
7468+ .bytes,
7469+ )
7470+ .unwrap();
7471+ assert!(filtered.contains("Aurora work"), "the tagged card is gone: {filtered}");
7472+ assert!(
7473+ !filtered.contains("Boreal work"),
7474+ "the other card did not filter out: {filtered}"
7475+ );
7476+
7477+ let everything = String::from_utf8(
7478+ app.get("/?tag=bogus", Some(&admin_cookie)).await.bytes,
7479+ )
7480+ .unwrap();
7481+ assert!(
7482+ everything.contains("Aurora work") && everything.contains("Boreal work"),
7483+ "an unknown tag did not fall back to all: {everything}"
7484+ );
7485+ assert!(
7486+ everything.contains("General"),
7487+ "the default tag is not an option in the filter: {everything}"
7488+ );
7489+}
7490+
7491+#[tokio::test]
7492+async fn the_default_tag_cannot_be_deleted_and_ships_no_delete_button() {
7493+ let app = App::open().await;
7494+ let admin_cookie = admin(&app).await;
7495+ let _aurora = a_tag(&app, &admin_cookie, "Aurora").await;
7496+
7497+ let workspace_id = app.workspace_id().await;
7498+ let board = app
7499+ .store
7500+ .board(&workspace_id)
7501+ .await
7502+ .unwrap()
7503+ .expect("no board");
7504+ let default_id = app
7505+ .store
7506+ .tags(&board.id)
7507+ .await
7508+ .unwrap()
7509+ .into_iter()
7510+ .find(|tag| tag.is_default)
7511+ .expect("no default tag")
7512+ .id;
7513+
7514+ let refused = app
7515+ .post("/api/delete_tag", Some(&admin_cookie), &[("tag_id", &default_id)])
7516+ .await;
7517+ assert!(refused.body.contains("Unavailable"), "{}", refused.body);
7518+
7519+ let page = String::from_utf8(app.get("/tags", Some(&admin_cookie)).await.bytes).unwrap();
7520+ assert_eq!(
7521+ page.matches(r#"action="/api/delete_tag""#).count(),
7522+ 1,
7523+ "the default tag's row ships a delete control: {page}"
7524+ );
7525+ assert!(page.contains("Aurora"), "the created tag is not listed: {page}");
7526+}
7527+
73077528 /// An open live stream must not be something the shutdown has to wait out.
73087529 ///
73097530 /// The server stops accepting connections and then gives in-flight requests
@@ -7338,3 +7559,139 @@ async fn a_live_stream_ends_when_the_server_is_told_to_stop() {
73387559 .await;
73397560 assert!(ended.is_ok(), "the stream outlived the stop");
73407561 }
7562+// --- profile page -----------------------------------------------------------
7563+
7564+/// One task row id, for the profile fixture. Fixture setup goes through the
7565+/// store directly, the way `record_sender_check`'s test does.
7566+async fn a_task_by(app: &App, board_id: &str, column_id: &str, title: &str, creator: &str) -> String {
7567+ app.store
7568+ .create_task(izlek_core::store::NewTask {
7569+ board_id,
7570+ column_id,
7571+ parent_id: None,
7572+ title,
7573+ description: "",
7574+ deadline: None,
7575+ created_by: creator,
7576+ })
7577+ .await
7578+ .unwrap()
7579+ .row
7580+ .id
7581+}
7582+
7583+/// Two tasks on Mem's plate, one finished under her, three she opened, four
7584+/// comments — the numbers the profile page has to show: 2 / 1 / 3 / 4.
7585+async fn profile_counts_fixture(app: &App, member: &str, admin: &str) {
7586+ let workspace = app.workspace_id().await;
7587+ let board = app.store.board(&workspace).await.unwrap().expect("no board");
7588+ let columns = app.store.columns(&board.id).await.unwrap();
7589+ let open = columns
7590+ .iter()
7591+ .find(|column| !column.is_done)
7592+ .expect("no open column")
7593+ .id
7594+ .clone();
7595+ let done = columns
7596+ .iter()
7597+ .find(|column| column.is_done)
7598+ .expect("no done column")
7599+ .id
7600+ .clone();
7601+ let now = time::OffsetDateTime::now_utc();
7602+
7603+ let hold = a_task_by(app, &board.id, &open, "Hold the door", admin).await;
7604+ app.store.assign_task(&hold, member).await.unwrap();
7605+ let other = a_task_by(app, &board.id, &open, "Oil the hinges", admin).await;
7606+ app.store.assign_task(&other, member).await.unwrap();
7607+ let finished = a_task_by(app, &board.id, &open, "Paint the frame", admin).await;
7608+ app.store.assign_task(&finished, member).await.unwrap();
7609+ app.store.move_task(&finished, &open, &done, admin, now).await.unwrap();
7610+ for title in ["Sweep", "Mop", "Dust"] {
7611+ a_task_by(app, &board.id, &open, title, member).await;
7612+ }
7613+ for _ in 0..4 {
7614+ app.store.add_comment(&hold, member, "a note", now).await.unwrap();
7615+ }
7616+}
7617+
7618+#[tokio::test]
7619+async fn a_member_may_read_another_members_profile_name_address_and_counts() {
7620+ let app = App::open().await;
7621+ let admin_cookie = admin(&app).await;
7622+ invited(&app, &admin_cookie, "mem@izlek.sh", "Mem Ber", Role::Member).await;
7623+ let reader = invited(&app, &admin_cookie, "ivy@izlek.sh", "Ivy Lear", Role::Member).await;
7624+ let mem_id = user_id(&app, "mem@izlek.sh").await;
7625+ let admin_id = app
7626+ .store
7627+ .users(&app.workspace_id().await)
7628+ .await
7629+ .unwrap()
7630+ .into_iter()
7631+ .find(|user| user.role == Role::Admin)
7632+ .unwrap()
7633+ .id;
7634+ profile_counts_fixture(&app, &mem_id, &admin_id).await;
7635+
7636+ let page = app.get(&format!("/people/{mem_id}"), Some(&reader)).await;
7637+ assert_eq!(page.status.as_u16(), 200);
7638+ let html = String::from_utf8(page.bytes).unwrap();
7639+ assert!(html.contains("Mem Ber"), "{html}");
7640+ assert!(html.contains("mem@izlek.sh"), "{html}");
7641+ for count in [2, 1, 3, 4] {
7642+ assert_eq!(
7643+ html.matches(&format!(">{count}</dd>")).count(),
7644+ 1,
7645+ "the {count} stat is not on the page once: {html}"
7646+ );
7647+ }
7648+}
7649+
7650+#[tokio::test]
7651+async fn a_profile_is_not_found_signed_out_or_outside_the_workspace() {
7652+ let app = App::open().await;
7653+ let admin_cookie = admin(&app).await;
7654+ invited(&app, &admin_cookie, "mem@izlek.sh", "Mem Ber", Role::Member).await;
7655+ let mem_id = user_id(&app, "mem@izlek.sh").await;
7656+
7657+ let signed_out = app.get(&format!("/people/{mem_id}"), None).await;
7658+ assert_eq!(signed_out.status.as_u16(), 404, "never a 403, never a page");
7659+
7660+ // A person who exists, but in another workspace, reads exactly like a
7661+ // missing one — the id is not looked at twice.
7662+ let other = App::open().await;
7663+ // A workspace has to be claimed before it holds anybody to be a stranger.
7664+ let _ = admin(&other).await;
7665+ let stranger = other.store.users(&other.workspace_id().await).await.unwrap()[0]
7666+ .id
7667+ .clone();
7668+ let foreign = app.get(&format!("/people/{stranger}"), Some(&admin_cookie)).await;
7669+ assert_eq!(foreign.status.as_u16(), 404);
7670+
7671+ let missing = app.get("/people/nobody", Some(&admin_cookie)).await;
7672+ assert_eq!(missing.status.as_u16(), 404);
7673+}
7674+
7675+#[tokio::test]
7676+async fn only_your_own_profile_offers_the_edit_link() {
7677+ let app = App::open().await;
7678+ let admin_cookie = admin(&app).await;
7679+ invited(&app, &admin_cookie, "mem@izlek.sh", "Mem Ber", Role::Member).await;
7680+ let mem_id = user_id(&app, "mem@izlek.sh").await;
7681+ let ivy = invited(&app, &admin_cookie, "ivy@izlek.sh", "Ivy Lear", Role::Member).await;
7682+ let ivy_id = user_id(&app, "ivy@izlek.sh").await;
7683+
7684+ let own = app.get(&format!("/people/{ivy_id}"), Some(&ivy)).await;
7685+ let own_html = String::from_utf8(own.bytes).unwrap();
7686+ assert!(
7687+ own_html.contains(r#"href="/settings?section=profile""#),
7688+ "no edit link on your own profile: {own_html}"
7689+ );
7690+
7691+ let theirs = app.get(&format!("/people/{mem_id}"), Some(&ivy)).await;
7692+ let theirs_html = String::from_utf8(theirs.bytes).unwrap();
7693+ assert!(
7694+ !theirs_html.contains("settings?section=profile"),
7695+ "someone else's profile grew an editor: {theirs_html}"
7696+ );
7697+}
\ No newline at end of file
style/_ledger.scssmodified+8 -0
@@ -103,6 +103,14 @@
103103 &-off { background: transparent; }
104104 }
105105
106+ .tag-row {
107+ background: transparent;
108+ border: none;
109+ border-bottom: 1px solid var(--border);
110+ border-radius: 0;
111+ padding: 14px 2px;
112+ }
113+
106114 // Activity log reads as a ruled ledger column too: no boxes, the actor
107115 // named in the display face like .member-name.
108116 .log-row {
style/main.scssmodified+143 -0
@@ -348,6 +348,18 @@ body:has(.settings-shell) {
348348 > .settings-shell { flex: 1; min-height: 0; }
349349 }
350350
351+// A profile is one column of its own; it pans inside itself like every other
352+// page here, and the document never grows a scrollbar.
353+body:has(.people-shell) {
354+ height: 100vh;
355+ overflow: hidden;
356+ display: flex;
357+ flex-direction: column;
358+
359+ > * { flex: none; }
360+ > .people-shell { flex: 1; min-height: 0; }
361+}
362+
351363 a {
352364 color: var(--accent);
353365 transition: color var(--dur-fast) var(--ease);
@@ -882,6 +894,15 @@ a {
882894 color: var(--muted);
883895 }
884896
897+.card-tag {
898+ font-family: var(--font-mono);
899+ font-size: 11px;
900+ color: var(--muted);
901+ background: var(--surface-sunken);
902+ border-radius: var(--radius-sm);
903+ padding: 2px 6px;
904+}
905+
885906 /// Parts still open is the same warning the blocker chips carry: this card
886907 /// cannot reach the done column yet.
887908 .card-subtasks-open { color: var(--warn-ink); }
@@ -3461,3 +3482,125 @@ input[type="radio"] {
34613482 flex-direction: column;
34623483 gap: 6px;
34633484 }
3485+
3486+.tag-list {
3487+ display: flex;
3488+ flex-direction: column;
3489+ gap: 10px;
3490+}
3491+
3492+.tag-row {
3493+ display: flex;
3494+ align-items: center;
3495+ gap: 14px;
3496+ padding: 16px;
3497+ background: var(--surface);
3498+ border: 1px solid var(--border);
3499+ border-radius: var(--radius-md);
3500+}
3501+
3502+.tag-name {
3503+ flex-grow: 1;
3504+ min-width: 0;
3505+ font-size: 13px;
3506+ overflow: hidden;
3507+ text-overflow: ellipsis;
3508+ white-space: nowrap;
3509+}
3510+
3511+.tag-new {
3512+ background: var(--surface);
3513+ border: 1px solid var(--border);
3514+ border-radius: var(--radius-lg);
3515+}
3516+
3517+.tag-new-open {
3518+ display: flex;
3519+ align-items: center;
3520+ height: var(--control-h);
3521+ padding: 0 16px;
3522+ font-size: 13px;
3523+ font-weight: 600;
3524+ color: var(--accent-ink);
3525+ cursor: pointer;
3526+ list-style: none;
3527+
3528+ &::marker, &::-webkit-details-marker { display: none; }
3529+ &::before { content: '+'; margin-right: 8px; font-size: 13px; }
3530+}
3531+
3532+.tag-form {
3533+ display: flex;
3534+ flex-direction: column;
3535+ gap: 20px;
3536+ padding: 0 16px 16px;
3537+ border-top: 1px solid var(--border);
3538+ padding-top: 16px;
3539+}
3540+
3541+.tag-field {
3542+ display: flex;
3543+ flex-direction: column;
3544+ gap: 6px;
3545+}
3546+
3547+// --- Profile (a member's page) ----------------------------------------------
3548+
3549+.people-shell {
3550+ width: 100%;
3551+ max-width: 860px;
3552+ margin: 0 auto;
3553+ padding: 24px 32px 40px;
3554+ display: flex;
3555+ flex-direction: column;
3556+ gap: 20px;
3557+ overflow-y: auto;
3558+ scrollbar-width: none;
3559+
3560+ &::-webkit-scrollbar { display: none; }
3561+ > * { flex: none; }
3562+}
3563+
3564+.people-stats {
3565+ display: flex;
3566+ flex-wrap: wrap;
3567+ gap: 28px;
3568+ margin: 0;
3569+
3570+ dt {
3571+ font-size: 11px;
3572+ letter-spacing: 0.08em;
3573+ text-transform: uppercase;
3574+ color: var(--muted);
3575+ }
3576+
3577+ dd {
3578+ margin: 0;
3579+ font-size: 20px;
3580+ font-weight: 600;
3581+ font-variant-numeric: tabular-nums;
3582+ }
3583+}
3584+
3585+.people-feed {
3586+ list-style: none;
3587+ margin: 0;
3588+ padding: 0;
3589+ display: flex;
3590+ flex-direction: column;
3591+ gap: 8px;
3592+
3593+ li {
3594+ display: flex;
3595+ align-items: baseline;
3596+ gap: 10px;
3597+ }
3598+}
3599+
3600+.people-feed-day {
3601+ margin-left: auto;
3602+ flex: none;
3603+ white-space: nowrap;
3604+ color: var(--muted);
3605+ font-size: 12px;
3606+}