forge
Explore
Log in

Don't you dare go Hollow

A subtask is a task with a parent

Browse files at this commit

71160f367f64a4d3dcca0702d4d773ef31303704Ahmet Kaan GümüşParent: 8196294
  • feat
    • a subtask is a task with a parent
Show full message
🗃️ feat(core): a subtask is a task with a parent

The schema is one file again. Three of the twenty migrations did not
tweak a table but rebuilt it — SQLite cannot drop a CHECK or a foreign
key in place — so 0001 described a `mail_rule`, a `transition` and an
`activity` that no running database had. Nothing is released, so the
chain collapses into the tables as they actually are, carrying the
reasoning each rebuild wrote down onto the table it explains. Two dead
columns go with it (`user.photo_path`, `board.next_task_no`), and
`task_dependency` finally states in SQL what only application code
enforced: a task cannot block itself.

`task.parent_id` is the whole of the subtask feature in this schema. A
subtask has every column a task has, so it carries assignees, a
deadline, comments, files, activity and mail with no new machinery, and
promoting one to a task of its own is a single UPDATE rather than a move
between tables.

Two rules the column cannot state itself are held in the store: subtasks
go one level deep, and a parent and its child share a board. The first
is refused from both sides — nothing may be created under a subtask, and
a task that already has children cannot become one.
crates/izlek-core/migrations/0001_init.sqlmodified+244 -40
@@ -1,26 +1,55 @@
1--- Izlek initial schema.1+-- Izlek's schema, whole, in one file.
2 --2 --
3 -- Plain versioned SQL applied at boot: Turso has no migration runner of its3 -- 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.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 UUIDs as text.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 replaces a chain of twenty migrations. Three of them (the old
10+-- 0013, 0014, 0019) did not tweak a table but rebuilt it — SQLite cannot drop
11+-- a CHECK or a foreign key in place — so the shape a reader found here no
12+-- longer matched the shape a running database had. Nothing has been released,
13+-- so the chain was collapsed into this: the tables as they actually are. The
14+-- reasoning those migrations carried is kept, on the tables it explains.
6 15
7 CREATE TABLE workspace (16 CREATE TABLE workspace (
8 id TEXT PRIMARY KEY,17 id TEXT PRIMARY KEY,
9 name TEXT NOT NULL,18 name TEXT NOT NULL,
10 created_at TEXT NOT NULL,19 created_at TEXT NOT NULL,
11- -- The single sender every mail in the workspace goes through. Written by20+ -- Limits. Each states its consequence in the UI, not here. They are
12- -- the admin in Settings; the password is never returned to the client.21+ -- workspace content — an admin edits them, and no restart should be
22+ -- needed to raise an attachment ceiling.
23+ attachment_limit_bytes INTEGER NOT NULL DEFAULT 26214400,
24+ photo_limit_bytes INTEGER NOT NULL DEFAULT 2097152,
25+ -- JSON array of allowed extensions. An empty array means every type.
26+ allowed_file_types TEXT NOT NULL DEFAULT '[]',
27+ -- The single sender every mail in the workspace goes through, written by
28+ -- the admin in Settings rather than by whoever has a shell on the box: a
29+ -- three-person team has those be different people, and the second one is
30+ -- not always awake.
31+ --
32+ -- `smtp_password` holds ciphertext, never the typed string. The server
33+ -- has to present the password to the mail host on every send, so a
34+ -- one-way hash is impossible; instead `store::secret` seals it under a
35+ -- key kept in `izlek.key` beside this file, so a database copied for a
36+ -- backup does not carry a working credential with it. No field on
37+ -- `Workspace` exposes it — it is written by `Store::set_sender` and read
38+ -- by `Store::smtp_password`, which only the mailer calls.
13 smtp_host TEXT,39 smtp_host TEXT,
14 smtp_port INTEGER,40 smtp_port INTEGER,
15 smtp_username TEXT,41 smtp_username TEXT,
16 smtp_password TEXT,42 smtp_password TEXT,
17 smtp_from_name TEXT,43 smtp_from_name TEXT,
18 smtp_from_address TEXT,44 smtp_from_address TEXT,
19- -- Limits. Each states its consequence in the UI, not here.45+ -- The result of the last "send a test mail to myself", kept rather than
20- attachment_limit_bytes INTEGER NOT NULL DEFAULT 26214400,46+ -- shown once: an admin fills the sender in, presses the button, and comes
21- photo_limit_bytes INTEGER NOT NULL DEFAULT 2097152,47+ -- back tomorrow wondering whether it ever worked. `smtp_test_error` is the
22- -- JSON array of allowed extensions. An empty array means every type.48+ -- mail server's own words, so the admin can act on them; the mailer builds
23- allowed_file_types TEXT NOT NULL DEFAULT '[]'49+ -- its errors from what the server said, never from the credentials it sent.
50+ smtp_test_at INTEGER,
51+ smtp_test_ms INTEGER,
52+ smtp_test_error TEXT
24 );53 );
25 54
26 CREATE TABLE user (55 CREATE TABLE user (
@@ -33,14 +62,37 @@ CREATE TABLE user (
33 -- NULL until the person picks a password on first sign-in. The admin62 -- NULL until the person picks a password on first sign-in. The admin
34 -- creates the account with a name and an address and nothing else.63 -- creates the account with a name and an address and nothing else.
35 password_hash TEXT,64 password_hash TEXT,
36- photo_path TEXT,65+ -- Whoever made this account, so the first-sign-in screen can greet the
66+ -- invited person by the inviter's name instead of reading their own name
67+ -- back to them. NULL for the first account, which nobody invited. A
68+ -- reference rather than a copied name, so a later rename is reflected.
69+ invited_by TEXT REFERENCES user(id),
70+ -- Display preferences. Stored data everywhere else stays UTC and
71+ -- language-neutral; these only change how a browser renders it for the
72+ -- one person signed in as this user, and nothing stored depends on them.
73+ timezone TEXT NOT NULL DEFAULT 'UTC',
74+ theme TEXT NOT NULL DEFAULT 'light',
75+ language TEXT NOT NULL DEFAULT 'en',
76+ ui TEXT NOT NULL DEFAULT 'instrument',
77+ -- The profile picture lives here as bytes, the way an attachment does:
78+ -- no filesystem path survives a backup or a move.
79+ photo BLOB,
80+ photo_mime TEXT,
37 created_at TEXT NOT NULL,81 created_at TEXT NOT NULL,
38 last_signed_in_at TEXT82 last_signed_in_at TEXT
39 );83 );
40 CREATE UNIQUE INDEX user_email_unique ON user(workspace_id, email);84 CREATE UNIQUE INDEX user_email_unique ON user(workspace_id, email);
41 85
42--- First sign-in / resend links. Only the hash is stored: the plaintext is shown86+-- One workspace, one owner. The singleton column is the whole point: the row
43--- once when the admin creates or resends it.87+-- can exist at most once, so a second claim cannot race a first one.
88+CREATE TABLE workspace_owner (
89+ singleton INTEGER PRIMARY KEY,
90+ user_id TEXT NOT NULL REFERENCES user(id),
91+ claimed_at TEXT NOT NULL
92+);
93+
94+-- First sign-in / resend links. Only the hash is stored: the plaintext is
95+-- shown once when the admin creates or resends it.
44 CREATE TABLE signin_link (96 CREATE TABLE signin_link (
45 id TEXT PRIMARY KEY,97 id TEXT PRIMARY KEY,
46 user_id TEXT NOT NULL REFERENCES user(id),98 user_id TEXT NOT NULL REFERENCES user(id),
@@ -51,10 +103,30 @@ CREATE TABLE signin_link (
51 );103 );
52 CREATE UNIQUE INDEX signin_link_token ON signin_link(token_hash);104 CREATE UNIQUE INDEX signin_link_token ON signin_link(token_hash);
53 105
106+CREATE TABLE session (
107+ id TEXT PRIMARY KEY,
108+ user_id TEXT NOT NULL REFERENCES user(id),
109+ token_hash TEXT NOT NULL,
110+ created_at TEXT NOT NULL,
111+ expires_at TEXT NOT NULL,
112+ revoked_at TEXT
113+);
114+CREATE UNIQUE INDEX session_token ON session(token_hash);
115+CREATE INDEX session_by_user ON session(user_id);
116+
117+-- The rate-limit ledger: one row per attempt, pruned by age.
118+CREATE TABLE auth_attempt (
119+ id TEXT PRIMARY KEY,
120+ bucket TEXT NOT NULL,
121+ attempted_at TEXT NOT NULL
122+);
123+CREATE INDEX auth_attempt_by_bucket ON auth_attempt(bucket, attempted_at);
124+
54 CREATE TABLE board (125 CREATE TABLE board (
55 id TEXT PRIMARY KEY,126 id TEXT PRIMARY KEY,
56 workspace_id TEXT NOT NULL REFERENCES workspace(id),127 workspace_id TEXT NOT NULL REFERENCES workspace(id),
57 name TEXT NOT NULL,128 name TEXT NOT NULL,
129+ -- The key prefix this board's tasks carry (`DZ-14`).
58 task_prefix TEXT NOT NULL DEFAULT 'DZ',130 task_prefix TEXT NOT NULL DEFAULT 'DZ',
59 created_at TEXT NOT NULL131 created_at TEXT NOT NULL
60 );132 );
@@ -68,10 +140,27 @@ CREATE TABLE board_column (
68 is_done INTEGER NOT NULL DEFAULT 0140 is_done INTEGER NOT NULL DEFAULT 0
69 );141 );
70 142
143+-- A task, and a subtask, which is the same thing with a parent.
144+--
145+-- `parent_id` is the whole of the subtask feature in this schema: a subtask
146+-- has every column a task has, so it carries assignees, a deadline, comments,
147+-- files, activity and mail exactly like anything else, and promoting one to
148+-- a task of its own is a single UPDATE rather than a move between tables.
149+--
150+-- Two rules the column cannot state itself, enforced in the store instead:
151+-- a parent must have `parent_id IS NULL` (one level, never a tree), and a
152+-- child sits on its parent's board. SQLite cannot ask, in a CHECK, whether
153+-- the row a foreign key points at has a NULL parent.
154+--
155+-- The board shows only rows with no parent; a subtask reaches its own detail
156+-- page through its parent's.
71 CREATE TABLE task (157 CREATE TABLE task (
72 id TEXT PRIMARY KEY,158 id TEXT PRIMARY KEY,
73 board_id TEXT NOT NULL REFERENCES board(id),159 board_id TEXT NOT NULL REFERENCES board(id),
74- -- Human key from the mockups, e.g. DZ-14.160+ parent_id TEXT REFERENCES task(id),
161+ -- Human key from the mockups, e.g. DZ-14. The tail is the end of the
162+ -- task's own ULID rather than a per-board counter: a counter leaves
163+ -- visible gaps once tasks are deleted.
75 task_key TEXT NOT NULL,164 task_key TEXT NOT NULL,
76 title TEXT NOT NULL,165 title TEXT NOT NULL,
77 description TEXT NOT NULL DEFAULT '',166 description TEXT NOT NULL DEFAULT '',
@@ -86,6 +175,7 @@ CREATE TABLE task (
86 );175 );
87 CREATE UNIQUE INDEX task_key_unique ON task(board_id, task_key);176 CREATE UNIQUE INDEX task_key_unique ON task(board_id, task_key);
88 CREATE INDEX task_by_column ON task(column_id);177 CREATE INDEX task_by_column ON task(column_id);
178+CREATE INDEX task_by_parent ON task(parent_id);
89 179
90 CREATE TABLE task_assignee (180 CREATE TABLE task_assignee (
91 task_id TEXT NOT NULL REFERENCES task(id),181 task_id TEXT NOT NULL REFERENCES task(id),
@@ -101,12 +191,17 @@ CREATE TABLE task_watcher (
101 191
102 -- blocked_task_id is blocked by blocking_task_id. cleared_at is set when the192 -- blocked_task_id is blocked by blocking_task_id. cleared_at is set when the
103 -- blocking task finishes, which is what the "you can start now" rule reads.193 -- blocking task finishes, which is what the "you can start now" rule reads.
194+--
195+-- The CHECK is new: a task blocking itself was only ever stopped in
196+-- application code, and a row like that would make a card permanently and
197+-- unfixably blocked by its own existence.
104 CREATE TABLE task_dependency (198 CREATE TABLE task_dependency (
105 blocked_task_id TEXT NOT NULL REFERENCES task(id),199 blocked_task_id TEXT NOT NULL REFERENCES task(id),
106 blocking_task_id TEXT NOT NULL REFERENCES task(id),200 blocking_task_id TEXT NOT NULL REFERENCES task(id),
107 created_at TEXT NOT NULL,201 created_at TEXT NOT NULL,
108 cleared_at TEXT,202 cleared_at TEXT,
109- PRIMARY KEY (blocked_task_id, blocking_task_id)203+ PRIMARY KEY (blocked_task_id, blocking_task_id),
204+ CHECK (blocked_task_id <> blocking_task_id)
110 );205 );
111 206
112 CREATE TABLE comment (207 CREATE TABLE comment (
@@ -118,6 +213,14 @@ CREATE TABLE comment (
118 );213 );
119 CREATE INDEX comment_by_task ON comment(task_id);214 CREATE INDEX comment_by_task ON comment(task_id);
120 215
216+-- Attachments live in the database file, not on disk beside it.
217+--
218+-- Izlek is one process over one file, and a second place to keep state is a
219+-- second thing to back up, to lock, and to get out of step with the rows that
220+-- name it. And a path is exactly where an uploaded file name must never end
221+-- up: `../../etc` is a valid file name and a terrible path. Keeping the bytes
222+-- here means `file_name` is only ever a label printed on a chip, never
223+-- anything the server resolves.
121 CREATE TABLE attachment (224 CREATE TABLE attachment (
122 id TEXT PRIMARY KEY,225 id TEXT PRIMARY KEY,
123 task_id TEXT NOT NULL REFERENCES task(id),226 task_id TEXT NOT NULL REFERENCES task(id),
@@ -125,54 +228,155 @@ CREATE TABLE attachment (
125 file_name TEXT NOT NULL,228 file_name TEXT NOT NULL,
126 mime_type TEXT NOT NULL,229 mime_type TEXT NOT NULL,
127 size_bytes INTEGER NOT NULL,230 size_bytes INTEGER NOT NULL,
128- stored_path TEXT NOT NULL,231+ bytes BLOB NOT NULL,
129 uploaded_by TEXT NOT NULL REFERENCES user(id),232 uploaded_by TEXT NOT NULL REFERENCES user(id),
130 created_at TEXT NOT NULL233 created_at TEXT NOT NULL
131 );234 );
235+CREATE INDEX attachment_by_task ON attachment(task_id);
132 236
133--- The activity strip in the task detail: who did what, and whether it mailed.237+-- Every move of a card from one column to another, written as a fact in the
238+-- same transaction as the move itself.
239+--
240+-- The mail rules trigger on the transition, not on the task's current column:
241+-- a card that goes Review -> Done -> Review has crossed into Done once, and
242+-- nothing recomputed from `task.column_id` afterwards can tell you that.
243+--
244+-- `from_column` deliberately carries no REFERENCES: a task created straight
245+-- into a column writes a transition with `from_column = ''`, meaning "created
246+-- into", so a rule watching that column fires for a new card and not only for
247+-- one dragged in later. No column's id is ever ''.
248+CREATE TABLE transition (
249+ id TEXT PRIMARY KEY,
250+ task_id TEXT NOT NULL REFERENCES task(id),
251+ from_column TEXT NOT NULL,
252+ to_column TEXT NOT NULL REFERENCES board_column(id),
253+ actor_id TEXT NOT NULL REFERENCES user(id),
254+ created_at TEXT NOT NULL
255+);
256+CREATE INDEX transition_by_task ON transition(task_id, created_at);
257+
258+-- A deletion that let other tasks go, recorded as a fact.
259+--
260+-- The unblocked rule has two causes and only one of them is a crossing: a
261+-- blocker can finish, or a blocker can be deleted. The crossing already has a
262+-- row in `transition`; the deletion had nowhere to be written, so a mail owed
263+-- because of one had no event to hang from and no way to be rebuilt on a
264+-- retry. This is that row.
265+--
266+-- `cause_key` and `cause_title` are copied rather than joined: the task they
267+-- name is deleted, and a mail sent an hour later still has to be able to say
268+-- which task it was.
269+CREATE TABLE freeing (
270+ id TEXT PRIMARY KEY,
271+ board_id TEXT NOT NULL REFERENCES board(id),
272+ cause_key TEXT NOT NULL,
273+ cause_title TEXT NOT NULL,
274+ actor_id TEXT NOT NULL REFERENCES user(id),
275+ created_at TEXT NOT NULL
276+);
277+CREATE INDEX freeing_by_board ON freeing(board_id, created_at);
278+
279+-- The activity strip in the task detail: who did what. `task_id` is nullable
280+-- because account and admin events — sign-ins, invites, role changes — have
281+-- no task to sit under, and still have to be loggable.
134 CREATE TABLE activity (282 CREATE TABLE activity (
135 id TEXT PRIMARY KEY,283 id TEXT PRIMARY KEY,
136- task_id TEXT NOT NULL REFERENCES task(id),284+ task_id TEXT REFERENCES task(id),
137 actor_id TEXT REFERENCES user(id),285 actor_id TEXT REFERENCES user(id),
138 kind TEXT NOT NULL,286 kind TEXT NOT NULL,
139 detail TEXT NOT NULL DEFAULT '',287 detail TEXT NOT NULL DEFAULT '',
140 created_at TEXT NOT NULL288 created_at TEXT NOT NULL
141 );289 );
142 CREATE INDEX activity_by_task ON activity(task_id);290 CREATE INDEX activity_by_task ON activity(task_id);
291+CREATE INDEX activity_recent ON activity(created_at);
143 292
144--- Mail rules are written only by the admin and are always on. A rule that293+-- Mail rules are written only by the admin.
145--- addresses an external address stays off until that address confirms.294+--
295+-- `trigger_kind` carries no CHECK on purpose: the set of triggers grows
296+-- without a schema change. `audience` does carry one, because those three
297+-- values are the only audiences the engine knows how to resolve.
146 CREATE TABLE mail_rule (298 CREATE TABLE mail_rule (
147- id TEXT PRIMARY KEY,299+ id TEXT PRIMARY KEY,
148- workspace_id TEXT NOT NULL REFERENCES workspace(id),300+ board_id TEXT NOT NULL REFERENCES board(id),
149- board_id TEXT REFERENCES board(id),301+ trigger_kind TEXT NOT NULL,
150- -- 'status_becomes' | 'deadline_in' | 'unblocked'302+ trigger_column TEXT REFERENCES board_column(id),
151- trigger_kind TEXT NOT NULL,303+ subject TEXT NOT NULL,
152- trigger_value TEXT NOT NULL,304+ -- 'assignees' — the people the card points at; 'board' — everyone who can
153- subject TEXT NOT NULL,305+ -- write on the board; 'creator' — whoever opened the card.
154- -- 'assignees' | 'assignees_watchers' | 'everyone' | 'external'306+ audience TEXT NOT NULL CHECK (audience IN ('assignees', 'board', 'creator')),
155- audience TEXT NOT NULL,307+ enabled INTEGER NOT NULL DEFAULT 1,
156- external_address TEXT,308+ -- Fold the task's own facts into the body instead of the subject line
157- external_confirmed INTEGER NOT NULL DEFAULT 0,309+ -- being all the recipient reads. Off by default.
158- created_at TEXT NOT NULL,310+ include_task_details INTEGER NOT NULL DEFAULT 0,
159- last_sent_at TEXT311+ created_at TEXT NOT NULL,
312+ -- A status rule names a column and an unblocked rule does not. The check
313+ -- is here so a half-written rule cannot be stored at all.
314+ CHECK ((trigger_kind = 'status') = (trigger_column IS NOT NULL))
160 );315 );
316+CREATE INDEX mail_rule_by_board ON mail_rule(board_id);
161 317
162--- One row per (rule, task, transition) actually sent, so a revert-then-redo318+-- One row per mail owed, from the moment it is claimed until it is sent or
163--- does not mail twice.319+-- abandoned.
320+--
321+-- Three shapes share the table. A 'rule' send is owed to somebody because a
322+-- rule matched an event on a task, and carries all three. An 'invite' or a
323+-- 'notice' has none of them — a person is invited before they have a task, a
324+-- transition, or a rule to owe them anything — and carries its own subject
325+-- and body instead of getting them from `mail_rule`. The two CHECKs make the
326+-- shapes exclusive, so a half-built row cannot be stored.
327+--
328+-- `event_id` names a transition or a freeing without a foreign key: two
329+-- tables can cause a send, so the column cannot point at either and hold both.
164 CREATE TABLE mail_send (330 CREATE TABLE mail_send (
331+ id TEXT PRIMARY KEY,
332+ rule_id TEXT REFERENCES mail_rule(id) ON DELETE CASCADE,
333+ event_id TEXT,
334+ task_id TEXT REFERENCES task(id),
335+ recipient TEXT NOT NULL,
336+ state TEXT NOT NULL CHECK (state IN ('pending', 'sent', 'failed', 'abandoned')),
337+ attempts INTEGER NOT NULL DEFAULT 0,
338+ last_error TEXT,
339+ claimed_at TEXT NOT NULL,
340+ next_attempt_at TEXT,
341+ sent_at TEXT,
342+ kind TEXT NOT NULL DEFAULT 'rule' CHECK (kind IN ('rule', 'invite', 'notice')),
343+ subject TEXT,
344+ body TEXT,
345+ CHECK ((kind = 'rule') = (rule_id IS NOT NULL AND event_id IS NOT NULL AND task_id IS NOT NULL)),
346+ CHECK ((kind IN ('invite', 'notice')) = (subject IS NOT NULL AND body IS NOT NULL))
347+);
348+CREATE UNIQUE INDEX mail_send_once ON mail_send(rule_id, event_id, task_id, recipient);
349+CREATE INDEX mail_send_owed ON mail_send(next_attempt_at);
350+CREATE INDEX mail_send_by_rule ON mail_send(rule_id, sent_at);
351+
352+-- What the mail engine decided, for every rule and every event, not just the
353+-- mails it sent.
354+--
355+-- `mail_send` only exists once a mail is owed and claimed; a card that moved
356+-- but matched no rule, a rule that was disabled, a task deleted before its
357+-- mail could go out — none of that left a trace. This is that trace, so "why
358+-- did nobody get mailed" has an answer that is not "look at the logs from
359+-- that day".
360+--
361+-- `task_id` carries no foreign key on purpose: a `task_gone` row exists
362+-- precisely because the task it names no longer does, and it has to keep
363+-- saying so afterwards.
364+CREATE TABLE mail_decision (
165 id TEXT PRIMARY KEY,365 id TEXT PRIMARY KEY,
166- rule_id TEXT NOT NULL REFERENCES mail_rule(id),366+ rule_id TEXT NOT NULL REFERENCES mail_rule(id) ON DELETE CASCADE,
167- task_id TEXT NOT NULL REFERENCES task(id),367+ event_id TEXT NOT NULL,
168- transition TEXT NOT NULL,368+ task_id TEXT NOT NULL,
169- sent_at TEXT NOT NULL369+ outcome TEXT NOT NULL CHECK (outcome IN
370+ ('owed', 'already_owed', 'no_recipients', 'not_matched', 'disabled', 'task_gone')),
371+ detail TEXT NOT NULL DEFAULT '',
372+ created_at TEXT NOT NULL
170 );373 );
171-CREATE UNIQUE INDEX mail_send_once ON mail_send(rule_id, task_id, transition);374+CREATE UNIQUE INDEX mail_decision_once ON mail_decision(rule_id, event_id, task_id);
375+CREATE INDEX mail_decision_recent ON mail_decision(created_at);
172 376
173 -- Read-only links: izlek.sh/v/<id>. Only the hash of the token is stored, so a377 -- Read-only links: izlek.sh/v/<id>. Only the hash of the token is stored, so a
174 -- database copy does not hand out working links; revoking is server-side and378 -- database copy does not hand out working links; revoking is server-side and
175--- immediate.379+-- immediate. Designed but not yet built — no store method writes this table.
176 CREATE TABLE view_link (380 CREATE TABLE view_link (
177 id TEXT PRIMARY KEY,381 id TEXT PRIMARY KEY,
178 workspace_id TEXT NOT NULL REFERENCES workspace(id),382 workspace_id TEXT NOT NULL REFERENCES workspace(id),
crates/izlek-core/migrations/0002_auth.sqldeleted+0 -33
@@ -1,33 +0,0 @@
1--- Sessions, the single-owner claim, and the rate-limit ledger.
2-
3--- Exactly one row, ever. The primary key is the whole point: two requests
4--- racing to claim an empty workspace both try to insert singleton = 1 and the
5--- database picks the winner, inside the same transaction that writes the
6--- workspace and its admin.
7-CREATE TABLE workspace_owner (
8- singleton INTEGER PRIMARY KEY,
9- user_id TEXT NOT NULL REFERENCES user(id),
10- claimed_at TEXT NOT NULL
11-);
12-
13--- A signed-in browser. Only the hash of the cookie token is stored, exactly
14--- like sign-in links and read-only links.
15-CREATE TABLE session (
16- id TEXT PRIMARY KEY,
17- user_id TEXT NOT NULL REFERENCES user(id),
18- token_hash TEXT NOT NULL,
19- created_at TEXT NOT NULL,
20- expires_at TEXT NOT NULL,
21- revoked_at TEXT
22-);
23-CREATE UNIQUE INDEX session_token ON session(token_hash);
24-CREATE INDEX session_by_user ON session(user_id);
25-
26--- Sign-in attempts and link redemptions, one row per attempt, counted over a
27--- window. The bucket is the address or the client address, never the password.
28-CREATE TABLE auth_attempt (
29- id TEXT PRIMARY KEY,
30- bucket TEXT NOT NULL,
31- attempted_at TEXT NOT NULL
32-);
33-CREATE INDEX auth_attempt_by_bucket ON auth_attempt(bucket, attempted_at);
crates/izlek-core/migrations/0003_transition.sqldeleted+0 -17
@@ -1,17 +0,0 @@
1--- Every move of a card from one column to another, written as a fact in the
2--- same transaction as the move itself.
3---
4--- The mail rules trigger on the transition, not on the task's current column:
5--- a card that goes Review -> Done -> Review has crossed into Done once, and
6--- nothing recomputed from `task.column_id` afterwards can tell you that. So
7--- this table is the record, and the rules read it.
8-CREATE TABLE transition (
9- id TEXT PRIMARY KEY,
10- task_id TEXT NOT NULL REFERENCES task(id),
11- from_column TEXT NOT NULL REFERENCES board_column(id),
12- to_column TEXT NOT NULL REFERENCES board_column(id),
13- actor_id TEXT NOT NULL REFERENCES user(id),
14- created_at TEXT NOT NULL
15-);
16-
17-CREATE INDEX transition_by_task ON transition(task_id, created_at);
crates/izlek-core/migrations/0004_mail.sqldeleted+0 -64
@@ -1,64 +0,0 @@
1--- Mail rules and the ledger of what they sent.
2---
3--- 0001 sketched both tables before there was an engine to read them, and the
4--- sketch is not the shape the engine needs: a rule needs a column id rather
5--- than a free-text trigger value, and a send needs a recipient, a state and an
6--- attempt count so a mail that failed can be tried again and seen. Nothing has
7--- ever written a row to either table -- no store method touched them until
8--- this migration -- so they are rebuilt rather than migrated in place.
9-DROP INDEX IF EXISTS mail_send_once;
10-DROP TABLE IF EXISTS mail_send;
11-DROP TABLE IF EXISTS mail_rule;
12-
13-CREATE TABLE mail_rule (
14- id TEXT PRIMARY KEY,
15- board_id TEXT NOT NULL REFERENCES board(id),
16- -- 'status' fires when a card crosses into `trigger_column`; 'unblocked'
17- -- fires for a task whose last blocker just finished.
18- trigger_kind TEXT NOT NULL CHECK (trigger_kind IN ('status', 'unblocked')),
19- trigger_column TEXT REFERENCES board_column(id),
20- subject TEXT NOT NULL,
21- -- 'assignees' — the people the card points at; 'board' — everyone who can
22- -- write on the board. A Viewer is in neither: a Viewer is never mailed.
23- audience TEXT NOT NULL CHECK (audience IN ('assignees', 'board')),
24- enabled INTEGER NOT NULL DEFAULT 1,
25- created_at TEXT NOT NULL,
26- -- A status rule names a column and an unblocked rule does not. The check
27- -- is here so a half-written rule cannot be stored at all.
28- CHECK ((trigger_kind = 'status') = (trigger_column IS NOT NULL))
29-);
30-
31-CREATE INDEX mail_rule_by_board ON mail_rule(board_id);
32-
33--- One row per (rule, event, task, recipient). The row is written BEFORE the
34--- mail is handed to the server, and the unique index below is what decides
35--- whether this process owns the send: an insert that conflicts means somebody
36--- else already owns it, and this process sends nothing. A check-then-insert
37--- would let the engine running twice mail the same person twice.
38---
39--- `event_id` is the transition that caused the send. It is what the engine calls
40--- of "the same happening", so a transition replayed on a restart lands on the
41--- rows that already exist rather than on new ones.
42-CREATE TABLE mail_send (
43- id TEXT PRIMARY KEY,
44- rule_id TEXT NOT NULL REFERENCES mail_rule(id) ON DELETE CASCADE,
45- event_id TEXT NOT NULL REFERENCES transition(id),
46- task_id TEXT NOT NULL REFERENCES task(id),
47- recipient TEXT NOT NULL,
48- -- 'pending' — owned, not yet accepted by the server
49- -- 'sent' — the server took it
50- -- 'failed' — the server refused in a way worth trying again
51- -- 'abandoned' — refused in a way that will not change, or out of attempts
52- state TEXT NOT NULL CHECK (state IN ('pending', 'sent', 'failed', 'abandoned')),
53- attempts INTEGER NOT NULL DEFAULT 0,
54- last_error TEXT,
55- claimed_at TEXT NOT NULL,
56- -- When a failed send may be tried again. NULL once it is sent or given up
57- -- on, so "what is owed" is one indexed read.
58- next_attempt_at TEXT,
59- sent_at TEXT
60-);
61-
62-CREATE UNIQUE INDEX mail_send_once ON mail_send(rule_id, event_id, task_id, recipient);
63-CREATE INDEX mail_send_owed ON mail_send(next_attempt_at);
64-CREATE INDEX mail_send_by_rule ON mail_send(rule_id, sent_at);
crates/izlek-core/migrations/0005_freeing.sqldeleted+0 -56
@@ -1,56 +0,0 @@
1--- A deletion that let other tasks go, recorded as a fact.
2---
3--- The unblocked rule has two causes and only one of them is a crossing: a
4--- blocker can finish, or a blocker can be deleted. The crossing already has a
5--- row in `transition`; the deletion had nowhere to be written, so a mail owed
6--- because of one had no event to hang from and no way to be rebuilt on a
7--- retry. This is that row.
8---
9--- `cause_key` and `cause_title` are copied rather than joined: the task they
10--- name is deleted, and a mail sent an hour later still has to be able to say
11--- which task it was.
12-CREATE TABLE freeing (
13- id TEXT PRIMARY KEY,
14- board_id TEXT NOT NULL REFERENCES board(id),
15- cause_key TEXT NOT NULL,
16- cause_title TEXT NOT NULL,
17- actor_id TEXT NOT NULL REFERENCES user(id),
18- created_at TEXT NOT NULL
19-);
20-
21-CREATE INDEX freeing_by_board ON freeing(board_id, created_at);
22-
23--- `mail_send.event_id` pointed at `transition(id)` alone. A freeing is an event
24--- too, so the column names one of two tables and the foreign key has to go.
25--- SQLite cannot drop a constraint in place, so the table is rebuilt and its
26--- rows are carried over.
27-CREATE TABLE mail_send_next (
28- id TEXT PRIMARY KEY,
29- rule_id TEXT NOT NULL REFERENCES mail_rule(id) ON DELETE CASCADE,
30- -- The transition or the freeing that caused it. Which table it is in is
31- -- answered by looking, and a send is rebuilt from whichever one has it.
32- event_id TEXT NOT NULL,
33- task_id TEXT NOT NULL REFERENCES task(id),
34- recipient TEXT NOT NULL,
35- state TEXT NOT NULL CHECK (state IN ('pending', 'sent', 'failed', 'abandoned')),
36- attempts INTEGER NOT NULL DEFAULT 0,
37- last_error TEXT,
38- claimed_at TEXT NOT NULL,
39- next_attempt_at TEXT,
40- sent_at TEXT
41-);
42-
43-INSERT INTO mail_send_next
44-SELECT id, rule_id, event_id, task_id, recipient, state, attempts, last_error,
45- claimed_at, next_attempt_at, sent_at
46-FROM mail_send;
47-
48-DROP INDEX IF EXISTS mail_send_once;
49-DROP INDEX IF EXISTS mail_send_owed;
50-DROP INDEX IF EXISTS mail_send_by_rule;
51-DROP TABLE mail_send;
52-ALTER TABLE mail_send_next RENAME TO mail_send;
53-
54-CREATE UNIQUE INDEX mail_send_once ON mail_send(rule_id, event_id, task_id, recipient);
55-CREATE INDEX mail_send_owed ON mail_send(next_attempt_at);
56-CREATE INDEX mail_send_by_rule ON mail_send(rule_id, sent_at);
crates/izlek-core/migrations/0006_sender_is_config.sqldeleted+0 -37
@@ -1,37 +0,0 @@
1--- The sender moves out of the database entirely.
2---
3--- `workspace` carried six `smtp_*` columns, one of them the password. A
4--- password in a row is a password an admin session can ask for: any handler
5--- that can read the workspace record is one bug away from returning it, and a
6--- database file that is copied for a backup carries it along. The sender is
7--- infrastructure, not workspace content — it is the same for everyone in the
8--- workspace, it changes when the deployment changes, and it is already read
9--- from `IZLEK_SMTP_HOST`, `IZLEK_SMTP_PORT`, `IZLEK_SMTP_USERNAME`,
10--- `IZLEK_SMTP_PASSWORD` and `IZLEK_MAIL_FROM` at boot.
11---
12--- So the columns go. Settings shows what the process is configured with and
13--- says the password lives in the server's configuration; changing it means
14--- changing the environment variable and restarting.
15---
16--- The limits stay: they are workspace content, an admin edits them, and no
17--- restart should be needed to raise an attachment ceiling.
18---
19--- SQLite cannot drop several columns and their comments in place here, so the
20--- table is rebuilt. Other tables reference `workspace` by name, and the name
21--- is what the rename restores.
22-CREATE TABLE workspace_next (
23- id TEXT PRIMARY KEY,
24- name TEXT NOT NULL,
25- created_at TEXT NOT NULL,
26- attachment_limit_bytes INTEGER NOT NULL DEFAULT 26214400,
27- photo_limit_bytes INTEGER NOT NULL DEFAULT 2097152,
28- -- JSON array of allowed extensions. An empty array means every type.
29- allowed_file_types TEXT NOT NULL DEFAULT '[]'
30-);
31-
32-INSERT INTO workspace_next
33-SELECT id, name, created_at, attachment_limit_bytes, photo_limit_bytes, allowed_file_types
34-FROM workspace;
35-
36-DROP TABLE workspace;
37-ALTER TABLE workspace_next RENAME TO workspace;
crates/izlek-core/migrations/0007_who_invited.sqldeleted+0 -8
@@ -1,8 +0,0 @@
1--- The first-sign-in screen greets the invited person with the name of whoever
2--- made the account. Nothing recorded that, so the screen was reading the
3--- invitee's own name back to them: "Kay Watcher made you an account".
4---
5--- The column is nullable and stays null for the first account, which nobody
6--- invited. It references user(id) rather than copying a name, so a later
7--- rename is reflected rather than frozen at invite time.
8-ALTER TABLE user ADD COLUMN invited_by TEXT REFERENCES user(id);
crates/izlek-core/migrations/0008_sender_is_settings.sqldeleted+0 -31
@@ -1,31 +0,0 @@
1--- The sender comes back into the table, because the admin sets it from the
2--- Settings screen and not from the server's environment.
3---
4--- Migration 0006 moved these columns out on the argument that a password in a
5--- row is a password a handler can be made to return. That argument is sound
6--- and the mitigations survive: the password has no field on `Workspace`, so
7--- no query that loads a workspace can carry it; it is written by
8--- `Store::set_sender` and read by `Store::smtp_password`, which only the
9--- mailer calls; and nothing that reaches a page ever holds it.
10---
11--- What it cost was the artboard's own screen: `SMTP HOST`, `PORT`,
12--- `USERNAME`, `PASSWORD`, `FROM NAME`, `FROM ADDRESS` and a Save button, with
13--- the sender changed by whoever runs the workspace rather than by whoever has
14--- a shell on the box. A three-person team has those be different people, and
15--- the second one is not always awake.
16---
17--- The password is stored as it is typed. It has to be: the server presents it
18--- to the mail host on every send, so a one-way hash would make sending
19--- impossible, and encrypting it under a key that also lives on this disk moves
20--- the problem without shrinking it. The consequence is stated rather than
21--- dressed up — whoever holds a copy of this file holds the sender's password,
22--- so it belongs to a sending account and to nothing else.
23---
24--- Added rather than rebuilt: `ALTER TABLE ... ADD COLUMN` works in place, and
25--- every one of these is nullable, which is what a workspace with no sender is.
26-ALTER TABLE workspace ADD COLUMN smtp_host TEXT;
27-ALTER TABLE workspace ADD COLUMN smtp_port INTEGER;
28-ALTER TABLE workspace ADD COLUMN smtp_username TEXT;
29-ALTER TABLE workspace ADD COLUMN smtp_password TEXT;
30-ALTER TABLE workspace ADD COLUMN smtp_from_name TEXT;
31-ALTER TABLE workspace ADD COLUMN smtp_from_address TEXT;
crates/izlek-core/migrations/0009_sender_test.sqldeleted+0 -14
@@ -1,14 +0,0 @@
1--- The result of the last "send test mail to myself", kept on the workspace.
2---
3--- It is kept rather than shown once because of what the panel is for: an admin
4--- fills the sender in, presses the button, and comes back tomorrow wondering
5--- whether it ever worked. A result that vanished on reload would answer that
6--- question with silence, and silence is what the whole mail ledger exists to
7--- avoid.
8---
9--- `smtp_test_error` is the mail server's own words, kept so the admin can act
10--- on them. Nothing writes the password into it: the mailer builds its errors
11--- from what the server said, never from the credentials it sent.
12-ALTER TABLE workspace ADD COLUMN smtp_test_at INTEGER;
13-ALTER TABLE workspace ADD COLUMN smtp_test_ms INTEGER;
14-ALTER TABLE workspace ADD COLUMN smtp_test_error TEXT;
crates/izlek-core/migrations/0010_attachments_live_in_the_file.sqldeleted+0 -30
@@ -1,30 +0,0 @@
1--- Attachments, moved off the filesystem and into the database file.
2---
3--- The table 0001 wrote kept a `stored_path`, and nothing ever filled it in.
4--- A path is the wrong shape for two reasons. Izlek is one process over one
5--- database file, and a second place to keep state is a second thing to back
6--- up, to lock, and to get out of step with the rows that name it. And a path
7--- is exactly where an uploaded file name must never end up: `../../etc` is a
8--- valid file name and a terrible path. Keeping the bytes here means the name
9--- is only ever a label printed on a chip, never anything the server resolves.
10---
11--- Nothing has ever been written to the old table, so it goes rather than
12--- being migrated.
13-DROP TABLE attachment;
14-
15-CREATE TABLE attachment (
16- id TEXT PRIMARY KEY,
17- task_id TEXT NOT NULL REFERENCES task(id),
18- -- The comment this file was posted with, when it was posted with one.
19- comment_id TEXT REFERENCES comment(id),
20- -- What the browser called it, kept for display only.
21- file_name TEXT NOT NULL,
22- -- What the server decided it is, from the bytes. Never what the upload
23- -- claimed.
24- mime_type TEXT NOT NULL,
25- size_bytes INTEGER NOT NULL,
26- bytes BLOB NOT NULL,
27- uploaded_by TEXT NOT NULL REFERENCES user(id),
28- created_at TEXT NOT NULL
29-);
30-CREATE INDEX attachment_by_task ON attachment(task_id);
crates/izlek-core/migrations/0011_what_the_mail_decided.sqldeleted+0 -42
@@ -1,42 +0,0 @@
1--- What the mail engine decided, for every rule and every event, not just the
2--- mails it sent.
3---
4--- `mail_send` only exists once a mail is owed and claimed; a card that moved
5--- but matched no rule, a rule that was disabled, a task deleted before its
6--- mail could go out — none of that left a trace. This table is that trace:
7--- one row per (rule, event, task), win or not, so "why did nobody get
8--- mailed" has an answer that is not "look at the logs from that day".
9---
10--- `event_id` names a transition or a freeing the same way `mail_send.event_id`
11--- does and for the same reason (0005_freeing.sql:23-26): two tables can cause
12--- a decision, so the column cannot point a foreign key at either one and
13--- still hold both. `task_id` carries no foreign key either, on purpose: a
14--- `task_gone` row exists precisely because the task it names no longer does,
15--- and it has to keep saying so after the row it would have pointed at is
16--- deleted.
17-CREATE TABLE mail_decision (
18- id TEXT PRIMARY KEY,
19- rule_id TEXT NOT NULL REFERENCES mail_rule(id) ON DELETE CASCADE,
20- event_id TEXT NOT NULL,
21- task_id TEXT NOT NULL,
22- -- 'owed' — a send was claimed for this
23- -- 'already_owed' — a send already existed; this is a replay
24- -- 'no_recipients' — the audience resolved to nobody
25- -- 'not_matched' — the event did not fire this rule
26- -- 'disabled' — the rule was off when the event happened
27- -- 'task_gone' — the task named by the event is deleted
28- outcome TEXT NOT NULL CHECK (outcome IN
29- ('owed', 'already_owed', 'no_recipients', 'not_matched', 'disabled', 'task_gone')),
30- detail TEXT NOT NULL DEFAULT '',
31- created_at TEXT NOT NULL
32-);
33-
34--- Same event, same rule, same task decided twice is a bug worth refusing at
35--- the schema rather than finding in a report: a retry has to land on the
36--- decision that is already there, not beside it.
37-CREATE UNIQUE INDEX mail_decision_once ON mail_decision(rule_id, event_id, task_id);
38-CREATE INDEX mail_decision_recent ON mail_decision(created_at);
39-
40--- The activity strip's own index was never added when the table was: reading
41--- the most recent activity has been a full scan since 0001.
42-CREATE INDEX activity_recent ON activity(created_at);
crates/izlek-core/migrations/0012_a_mail_that_owes_no_rule.sqldeleted+0 -50
@@ -1,50 +0,0 @@
1--- An invite is a mail with nobody it is owed to on the board and no event
2--- that caused it — a person is invited before they have a task, a
3--- transition, or a rule to owe them anything. `mail_send` has assumed all
4--- three since 0004_mail.sql; this rebuild lets a row go without them.
5---
6--- `rule_id`/`event_id`/`task_id` become nullable, `rule_id`'s foreign key
7--- kept for the rows that still have one. `kind` says which shape a row is,
8--- and the two CHECKs make the shapes exclusive: a 'rule' send still has to
9--- carry all three of its old columns, an 'invite' send has to carry the
10--- subject and body a rule send gets from `mail_rule`/`compose` instead.
11---
12--- SQLite cannot loosen a column's NOT NULL or add a CHECK in place, so the
13--- table is rebuilt again, same shape of migration as 0005_freeing.sql.
14-CREATE TABLE mail_send_next (
15- id TEXT PRIMARY KEY,
16- rule_id TEXT REFERENCES mail_rule(id) ON DELETE CASCADE,
17- event_id TEXT,
18- task_id TEXT REFERENCES task(id),
19- recipient TEXT NOT NULL,
20- state TEXT NOT NULL CHECK (state IN ('pending', 'sent', 'failed', 'abandoned')),
21- attempts INTEGER NOT NULL DEFAULT 0,
22- last_error TEXT,
23- claimed_at TEXT NOT NULL,
24- next_attempt_at TEXT,
25- sent_at TEXT,
26- kind TEXT NOT NULL DEFAULT 'rule' CHECK (kind IN ('rule', 'invite')),
27- subject TEXT,
28- body TEXT,
29- CHECK ((kind = 'rule') = (rule_id IS NOT NULL AND event_id IS NOT NULL AND task_id IS NOT NULL)),
30- CHECK ((kind = 'invite') = (subject IS NOT NULL AND body IS NOT NULL))
31-);
32-
33-INSERT INTO mail_send_next
34-SELECT id, rule_id, event_id, task_id, recipient, state, attempts, last_error,
35- claimed_at, next_attempt_at, sent_at, 'rule', NULL, NULL
36-FROM mail_send;
37-
38-DROP INDEX IF EXISTS mail_send_once;
39-DROP INDEX IF EXISTS mail_send_owed;
40-DROP INDEX IF EXISTS mail_send_by_rule;
41-DROP TABLE mail_send;
42-ALTER TABLE mail_send_next RENAME TO mail_send;
43-
44--- NULLs are distinct in a SQLite unique index, so two invite rows (whose
45--- rule_id/event_id/task_id are all NULL) never collide here — each invite
46--- send is its own row, which is intended: a resend is a new mail, not a
47--- replay of the same one.
48-CREATE UNIQUE INDEX mail_send_once ON mail_send(rule_id, event_id, task_id, recipient);
49-CREATE INDEX mail_send_owed ON mail_send(next_attempt_at);
50-CREATE INDEX mail_send_by_rule ON mail_send(rule_id, sent_at);
crates/izlek-core/migrations/0013_more_than_a_move.sqldeleted+0 -48
@@ -1,48 +0,0 @@
1--- The rule table named its two triggers in a CHECK: 'status' or 'unblocked',
2--- nothing else. Every new trigger has meant a migration just to widen that
3--- list. This rebuild drops the CHECK on `trigger_kind` entirely — a future
4--- trigger is a value, not a schema change — and widens `audience` to add
5--- 'creator' the same way 0004_mail.sql wrote it in the first place.
6---
7--- SQLite cannot drop or relax a CHECK in place, so the table is rebuilt,
8--- same shape of migration as 0005_freeing.sql and 0012.
9---
10--- `mail_send.rule_id` and `mail_decision.rule_id` both point at `mail_rule`
11--- with ON DELETE CASCADE, and every connection this store opens runs with
12--- foreign keys on. SQLite performs an implicit DELETE FROM before a DROP
13--- TABLE takes effect, and that implicit delete walks ON DELETE CASCADE like
14--- any other — dropping `mail_rule` with rows in it would carry every send and
15--- every decision away with it. `PRAGMA foreign_keys` is documented as a
16--- no-op inside a transaction, which is where every migration in this file
17--- runs, so the pragma is set here anyway and then proven by the reopen test
18--- rather than trusted from the manual.
19-PRAGMA foreign_keys = OFF;
20-
21-CREATE TABLE mail_rule_next (
22- id TEXT PRIMARY KEY,
23- board_id TEXT NOT NULL REFERENCES board(id),
24- -- No CHECK list: the set of triggers grows without a schema change now.
25- trigger_kind TEXT NOT NULL,
26- trigger_column TEXT REFERENCES board_column(id),
27- subject TEXT NOT NULL,
28- -- 'assignees' — the people the card points at; 'board' — everyone who can
29- -- write on the board; 'creator' — whoever opened the card.
30- audience TEXT NOT NULL CHECK (audience IN ('assignees', 'board', 'creator')),
31- enabled INTEGER NOT NULL DEFAULT 1,
32- created_at TEXT NOT NULL,
33- -- A status rule names a column and an unblocked rule does not. The check
34- -- is here so a half-written rule cannot be stored at all.
35- CHECK ((trigger_kind = 'status') = (trigger_column IS NOT NULL))
36-);
37-
38-INSERT INTO mail_rule_next
39-SELECT id, board_id, trigger_kind, trigger_column, subject, audience, enabled, created_at
40-FROM mail_rule;
41-
42-DROP INDEX IF EXISTS mail_rule_by_board;
43-DROP TABLE mail_rule;
44-ALTER TABLE mail_rule_next RENAME TO mail_rule;
45-
46-CREATE INDEX mail_rule_by_board ON mail_rule(board_id);
47-
48-PRAGMA foreign_keys = ON;
crates/izlek-core/migrations/0014_created_into_a_column_is_a_transition.sqldeleted+0 -32
@@ -1,32 +0,0 @@
1--- A task created directly into a column never wrote a transition, so a rule
2--- watching that column ("When status becomes In Progress") never fired for
3--- it — only a later move into the column did. `create_task` now writes a
4--- transition in the same statement as the insert, with `from_column` set to
5--- '' (empty string) meaning "created into", never a real column.
6---
7--- `from_column` carried `REFERENCES board_column(id)`, and no column's id is
8--- ever ''. SQLite cannot drop a column's foreign key in place, so the table
9--- is rebuilt, same shape as 0005_freeing.sql and 0013.
10-PRAGMA foreign_keys = OFF;
11-
12-CREATE TABLE transition_next (
13- id TEXT PRIMARY KEY,
14- task_id TEXT NOT NULL REFERENCES task(id),
15- -- No REFERENCES: '' means "created into", and is never a column id.
16- from_column TEXT NOT NULL,
17- to_column TEXT NOT NULL REFERENCES board_column(id),
18- actor_id TEXT NOT NULL REFERENCES user(id),
19- created_at TEXT NOT NULL
20-);
21-
22-INSERT INTO transition_next
23-SELECT id, task_id, from_column, to_column, actor_id, created_at
24-FROM transition;
25-
26-DROP INDEX IF EXISTS transition_by_task;
27-DROP TABLE transition;
28-ALTER TABLE transition_next RENAME TO transition;
29-
30-CREATE INDEX transition_by_task ON transition(task_id, created_at);
31-
32-PRAGMA foreign_keys = ON;
crates/izlek-core/migrations/0015_task_details_in_the_mail.sqldeleted+0 -5
@@ -1,5 +0,0 @@
1--- A rule can opt into folding the task's own facts into the mail body,
2--- instead of the rule's subject line being the only thing the recipient
3--- reads. Off by default, so every existing rule keeps sending exactly what
4--- it always sent.
5-ALTER TABLE mail_rule ADD COLUMN include_task_details INTEGER NOT NULL DEFAULT 0;
crates/izlek-core/migrations/0016_display_preferences.sqldeleted+0 -6
@@ -1,6 +0,0 @@
1--- Per-user display preferences. Stored data everywhere else stays UTC and
2--- language-neutral; these three columns only ever change how a browser
3--- renders that data for the one person signed in as this user.
4-ALTER TABLE user ADD COLUMN timezone TEXT NOT NULL DEFAULT 'UTC';
5-ALTER TABLE user ADD COLUMN theme TEXT NOT NULL DEFAULT 'light';
6-ALTER TABLE user ADD COLUMN language TEXT NOT NULL DEFAULT 'en';
crates/izlek-core/migrations/0017_ui_preference.sqldeleted+0 -3
@@ -1,3 +0,0 @@
1--- Which interface this person uses. Display-only, as the preferences before
2--- it: no stored data depends on it.
3-ALTER TABLE user ADD COLUMN ui TEXT NOT NULL DEFAULT 'instrument';
crates/izlek-core/migrations/0018_photo_in_the_user.sqldeleted+0 -5
@@ -1,5 +0,0 @@
1--- A profile picture lives in the database as bytes, the way an attachment
2--- lives in its file (0010): no filesystem path survives a backup or a move.
3--- `photo_path` (0001) never carried a value and is left behind, dead.
4-ALTER TABLE user ADD COLUMN photo BLOB;
5-ALTER TABLE user ADD COLUMN photo_mime TEXT;
crates/izlek-core/migrations/0019_events_without_a_task.sqldeleted+0 -23
@@ -1,23 +0,0 @@
1--- Account and admin events — sign-ins, invites, role changes — have no task
2--- to sit under, and `activity.task_id` being NOT NULL left them unloggable.
3--- The table is rebuilt with the task column nullable.
4-CREATE TABLE activity_next (
5- id TEXT PRIMARY KEY,
6- task_id TEXT REFERENCES task(id),
7- actor_id TEXT REFERENCES user(id),
8- kind TEXT NOT NULL,
9- detail TEXT NOT NULL DEFAULT '',
10- created_at TEXT NOT NULL
11-);
12-
13-INSERT INTO activity_next
14-SELECT id, task_id, actor_id, kind, detail, created_at
15-FROM activity;
16-
17-DROP INDEX IF EXISTS activity_by_task;
18-DROP INDEX IF EXISTS activity_recent;
19-DROP TABLE activity;
20-ALTER TABLE activity_next RENAME TO activity;
21-
22-CREATE INDEX activity_by_task ON activity(task_id);
23-CREATE INDEX activity_recent ON activity(created_at);
crates/izlek-core/migrations/0020_a_notice_owes_no_rule_either.sqldeleted+0 -38
@@ -1,38 +0,0 @@
1--- A notice is an admin's own mail to a member — same shape as an invite:
2--- no rule, no event, no task, just a subject and a body. 0012's CHECK only
3--- named 'invite' alongside 'rule', so a 'notice' row would fail it. SQLite
4--- cannot widen a CHECK in place, so the table is rebuilt again, same shape
5--- of migration as 0012/0013.
6-CREATE TABLE mail_send_next (
7- id TEXT PRIMARY KEY,
8- rule_id TEXT REFERENCES mail_rule(id) ON DELETE CASCADE,
9- event_id TEXT,
10- task_id TEXT REFERENCES task(id),
11- recipient TEXT NOT NULL,
12- state TEXT NOT NULL CHECK (state IN ('pending', 'sent', 'failed', 'abandoned')),
13- attempts INTEGER NOT NULL DEFAULT 0,
14- last_error TEXT,
15- claimed_at TEXT NOT NULL,
16- next_attempt_at TEXT,
17- sent_at TEXT,
18- kind TEXT NOT NULL DEFAULT 'rule' CHECK (kind IN ('rule', 'invite', 'notice')),
19- subject TEXT,
20- body TEXT,
21- CHECK ((kind = 'rule') = (rule_id IS NOT NULL AND event_id IS NOT NULL AND task_id IS NOT NULL)),
22- CHECK ((kind IN ('invite', 'notice')) = (subject IS NOT NULL AND body IS NOT NULL))
23-);
24-
25-INSERT INTO mail_send_next
26-SELECT id, rule_id, event_id, task_id, recipient, state, attempts, last_error,
27- claimed_at, next_attempt_at, sent_at, kind, subject, body
28-FROM mail_send;
29-
30-DROP INDEX IF EXISTS mail_send_once;
31-DROP INDEX IF EXISTS mail_send_owed;
32-DROP INDEX IF EXISTS mail_send_by_rule;
33-DROP TABLE mail_send;
34-ALTER TABLE mail_send_next RENAME TO mail_send;
35-
36-CREATE UNIQUE INDEX mail_send_once ON mail_send(rule_id, event_id, task_id, recipient);
37-CREATE INDEX mail_send_owed ON mail_send(next_attempt_at);
38-CREATE INDEX mail_send_by_rule ON mail_send(rule_id, sent_at);
crates/izlek-core/src/store/mod.rsmodified+25 -0
@@ -33,6 +33,13 @@ pub enum StoreError {
33 /// The dependency asked for would put a task behind itself.33 /// The dependency asked for would put a task behind itself.
34 #[error("that link would make a circle")]34 #[error("that link would make a circle")]
35 Cycle,35 Cycle,
36+ /// Subtasks are one level deep. Either the would-be parent is itself a
37+ /// subtask, or the task being parented already has subtasks of its own.
38+ #[error("subtasks go one level deep")]
39+ NotNestable,
40+ /// A parent and its subtask live on the same board.
41+ #[error("that task is on another board")]
42+ OtherBoard,
36 }43 }
37 44
38 pub type Result<T> = std::result::Result<T, StoreError>;45 pub type Result<T> = std::result::Result<T, StoreError>;
@@ -209,6 +216,9 @@ impl Session {
209 pub struct NewTask<'a> {216 pub struct NewTask<'a> {
210 pub board_id: &'a str,217 pub board_id: &'a str,
211 pub column_id: &'a str,218 pub column_id: &'a str,
219+ /// The task this one is a subtask of, if any. It must be on the same
220+ /// board and must not itself be a subtask.
221+ pub parent_id: Option<&'a str>,
212 pub title: &'a str,222 pub title: &'a str,
213 pub description: &'a str,223 pub description: &'a str,
214 pub deadline: Option<time::Date>,224 pub deadline: Option<time::Date>,
@@ -740,6 +750,21 @@ pub trait Store: BoardReads + DetailReads + 'static {
740 async fn create_task(&self, new: NewTask<'_>) -> Result<TaskCreated>;750 async fn create_task(&self, new: NewTask<'_>) -> Result<TaskCreated>;
741 751
742 /// Idempotent: assigning someone twice is not an error.752 /// Idempotent: assigning someone twice is not an error.
753+ /// Makes `task_id` a subtask of `parent_id`, or `None` to promote it back
754+ /// to a task of its own. Both directions are one write: that is the whole
755+ /// reason a subtask is a task with a parent rather than a row in a table
756+ /// of its own.
757+ ///
758+ /// Refuses with [`StoreError::NotNestable`] when the move would make two
759+ /// levels — the parent is already somebody's subtask, or the task being
760+ /// parented has subtasks of its own — and with [`StoreError::OtherBoard`]
761+ /// when the two are not on the same board.
762+ async fn set_parent(&self, task_id: &str, parent_id: Option<&str>) -> Result<()>;
763+
764+ /// The live subtasks of `parent_id`, oldest first. Empty for a task that
765+ /// has none, and for a subtask, which cannot have any.
766+ async fn subtasks(&self, parent_id: &str) -> Result<Vec<TaskRow>>;
767+
743 async fn assign_task(&self, task_id: &str, user_id: &str) -> Result<()>;768 async fn assign_task(&self, task_id: &str, user_id: &str) -> Result<()>;
744 769
745 async fn unassign_task(&self, task_id: &str, user_id: &str) -> Result<()>;770 async fn unassign_task(&self, task_id: &str, user_id: &str) -> Result<()>;
crates/izlek-core/src/store/turso_store.rsmodified+148 -52
@@ -33,49 +33,6 @@ use time::macros::format_description;
33 /// Every migration, in order. Adding one means appending a file and a line.33 /// Every migration, in order. Adding one means appending a file and a line.
34 const MIGRATIONS: &[(i64, &str)] = &[34 const MIGRATIONS: &[(i64, &str)] = &[
35 (1, include_str!("../../migrations/0001_init.sql")),35 (1, include_str!("../../migrations/0001_init.sql")),
36- (2, include_str!("../../migrations/0002_auth.sql")),
37- (3, include_str!("../../migrations/0003_transition.sql")),
38- (4, include_str!("../../migrations/0004_mail.sql")),
39- (5, include_str!("../../migrations/0005_freeing.sql")),
40- (6, include_str!("../../migrations/0006_sender_is_config.sql")),
41- (7, include_str!("../../migrations/0007_who_invited.sql")),
42- (8, include_str!("../../migrations/0008_sender_is_settings.sql")),
43- (9, include_str!("../../migrations/0009_sender_test.sql")),
44- (
45- 10,
46- include_str!("../../migrations/0010_attachments_live_in_the_file.sql"),
47- ),
48- (
49- 11,
50- include_str!("../../migrations/0011_what_the_mail_decided.sql"),
51- ),
52- (
53- 12,
54- include_str!("../../migrations/0012_a_mail_that_owes_no_rule.sql"),
55- ),
56- (
57- 13,
58- include_str!("../../migrations/0013_more_than_a_move.sql"),
59- ),
60- (
61- 14,
62- include_str!("../../migrations/0014_created_into_a_column_is_a_transition.sql"),
63- ),
64- (
65- 15,
66- include_str!("../../migrations/0015_task_details_in_the_mail.sql"),
67- ),
68- (
69- 16,
70- include_str!("../../migrations/0016_display_preferences.sql"),
71- ),
72- (17, include_str!("../../migrations/0017_ui_preference.sql")),
73- (18, include_str!("../../migrations/0018_photo_in_the_user.sql")),
74- (19, include_str!("../../migrations/0019_events_without_a_task.sql")),
75- (
76- 20,
77- include_str!("../../migrations/0020_a_notice_owes_no_rule_either.sql"),
78- ),
79 ];36 ];
80 37
81 /// The board a fresh workspace gets, and its columns. `Done` is the column38 /// The board a fresh workspace gets, and its columns. `Done` is the column
@@ -1375,11 +1332,35 @@ impl Store for TursoStore {
1375 )1332 )
1376 .await?;1333 .await?;
1377 let Some(row) = rows.next().await? else {1334 let Some(row) = rows.next().await? else {
1378- return Ok(None);1335+ return Ok(Err(StoreError::NotFound));
1379 };1336 };
1380 let prefix = row.get::<String>(0)?;1337 let prefix = row.get::<String>(0)?;
1381 drop(rows);1338 drop(rows);
1382 1339
1340+ // A subtask is checked before anything is written: the parent has
1341+ // to exist, sit on this board, and not be a subtask itself.
1342+ if let Some(parent) = new.parent_id {
1343+ let mut rows = tx
1344+ .query(
1345+ "SELECT board_id, parent_id FROM task \
1346+ WHERE id = ?1 AND deleted_at IS NULL",
1347+ params![parent],
1348+ )
1349+ .await?;
1350+ let Some(row) = rows.next().await? else {
1351+ return Ok(Err(StoreError::NotFound));
1352+ };
1353+ let parent_board = row.get::<String>(0)?;
1354+ let grandparent = row.get::<Option<String>>(1)?;
1355+ drop(rows);
1356+ if parent_board != new.board_id {
1357+ return Ok(Err(StoreError::OtherBoard));
1358+ }
1359+ if grandparent.is_some() {
1360+ return Ok(Err(StoreError::NotNestable));
1361+ }
1362+ }
1363+
1383 // New cards land at the end of their column.1364 // New cards land at the end of their column.
1384 let mut rows = tx1365 let mut rows = tx
1385 .query(1366 .query(
@@ -1405,9 +1386,9 @@ impl Store for TursoStore {
1405 let candidate = format!("{prefix}-{}", &id[id.len() - tail_len..]);1386 let candidate = format!("{prefix}-{}", &id[id.len() - tail_len..]);
1406 match tx1387 match tx
1407 .execute(1388 .execute(
1408- "INSERT INTO task (id, board_id, task_key, title, description, column_id, \1389+ "INSERT INTO task (id, board_id, parent_id, task_key, title, description, \
1409- deadline, position, created_by, created_at, updated_at) \1390+ column_id, deadline, position, created_by, created_at, updated_at) \
1410- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?10)",1391+ VALUES (?1, ?2, ?11, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?10)",
1411 params![1392 params![
1412 id.clone(),1393 id.clone(),
1413 new.board_id,1394 new.board_id,
@@ -1418,7 +1399,8 @@ impl Store for TursoStore {
1418 deadline.clone(),1399 deadline.clone(),
1419 position,1400 position,
1420 new.created_by,1401 new.created_by,
1421- now.clone()1402+ now.clone(),
1403+ new.parent_id
1422 ],1404 ],
1423 )1405 )
1424 .await1406 .await
@@ -1456,15 +1438,15 @@ impl Store for TursoStore {
1456 ],1438 ],
1457 )1439 )
1458 .await?;1440 .await?;
1459- Ok::<_, turso::Error>(Some((task_key, position)))1441+ Ok::<_, turso::Error>(Ok((task_key, position)))
1460 }1442 }
1461 .await;1443 .await;
1462 1444
1463 let written = match written {1445 let written = match written {
1464- Ok(Some(written)) => written,1446+ Ok(Ok(written)) => written,
1465- Ok(None) => {1447+ Ok(Err(refused)) => {
1466 let _ = tx.rollback().await;1448 let _ = tx.rollback().await;
1467- return Err(StoreError::NotFound);1449+ return Err(refused);
1468 }1450 }
1469 Err(e) => {1451 Err(e) => {
1470 let _ = tx.rollback().await;1452 let _ = tx.rollback().await;
@@ -1496,6 +1478,120 @@ impl Store for TursoStore {
1496 })1478 })
1497 }1479 }
1498 1480
1481+ async fn set_parent(&self, task_id: &str, parent_id: Option<&str>) -> Result<()> {
1482+ let mut conn = self.tx_conn().await?;
1483+ // IMMEDIATE: the one-level rule is read-then-write. Two concurrent
1484+ // parentings each read a NULL parent, each pass, and the pair leaves a
1485+ // grandchild neither of them could see.
1486+ let tx = conn
1487+ .transaction_with_behavior(TransactionBehavior::Immediate)
1488+ .await
1489+ .map_err(backend)?;
1490+
1491+ let outcome = async {
1492+ let mut rows = tx
1493+ .query(
1494+ "SELECT board_id FROM task WHERE id = ?1 AND deleted_at IS NULL",
1495+ params![task_id],
1496+ )
1497+ .await?;
1498+ let Some(row) = rows.next().await? else {
1499+ return Ok(Err(StoreError::NotFound));
1500+ };
1501+ let board_id = row.get::<String>(0)?;
1502+ drop(rows);
1503+
1504+ if let Some(parent) = parent_id {
1505+ if parent == task_id {
1506+ return Ok(Err(StoreError::Cycle));
1507+ }
1508+ let mut rows = tx
1509+ .query(
1510+ "SELECT board_id, parent_id FROM task \
1511+ WHERE id = ?1 AND deleted_at IS NULL",
1512+ params![parent],
1513+ )
1514+ .await?;
1515+ let Some(row) = rows.next().await? else {
1516+ return Ok(Err(StoreError::NotFound));
1517+ };
1518+ let parent_board = row.get::<String>(0)?;
1519+ let grandparent = row.get::<Option<String>>(1)?;
1520+ drop(rows);
1521+ if parent_board != board_id {
1522+ return Ok(Err(StoreError::OtherBoard));
1523+ }
1524+ if grandparent.is_some() {
1525+ return Ok(Err(StoreError::NotNestable));
1526+ }
1527+
1528+ // The other half of the same rule: a task that already has
1529+ // subtasks cannot become one, or its own children become
1530+ // grandchildren without ever being touched.
1531+ let mut rows = tx
1532+ .query(
1533+ "SELECT 1 FROM task WHERE parent_id = ?1 AND deleted_at IS NULL LIMIT 1",
1534+ params![task_id],
1535+ )
1536+ .await?;
1537+ let has_children = rows.next().await?.is_some();
1538+ drop(rows);
1539+ if has_children {
1540+ return Ok(Err(StoreError::NotNestable));
1541+ }
1542+ }
1543+
1544+ tx.execute(
1545+ "UPDATE task SET parent_id = ?2 WHERE id = ?1",
1546+ params![task_id, parent_id],
1547+ )
1548+ .await?;
1549+ Ok::<_, turso::Error>(Ok(()))
1550+ }
1551+ .await;
1552+
1553+ match outcome {
1554+ Ok(Ok(())) => {
1555+ tx.commit().await.map_err(backend)?;
1556+ Ok(())
1557+ }
1558+ Ok(Err(refused)) => {
1559+ let _ = tx.rollback().await;
1560+ Err(refused)
1561+ }
1562+ Err(e) => {
1563+ let _ = tx.rollback().await;
1564+ Err(backend(e))
1565+ }
1566+ }
1567+ }
1568+
1569+ async fn subtasks(&self, parent_id: &str) -> Result<Vec<TaskRow>> {
1570+ let conn = self.conn.lock().await;
1571+ let mut rows = conn
1572+ .query(
1573+ "SELECT id, task_key, title, column_id, deadline, position, done_at \
1574+ FROM task WHERE parent_id = ?1 AND deleted_at IS NULL \
1575+ ORDER BY created_at",
1576+ params![parent_id],
1577+ )
1578+ .await
1579+ .map_err(backend)?;
1580+ let mut out = Vec::new();
1581+ while let Some(row) = rows.next().await.map_err(backend)? {
1582+ out.push(TaskRow {
1583+ id: text(&row, 0)?,
1584+ task_key: text(&row, 1)?,
1585+ title: text(&row, 2)?,
1586+ column_id: text(&row, 3)?,
1587+ deadline: opt_day(&row, 4)?,
1588+ position: row.get::<f64>(5).unwrap_or(0.0),
1589+ done_at: opt_stamp(&row, 6)?,
1590+ });
1591+ }
1592+ Ok(out)
1593+ }
1594+
1499 async fn assign_task(&self, task_id: &str, user_id: &str) -> Result<()> {1595 async fn assign_task(&self, task_id: &str, user_id: &str) -> Result<()> {
1500 let conn = self.conn.lock().await;1596 let conn = self.conn.lock().await;
1501 conn1597 conn
crates/izlek-core/tests/store.rsmodified+148 -162
@@ -94,141 +94,6 @@ async fn member(store: &TursoStore, workspace_id: &str, email: &str, name: &str)
94 .id94 .id
95 }95 }
96 96
97-/// Builds a database file shaped like schema version 12 — every migration
98-/// through 0012 applied, nothing after — by replaying the migration files
99-/// straight off disk on a raw connection, the same way [`TursoStore::apply`]
100-/// does it one at a time. Used only to put a rule, a send and a decision in
101-/// place before 0013 exists, so 0013 runs against real rows rather than an
102-/// empty table.
103-async fn a_pre_0013_store_with_a_rule_send_and_decision()
104--> (PathBuf, String, String, String, String) {
105- let dir = std::env::temp_dir().join(format!("izlek-test-{}", Ulid::new()));
106- std::fs::create_dir_all(&dir).unwrap();
107- let path = dir.join("izlek.db").to_string_lossy().into_owned();
108-
109- let db = turso::Builder::new_local(&path).build().await.unwrap();
110- let conn = db.connect().unwrap();
111- conn.execute("PRAGMA foreign_keys = ON", ()).await.unwrap();
112- conn.execute(
113- "CREATE TABLE schema_version (version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL)",
114- (),
115- )
116- .await
117- .unwrap();
118-
119- let migrations_dir =
120- PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("migrations");
121- let mut files: Vec<_> = std::fs::read_dir(&migrations_dir)
122- .unwrap()
123- .map(|e| e.unwrap().path())
124- .filter(|p| {
125- p.file_name()
126- .and_then(|n| n.to_str())
127- .map(|n| n < "0013")
128- .unwrap_or(false)
129- })
130- .collect();
131- files.sort();
132- for (i, file) in files.iter().enumerate() {
133- let sql = std::fs::read_to_string(file).unwrap();
134- conn.execute_batch(&sql).await.unwrap();
135- conn.execute(
136- "INSERT INTO schema_version (version, applied_at) VALUES (?1, '2026-08-26T00:00:00Z')",
137- turso::params![(i + 1) as i64],
138- )
139- .await
140- .unwrap();
141- }
142-
143- let workspace = Ulid::new().to_string();
144- let admin = Ulid::new().to_string();
145- let board = Ulid::new().to_string();
146- let backlog = Ulid::new().to_string();
147- let done = Ulid::new().to_string();
148- let task = Ulid::new().to_string();
149- let rule = Ulid::new().to_string();
150- let transition = Ulid::new().to_string();
151- conn.execute(
152- "INSERT INTO workspace (id, name, created_at) VALUES (?1, 'Izlek', '2026-08-26T00:00:00Z')",
153- turso::params![workspace.clone()],
154- )
155- .await
156- .unwrap();
157- conn.execute(
158- "INSERT INTO user (id, workspace_id, email, display_name, role, password_hash, \
159- created_at) VALUES (?1, ?2, 'ada@izlek.sh', 'Ada', 'admin', 'x', '2026-08-26T00:00:00Z')",
160- turso::params![admin.clone(), workspace.clone()],
161- )
162- .await
163- .unwrap();
164- conn.execute(
165- "INSERT INTO board (id, workspace_id, name, created_at) VALUES (?1, ?2, 'Board', \
166- '2026-08-26T00:00:00Z')",
167- turso::params![board.clone(), workspace.clone()],
168- )
169- .await
170- .unwrap();
171- conn.execute(
172- "INSERT INTO board_column (id, board_id, name, position, is_done) VALUES (?1, ?2, \
173- 'Backlog', 0, 0)",
174- turso::params![backlog.clone(), board.clone()],
175- )
176- .await
177- .unwrap();
178- conn.execute(
179- "INSERT INTO board_column (id, board_id, name, position, is_done) VALUES (?1, ?2, \
180- 'Done', 1, 1)",
181- turso::params![done.clone(), board.clone()],
182- )
183- .await
184- .unwrap();
185- conn.execute(
186- "INSERT INTO task (id, board_id, task_key, title, column_id, created_by, created_at, \
187- updated_at) VALUES (?1, ?2, 'DZ-1', 'Ship it', ?3, ?4, '2026-08-26T00:00:00Z', '2026-08-26T00:00:00Z')",
188- turso::params![task.clone(), board.clone(), done.clone(), admin.clone()],
189- )
190- .await
191- .unwrap();
192- conn.execute(
193- "INSERT INTO transition (id, task_id, from_column, to_column, actor_id, created_at) \
194- VALUES (?1, ?2, ?3, ?4, ?5, '2026-08-26T00:00:00Z')",
195- turso::params![
196- transition.clone(),
197- task.clone(),
198- backlog.clone(),
199- done.clone(),
200- admin.clone()
201- ],
202- )
203- .await
204- .unwrap();
205- conn.execute(
206- "INSERT INTO mail_rule (id, board_id, trigger_kind, trigger_column, subject, audience, \
207- enabled, created_at) VALUES (?1, ?2, 'status', ?3, 'Task completed', 'assignees', 1, \
208- '2026-08-26T00:00:00Z')",
209- turso::params![rule.clone(), board.clone(), done.clone()],
210- )
211- .await
212- .unwrap();
213- conn.execute(
214- "INSERT INTO mail_send (id, rule_id, event_id, task_id, recipient, state, attempts, \
215- claimed_at) VALUES ('s1', ?1, ?2, ?3, 'ada@izlek.sh', 'pending', 0, '2026-08-26T00:00:00Z')",
216- turso::params![rule.clone(), transition.clone(), task.clone()],
217- )
218- .await
219- .unwrap();
220- conn.execute(
221- "INSERT INTO mail_decision (id, rule_id, event_id, task_id, outcome, detail, \
222- created_at) VALUES ('d1', ?1, ?2, ?3, 'owed', '', '2026-08-26T00:00:00Z')",
223- turso::params![rule.clone(), transition.clone(), task.clone()],
224- )
225- .await
226- .unwrap();
227- drop(conn);
228-
229- (PathBuf::from(path), workspace, board, rule, task)
230-}
231-
232 #[tokio::test]97 #[tokio::test]
233 async fn migrations_apply_once_and_survive_reopen() {98 async fn migrations_apply_once_and_survive_reopen() {
234 let dir = std::env::temp_dir().join(format!("izlek-test-{}", Ulid::new()));99 let dir = std::env::temp_dir().join(format!("izlek-test-{}", Ulid::new()));
@@ -236,52 +101,170 @@ async fn migrations_apply_once_and_survive_reopen() {
236 let path = dir.join("izlek.db").to_string_lossy().into_owned();101 let path = dir.join("izlek.db").to_string_lossy().into_owned();
237 102
238 let first = TursoStore::open(&path).await.unwrap();103 let first = TursoStore::open(&path).await.unwrap();
239- assert_eq!(first.schema_version().await.unwrap(), 20);104+ assert_eq!(first.schema_version().await.unwrap(), 1);
240 claim(&first).await;105 claim(&first).await;
241 drop(first);106 drop(first);
242 107
243 // Re-opening must not re-run 0001 (which would fail on CREATE TABLE) and108 // Re-opening must not re-run 0001 (which would fail on CREATE TABLE) and
244 // must not lose what the first open wrote.109 // must not lose what the first open wrote.
245 let second = TursoStore::open(&path).await.unwrap();110 let second = TursoStore::open(&path).await.unwrap();
246- assert_eq!(second.schema_version().await.unwrap(), 20);111+ assert_eq!(second.schema_version().await.unwrap(), 1);
247 assert_eq!(second.workspace().await.unwrap().unwrap().name, "Izlek");112 assert_eq!(second.workspace().await.unwrap().unwrap().name, "Izlek");
248 drop(second);113 drop(second);
249 let _ = std::fs::remove_dir_all(&dir);114 let _ = std::fs::remove_dir_all(&dir);
250 }115 }
251 116
252 #[tokio::test]117 #[tokio::test]
253-async fn migration_0013_rebuilds_mail_rule_without_losing_its_ledger() {118+async fn a_subtask_is_a_task_with_a_parent() {
254- // `mail_send.rule_id` and `mail_decision.rule_id` both carry ON DELETE119+ let scratch = Scratch::open().await;
255- // CASCADE at `mail_rule`, and every connection this store opens runs with120+ let (workspace, admin) = claim(&scratch.store).await;
256- // foreign keys on. Rebuilding `mail_rule` — dropping the old table while121+ let parent = add_task(
257- // rows still point at it — would, without a guard, cascade the drop122+ &scratch.store,
258- // straight through this rule's own send and its own decision.123+ &workspace,
259- let (path, workspace, board, rule, task) =124+ "Backlog",
260- a_pre_0013_store_with_a_rule_send_and_decision().await;125+ "Ship the exporter",
126+ None,
127+ &admin,
128+ )
129+ .await;
261 130
262- let store = TursoStore::open(path.to_str().unwrap()).await.unwrap();131+ let board = scratch.store.board(&workspace).await.unwrap().unwrap();
263- assert_eq!(store.schema_version().await.unwrap(), 20);132+ let column_id = column_named(&scratch.store, &workspace, "Backlog").await;
264- assert_eq!(store.board(&workspace).await.unwrap().unwrap().id, board);133+ let child = scratch
134+ .store
135+ .create_task(NewTask {
136+ board_id: &board.id,
137+ column_id: &column_id,
138+ parent_id: Some(&parent),
139+ title: "Write the CSV writer",
140+ description: "",
141+ deadline: None,
142+ created_by: &admin,
143+ })
144+ .await
145+ .unwrap()
146+ .row;
265 147
266- let rules = store.mail_rules(&board).await.unwrap();148+ // It gets a key of its own from the same prefix, not a derived DZ-14.1.
267- assert_eq!(rules.len(), 1, "the rule survived the rebuild");149+ assert!(child.task_key.starts_with("DZ-"));
268- assert_eq!(rules[0].id, rule);150+ assert_ne!(child.task_key, parent);
269- assert_eq!(rules[0].audience, Audience::Assignees);
270 151
271- let sends = store.sends_for_rule(&rule, 10).await.unwrap();152+ let children = scratch.store.subtasks(&parent).await.unwrap();
272- assert_eq!(sends.len(), 1, "the send survived, joined to its rule");153+ assert_eq!(children.len(), 1);
273- assert_eq!(sends[0].task_id, Some(task.clone()));154+ assert_eq!(children[0].id, child.id);
155+ assert!(
156+ scratch.store.subtasks(&child.id).await.unwrap().is_empty(),
157+ "a subtask has none of its own"
158+ );
159+}
274 160
275- let decisions = store.recent_mail_decisions(10, izlek_core::store::FeedPage::Newest).await.unwrap();161+#[tokio::test]
162+async fn subtasks_go_one_level_deep() {
163+ let scratch = Scratch::open().await;
164+ let (workspace, admin) = claim(&scratch.store).await;
165+ let board = scratch.store.board(&workspace).await.unwrap().unwrap();
166+ let column_id = column_named(&scratch.store, &workspace, "Backlog").await;
167+
168+ let parent = add_task(&scratch.store, &workspace, "Backlog", "Parent", None, &admin).await;
169+ let child = scratch
170+ .store
171+ .create_task(NewTask {
172+ board_id: &board.id,
173+ column_id: &column_id,
174+ parent_id: Some(&parent),
175+ title: "Child",
176+ description: "",
177+ deadline: None,
178+ created_by: &admin,
179+ })
180+ .await
181+ .unwrap()
182+ .row
183+ .id;
184+
185+ // Creating under a subtask is refused outright.
186+ let grandchild = scratch
187+ .store
188+ .create_task(NewTask {
189+ board_id: &board.id,
190+ column_id: &column_id,
191+ parent_id: Some(&child),
192+ title: "Grandchild",
193+ description: "",
194+ deadline: None,
195+ created_by: &admin,
196+ })
197+ .await;
198+ assert!(matches!(grandchild, Err(StoreError::NotNestable)));
199+
200+ // And so is reaching the same shape from the other side: an existing task
201+ // cannot be filed under a subtask ...
202+ let loose = add_task(&scratch.store, &workspace, "Backlog", "Loose", None, &admin).await;
203+ assert!(matches!(
204+ scratch.store.set_parent(&loose, Some(&child)).await,
205+ Err(StoreError::NotNestable)
206+ ));
207+
208+ // ... nor can a task that already has children become one itself.
209+ assert!(matches!(
210+ scratch.store.set_parent(&parent, Some(&loose)).await,
211+ Err(StoreError::NotNestable)
212+ ));
213+
214+ // Nothing was written by any of the three refusals.
215+ assert_eq!(scratch.store.subtasks(&parent).await.unwrap().len(), 1);
216+ assert!(scratch.store.subtasks(&child).await.unwrap().is_empty());
217+ assert!(scratch.store.subtasks(&loose).await.unwrap().is_empty());
218+}
219+
220+#[tokio::test]
221+async fn a_task_cannot_be_its_own_parent() {
222+ let scratch = Scratch::open().await;
223+ let (workspace, admin) = claim(&scratch.store).await;
224+ let task = add_task(&scratch.store, &workspace, "Backlog", "Alone", None, &admin).await;
225+
226+ assert!(matches!(
227+ scratch.store.set_parent(&task, Some(&task)).await,
228+ Err(StoreError::Cycle)
229+ ));
230+ assert!(scratch.store.subtasks(&task).await.unwrap().is_empty());
231+}
232+
233+#[tokio::test]
234+async fn parenting_and_promoting_are_each_one_write() {
235+ let scratch = Scratch::open().await;
236+ let (workspace, admin) = claim(&scratch.store).await;
237+ let parent = add_task(&scratch.store, &workspace, "Backlog", "Parent", None, &admin).await;
238+ let loose = add_task(&scratch.store, &workspace, "Review", "Loose", None, &admin).await;
239+
240+ scratch.store.set_parent(&loose, Some(&parent)).await.unwrap();
241+ let children = scratch.store.subtasks(&parent).await.unwrap();
242+ assert_eq!(children.len(), 1);
243+ assert_eq!(children[0].id, loose);
244+ // It kept everything a task has: it did not move column to become one.
276 assert_eq!(245 assert_eq!(
277- decisions.len(),246+ children[0].column_id,
278- 1,247+ column_named(&scratch.store, &workspace, "Review").await
279- "the decision survived, joined to its rule"
280 );248 );
281- assert_eq!(decisions[0].rule_id, rule);
282 249
283- drop(store);250+ scratch.store.set_parent(&loose, None).await.unwrap();
284- let _ = std::fs::remove_dir_all(path.parent().unwrap());251+ assert!(scratch.store.subtasks(&parent).await.unwrap().is_empty());
252+}
253+
254+#[tokio::test]
255+async fn parenting_a_task_that_is_not_there_is_not_found() {
256+ let scratch = Scratch::open().await;
257+ let (workspace, admin) = claim(&scratch.store).await;
258+ let task = add_task(&scratch.store, &workspace, "Backlog", "Alone", None, &admin).await;
259+
260+ assert!(matches!(
261+ scratch.store.set_parent(&task, Some("nope")).await,
262+ Err(StoreError::NotFound)
263+ ));
264+ assert!(matches!(
265+ scratch.store.set_parent("nope", None).await,
266+ Err(StoreError::NotFound)
267+ ));
285 }268 }
286 269
287 #[tokio::test]270 #[tokio::test]
@@ -2033,6 +2016,7 @@ async fn add_task(
2033 .create_task(NewTask {2016 .create_task(NewTask {
2034 board_id: &board.id,2017 board_id: &board.id,
2035 column_id: &column_id,2018 column_id: &column_id,
2019+ parent_id: None,
2036 title,2020 title,
2037 description: "",2021 description: "",
2038 deadline,2022 deadline,
@@ -3705,6 +3689,7 @@ async fn a_task_created_straight_into_a_watched_column_mails_too() {
3705 .create_task(NewTask {3689 .create_task(NewTask {
3706 board_id: &board.id,3690 board_id: &board.id,
3707 column_id: &column_id,3691 column_id: &column_id,
3692+ parent_id: None,
3708 title: "Wire the exporter",3693 title: "Wire the exporter",
3709 description: "",3694 description: "",
3710 deadline: None,3695 deadline: None,
@@ -4920,6 +4905,7 @@ async fn a_created_task_s_activity_id_resolves_as_an_event() {
4920 4905
4921 let created = store4906 let created = store
4922 .create_task(NewTask {4907 .create_task(NewTask {
4908+ parent_id: None,
4923 board_id: &board.id,4909 board_id: &board.id,
4924 column_id: &column_id,4910 column_id: &column_id,
4925 title: "brand new",4911 title: "brand new",
crates/izlek-web/src/board.rsmodified+1 -0
@@ -110,6 +110,7 @@ async fn create_task_shared(
110 .create_task(NewTask {110 .create_task(NewTask {
111 board_id: &board.id,111 board_id: &board.id,
112 column_id,112 column_id,
113+ parent_id: None,
113 title,114 title,
114 description: description.trim(),115 description: description.trim(),
115 deadline,116 deadline,