Public: anyone can read this; the crew can change it.

Build deal-clock #2

Merged opened this in answer to

Check · Review · Land · Live done — Landed and live in production.

Merged

mason/deal-clock:mason/1-build-deal-clock → main 10 commits fork 11 threads · 11 unresolved

  • Merged. mason/1-build-deal-clock was merged into main as 8969e75.

Review

Sign in to review this change.
38 files changed +4637 −386
AGENTS.md +19 −7
@@ -29,8 +29,10 @@ preview at its own address, deployed from your branch as you push.
2929 ## The shape
3030
3131 One implementation, many doors. Every operation is a function in
32 `src/actions.ts` — `(db, who, input)` in, data or a named failure out — and
33 the page (`src/routes.ts`, `src/page.ts`), the JSON API (`src/routes.ts`),
32 `src/deals.ts` (deals, their dates, parties and reminders) or
33 `src/actions.ts` (notes, the audit trail) — `(db, who, input)` in, data or
34 a named failure out, shaped by `src/result.ts` — and
35 the pages (`src/routes.ts`, `src/pages/`), the JSON API (`src/routes.ts`),
3436 the MCP server (`src/mcp.ts`) and the terminal (`src/tty.ts`) call it. A
3537 door reads its wire format and shapes the answer; it decides nothing. A
3638 rule in an action holds at every door at once; a rule anywhere else is a
@@ -74,13 +76,21 @@ door that was decided.
7476
7577 To add a concept:
7678
77 - **An action** — a function in `src/actions.ts` that asks `permit`, its
79 - **Deal date math** — pure functions in `src/dates.ts` (calendar) and
80 `src/deadlines.ts` (what a contract's dates are); drafts in
81 `src/reminders.ts`, the calendar file in `src/ics.ts`. None of them reads
82 a database or a clock (`today()` is the one clock), so each is tested on
83 plain data. A change to a deal's dates, parties or reminders is an
84 `update` of the deal: it asks `permit(who, "deal", "update", deal)` and is
85 audited against the deal's id.
86 - **An action** — a function in `src/actions.ts` or `src/deals.ts` that asks `permit`, its
7887 resource's row in `contract.json`, its door in `src/contract.test.ts`,
7988 and a test in `src/actions.test.ts` for what the table cannot say.
8089 - **A migration** — append to `migrations` in `src/db.ts`. Never edit one
8190 that has run. `bun run src/db.ts --check` shows the version.
82 - **A page** — a row in `src/routes.ts` and a function in `src/page.ts`.
83 With a second page, move them under `src/pages/` and keep one `layout`.
91 - **A page** — a row in `src/routes.ts` and a function in `src/pages/`,
92 wrapped in the one `layout` (`src/pages/layout.ts`). A form posts, and
93 comes back to the page it names in `to` (checked by `backTo`).
8494 - **An API route** — a row in `src/routes.ts` that calls the action and
8595 answers with `answer(...)`; the status follows the failure. Give it an
8696 `api` entry beside it (a sentence, the body and answer as JSON Schema)
@@ -90,8 +100,10 @@ To add a concept:
90100 names, so the door and the forge's probe find them.
91101 - **A tool** — an entry in `tools` in `src/mcp.ts`: a name, one sentence,
92102 a JSON schema, the action.
93 - **A terminal command** — a key in `src/tty.ts` that calls the action and
94 reports on the status line.
103 - **A terminal command** — a key in `src/terminal.ts` that calls the action
104 and reports on the status line, and a test in `src/terminal.test.ts` that
105 presses it. `src/tty.ts` only wires it to the pty. A write there reaches
106 pages live because the server `follow`s the database (`src/live.ts`).
95107 - **Something live** — `emit(type, data)` in the action, and
96108 `data-live="<types>"` on the region of the page that shows it.
97109 - **A colour, a space, a size** — a token in `design/tokens.json` (a
README.md +104 −19
@@ -1,6 +1,82 @@
11 # deal-clock
22
3 Every deadline of every deal on one timeline: inspection, appraisal, financing and closing, with reminders to each party before anything slips.
3 Every deadline of every deal on one timeline, so nothing slips.
4
5 ## For the agent
6
7 **The clock** is the first screen. Each deal is a lane; time runs left to
8 right, and today is the dark line down the middle. Every date in a contract
9 is a marker on its lane:
10
11 - **red** — overdue
12 - **amber** — due within three days
13 - **teal** — coming up
14 - **grey** — done
15
16 Tap a marker to see who owes what, the reminder drafts for each party,
17 and two buttons: **Mark done**, and **Move this date** (it asks why, and
18 keeps the reason). Moving one date moves nothing else.
19
20 Under the clock, **Reminders for today** lists what should go out this
21 morning. Every open date reminds the parties it concerns — buyer, seller,
22 lender, title company, the other agent — **three days before** and **the
23 morning of**. Open a draft to read it; tap **Send** to mark it sent.
24
25 **A deal's page** (tap its address) lists every date and party. Add a date
26 the contract adds (an HOA review, a repair deadline), add the lender or the
27 title company, and **Add to calendar** downloads an `.ics` file with every
28 date and its alarms for your own calendar.
29
30 **New deal** takes the address, buyer, seller, contract date and closing
31 date, and works out the rest from the contingency lengths. The defaults —
32 inspection 10 days, appraisal 21, financing 30, title 14, final walkthrough
33 the day before closing — are editable on the form. Days are calendar days;
34 tick *Count business days* to skip weekends.
35
36 Four sample deals are already in: one with an overdue inspection, one
37 closing this week, one whose appraisal was moved, and one just signed.
38 Their dates are set relative to the day the app first started.
39
40 ### What is real, and what is not yet
41
42 - **Real:** the dates and their math, mark done, moves with their reasons,
43 who owes what, the reminder drafts, the record of what was sent, the
44 calendar file, and `POST /tick` (below).
45 - **Simulated:** sending. *Send* records that a reminder went out; no
46 email or text message leaves the app.
47 - **Not in this prototype:** real email or SMS, e-signature, document
48 storage, and reading the dates out of a contract PDF (phase two).
49
50 Deals are private: sign in (the forge's account) to see the clock or a
51 deal, and to open deals, mark dates done, move them and send reminders. A
52 visitor who is not signed in is asked to sign in, and sees nothing of any
53 deal. Only the agent who opened a deal, or an admin, can remove it.
54
55 The name and brokerage in the header come from two settings
56 (Settings → App → Environment): `DEAL_CLOCK_AGENT` and
57 `DEAL_CLOCK_BROKERAGE`. Dates follow the server's time zone (`TZ`).
58
59 ## For whoever runs it
60
61 `POST /tick` answers the reminders that go out today and are not yet
62 marked sent, as JSON — call it each morning as a signed-in account (a
63 stranger gets 401; it sends nothing and changes nothing). `GET /deals/:id/ics` is a deal's calendar file. The JSON API is
64 `/api/deals`, described at `/openapi.json`; the same operations are MCP
65 tools at `POST /mcp` (`list_deals`, `get_deal`, `reminders_today`,
66 `mark_done`, `move_date`, `send_reminder`).
67
outdated

"The terminal does the page's work too" is not yet true: there is no way to open a new deal there. Once n exists, list it here.

68 The terminal does the page's work too. It opens on every open date, soonest
69 first: `n` opens a new deal (address, buyer, seller, contract date, closing
70 date; the standard lengths do the rest), `x` marks the date under the cursor
71 done, `u` reopens it, `m` moves it (the new date, then the reason), `o` opens
72 its deal — where `a` adds a date,
73 `p` adds a party and `D` removes the deal after you type `yes` — and `h`
74 shows done dates. `r` lists today's reminders: enter reads a draft, `s`
75 sends it. `j`/`k` move, `b` goes back, `q` quits. What you change there
76 shows on every open page within a second.
77
78 No runtime dependencies: Bun, `bun:sqlite`, and the browser's own popovers
79 — the page needs no script to work.
480
581 This is an app: the forge runs it. Production follows the default branch;
682 every open pull gets a preview at its own address with its own copy of the
@@ -29,7 +105,12 @@ decide nothing themselves. `AGENTS.md` says how to add to it.
29105
30106 | file | what it is |
31107 | ---------------------------------- | -------------------------------------------------------------- |
32 | `src/actions.ts` | list, add, delete; the audit trail, read |
108 | `src/deals.ts` | deals: open, read, move a date, mark done, parties, reminders sent |
109 | `src/dates.ts`, `src/deadlines.ts` | calendar math; the standard contract dates and who owes them |
110 | `src/reminders.ts`, `src/ics.ts` | reminder drafts and `/tick`; the calendar file |
111 | `src/sample.ts` | the four sample deals a new database starts with |
112 | `src/result.ts` | what an action answers, and the audit habit they share |
113 | `src/actions.ts` | notes (the API scaffold); the audit trail, read |
33114 | `contract.json` | who may do what: roles, and the least role each verb needs |
34115 | `src/contract.ts`, `src/can.ts` | the table, read at boot; the forge's evaluator, verbatim |
35116 | `src/security.ts` | the door: rationing, same origin, the table before the body |
@@ -40,13 +121,13 @@ decide nothing themselves. `AGENTS.md` says how to add to it.
40121 | `src/mcp.ts` | the actions as MCP tools at `POST /mcp` |
41122 | `src/routes.ts` | every path, in one table, each API route described beside it |
42123 | `src/openapi.ts` | the routes as OpenAPI; committed at `contract/openapi.json` |
43 | `src/page.ts` | the HTML, rendered on the server, with its share metadata |
124 | `src/pages/` | the clock, a deal, a new deal, a date's sheet; one `layout` |
44125 | `design/tokens.json`, `src/tokens.ts` | the look as data, light and dark; compiled to `/tokens.css` |
45126 | `src/http.ts` | the floor: headers, body cap, files |
46127 | `src/server.ts` | boot: open the database, serve |
47 | `src/tty.ts` | the terminal, over the same actions |
128 | `src/tty.ts`, `src/terminal.ts` | the terminal: the pty, and the keys and screen over the same actions |
48129 | `src/env.ts` | what the forge told this process |
49 | `static/app.css`, `static/live.js` | the look in the tokens' words, and the list that stays current |
130 | `static/app.css`, `static/live.js` | the look in the tokens' words, and the clock that stays current |
50131
51132 ## What every app stands on
52133
@@ -77,10 +158,12 @@ decide nothing themselves. `AGENTS.md` says how to add to it.
77158 The forge says who is asking on every request it proxies, and the app
78159 verifies the signature (`src/who.ts`); nothing else is trusted. Three tiers:
79160
80 - **anon** — anyone. Reads.
81 - **user** — signed in to the forge and able to see this app. Adds notes, as
82 themselves, and removes their own.
83 - **admin** — able to write this repository. Removes any note.
161 - **anon** — anyone. Sees the sign-in notice; no deal, date or party.
162 - **user** — signed in to the forge and able to see this app. Reads every
163 deal, its parties and their contacts. Opens deals,
164 marks dates done, moves them, adds dates and parties, sends reminders;
165 removes the deals they opened (and their own notes).
166 - **admin** — able to write this repository. Removes any deal or note.
84167
85168 "Sign in" is `/__forge/signin?to=<path>` and "Sign out" is
86169 `/__forge/signout`; the forge answers both on the app's own host, and
@@ -93,32 +176,34 @@ The same actions, the same rules, at every door. A script is the person
93176 whose forge grant it carries; a bare script is anonymous.
94177
95178 ```sh
96 curl https://<app>/api/notes
97 curl -X POST https://<app>/api/notes -H 'content-type: application/json' -d '{"body":"hi"}'
98 curl -X DELETE https://<app>/api/notes/1
179 curl https://<app>/api/deals
180 curl -X POST https://<app>/tick
181 curl https://<app>/deals/1/ics
99182 ```
100183
101 As an MCP server, for Claude Code or Claude Desktop — `list_notes`,
102 `add_note`, `delete_note`:
184 As an MCP server, for Claude Code or Claude Desktop — the deal tools above,
185 and `list_notes`, `add_note`, `delete_note`:
103186
104187 ```sh
105 claude mcp add --transport http __TITLE__ https://<app>/mcp
188 claude mcp add --transport http deal-clock https://<app>/mcp
106189 ```
107190
108191 ```json
109192 {
110 "mcpServers": { "__TITLE__": { "type": "http", "url": "https://<app>/mcp" } }
193 "mcpServers": { "deal-clock": { "type": "http", "url": "https://<app>/mcp" } }
111194 }
112195 ```
113196
114 The page stays current over `/events`: a note someone else adds or removes
115 appears without a reload. Without JavaScript it is the same page, one
197 The clock stays current over `/events`: a date someone else marks done or
198 moves — on the page, over the API, or in the terminal — changes without a
199 reload. Without JavaScript it is the same page, one
116200 reload behind.
117201
118202 The terminal opens with the exact command in `FORGE_APP_SSH` when the app
119203 runs (`ssh -p 2222 <name>@<forge>` — the app is the login name, the forge
120204 the host; `<name>--<pull>@<forge>` for a preview's). It is `src/tty.ts` on
121 a real pty over the same data, as the account at the keyboard.
205 a real pty over the same data, as the account at the keyboard; everything
206 it does is `src/terminal.ts`, which `src/terminal.test.ts` drives key by key.
122207
123208 The forge sets `PORT`, `FORGE_APP_DATA`, `FORGE_APP_ENV` (`production` or
124209 `preview`), `FORGE_APP_URL`, `FORGE_APP_COMMIT`, `FORGE_APP_SSH` and
contract.json +10
@@ -16,6 +16,16 @@
1616 "list": "anon"
1717 }
1818 },
19 "deal": {
20 "api": "/api/deals",
21 "can": {
22 "create": "user",

Medium: with read/list anon, every party's contact (email or phone) is public through /api/deals, /tick, the .ics and MCP. Before real deals go in, either redact contact for a reader who may not update the deal, or raise read/list to user.

23 "read": "user",
24 "update": "user",

Not blocking, but worth the signer's attention: update: user lets any signed-in account change any deal and see its parties' contacts. It is fine for the sample-data meeting. Make it author before real clients go in.

Info: update: user lets any signed-in forge account change any deal, see every party's email and phone, and mark reminders sent. That fits a one-agent prototype and the README says it. If this ever serves a team, a member role under user is the narrower cell. That would be a new role, not a loosened one.

Low: update: user means any account that can see the app can mark done, move or send on any agent's deal. That fits a single-agent prototype with sample-authored deals. Before a second agent uses it, narrow this to author (an admin still overrides), and shown will start blanking contacts as written.

25 "delete": "author",
26 "list": "user"
27 }
28 },
1929 "audit": {
2030 "api": "/api/audit",
2131 "can": {
contract/openapi.json +538
@@ -6,6 +6,50 @@
66 "description": "Every deadline of every deal on one timeline: inspection, appraisal, financing and closing, with reminders to each party before anything slips."
77 },
88 "paths": {
9 "/tick": {
10 "post": {
11 "summary": "The reminders that go out today and have not been sent: call it each morning. It sends nothing and changes nothing.",
12 "operationId": "postTick",
13 "responses": {
14 "200": {
15 "description": "The reminders that go out today and have not been sent: call it each morning. It sends nothing and changes nothing.",
16 "content": {
17 "application/json": {
18 "schema": {
19 "type": "object",
20 "properties": {
21 "on": {
22 "type": "string",
23 "format": "date"
24 },
25 "reminders": {
26 "type": "array",
27 "items": {
28 "$ref": "#/components/schemas/Reminder"
29 }
30 }
31 },
32 "required": [
33 "on",
34 "reminders"
35 ]
36 }
37 }
38 }
39 },
40 "default": {
41 "description": "{ error, message }: why not",
42 "content": {
43 "application/json": {
44 "schema": {
45 "$ref": "#/components/schemas/Error"
46 }
47 }
48 }
49 }
50 }
51 }
52 },
953 "/api/notes": {
1054 "get": {
1155 "summary": "The notes, newest first.",
@@ -258,6 +302,302 @@
258302 }
259303 }
260304 },
305 "/api/deals": {
306 "get": {
307 "summary": "Every deal with its dates, parties and sent reminders, soonest closing first.",
308 "operationId": "getApiDeals",
309 "responses": {
310 "200": {
311 "description": "Every deal with its dates, parties and sent reminders, soonest closing first.",
312 "content": {
313 "application/json": {
314 "schema": {
315 "type": "array",
316 "items": {
317 "$ref": "#/components/schemas/Deal"
318 }
319 }
320 }
321 }
322 },
323 "default": {
324 "description": "{ error, message }: why not",
325 "content": {
326 "application/json": {
327 "schema": {
328 "$ref": "#/components/schemas/Error"
329 }
330 }
331 }
332 }
333 },
334 "x-contract": {
335 "resource": "deal",
336 "verb": "list",
337 "least": "user"
338 }
339 },
340 "post": {
341 "summary": "Open a deal: its standard dates are computed from the contract date, the closing date and the contingency lengths.",
342 "operationId": "postApiDeals",
343 "requestBody": {
344 "required": true,
345 "content": {
346 "application/json": {
347 "schema": {
348 "type": "object",
349 "properties": {
350 "address": {
351 "type": "string",
352 "minLength": 3,
353 "maxLength": 200
354 },
355 "buyer": {
356 "type": "string",
357 "minLength": 1,
358 "maxLength": 100
359 },
360 "seller": {
361 "type": "string",
362 "minLength": 1,
363 "maxLength": 100
364 },
365 "contract_date": {
366 "type": "string",
367 "format": "date"
368 },
369 "closing_date": {
370 "type": "string",
371 "format": "date"
372 },
373 "inspection": {
374 "type": "integer",
375 "minimum": 0,
376 "maximum": 180,
377 "default": 10
378 },
379 "appraisal": {
380 "type": "integer",
381 "minimum": 0,
382 "maximum": 180,
383 "default": 21
384 },
385 "financing": {
386 "type": "integer",
387 "minimum": 0,
388 "maximum": 180,
389 "default": 30
390 },
391 "title": {
392 "type": "integer",
393 "minimum": 0,
394 "maximum": 180,
395 "default": 14
396 },
397 "walkthrough": {
398 "type": "integer",
399 "minimum": 0,
400 "maximum": 180,
401 "default": 1
402 },
403 "business_days": {
404 "type": "boolean",
405 "default": false
406 }
407 },
408 "required": [
409 "address",
410 "buyer",
411 "seller",
412 "contract_date",
413 "closing_date"
414 ]
415 }
416 }
417 }
418 },
419 "responses": {
420 "201": {
421 "description": "Open a deal: its standard dates are computed from the contract date, the closing date and the contingency lengths.",
422 "content": {
423 "application/json": {
424 "schema": {
425 "$ref": "#/components/schemas/Deal"
426 }
427 }
428 }
429 },
430 "default": {
431 "description": "{ error, message }: why not",
432 "content": {
433 "application/json": {
434 "schema": {
435 "$ref": "#/components/schemas/Error"
436 }
437 }
438 }
439 }
440 },
441 "x-contract": {
442 "resource": "deal",
443 "verb": "create",
444 "least": "user"
445 }
446 }
447 },
448 "/api/deals/{id}": {
449 "get": {
450 "summary": "One deal.",
451 "operationId": "getApiDealsId",
452 "parameters": [
453 {
454 "name": "id",
455 "in": "path",
456 "required": true,
457 "schema": {
458 "type": "integer"
459 }
460 }
461 ],
462 "responses": {
463 "200": {
464 "description": "One deal.",
465 "content": {
466 "application/json": {
467 "schema": {
468 "$ref": "#/components/schemas/Deal"
469 }
470 }
471 }
472 },
473 "default": {
474 "description": "{ error, message }: why not",
475 "content": {
476 "application/json": {
477 "schema": {
478 "$ref": "#/components/schemas/Error"
479 }
480 }
481 }
482 }
483 },
484 "x-contract": {
485 "resource": "deal",
486 "verb": "read",
487 "least": "user"
488 }
489 },
490 "patch": {
491 "summary": "Correct a deal's address. Dates move one at a time, with a reason (POST /deadlines/:id/move).",
492 "operationId": "patchApiDealsId",
493 "parameters": [
494 {
495 "name": "id",
496 "in": "path",
497 "required": true,
498 "schema": {
499 "type": "integer"
500 }
501 }
502 ],
503 "requestBody": {
504 "required": true,
505 "content": {
506 "application/json": {
507 "schema": {
508 "type": "object",
509 "properties": {
510 "address": {
511 "type": "string",
512 "minLength": 3,
513 "maxLength": 200
514 }
515 },
516 "required": [
517 "address"
518 ]
519 }
520 }
521 }
522 },
523 "responses": {
524 "200": {
525 "description": "Correct a deal's address. Dates move one at a time, with a reason (POST /deadlines/:id/move).",
526 "content": {
527 "application/json": {
528 "schema": {
529 "$ref": "#/components/schemas/Deal"
530 }
531 }
532 }
533 },
534 "default": {
535 "description": "{ error, message }: why not",
536 "content": {
537 "application/json": {
538 "schema": {
539 "$ref": "#/components/schemas/Error"
540 }
541 }
542 }
543 }
544 },
545 "x-contract": {
546 "resource": "deal",
547 "verb": "update",
548 "least": "user"
549 }
550 },
551 "delete": {
552 "summary": "Remove a deal and everything on it.",
553 "operationId": "deleteApiDealsId",
554 "parameters": [
555 {
556 "name": "id",
557 "in": "path",
558 "required": true,
559 "schema": {
560 "type": "integer"
561 }
562 }
563 ],
564 "responses": {
565 "200": {
566 "description": "Remove a deal and everything on it.",
567 "content": {
568 "application/json": {
569 "schema": {
570 "type": "object",
571 "properties": {
572 "id": {
573 "type": "integer"
574 }
575 },
576 "required": [
577 "id"
578 ]
579 }
580 }
581 }
582 },
583 "default": {
584 "description": "{ error, message }: why not",
585 "content": {
586 "application/json": {
587 "schema": {
588 "$ref": "#/components/schemas/Error"
589 }
590 }
591 }
592 }
593 },
594 "x-contract": {
595 "resource": "deal",
596 "verb": "delete",
597 "least": "author"
598 }
599 }
600 },
261601 "/api/audit": {
262602 "get": {
263603 "summary": "The audit trail, newest first; `before` pages back by id.",
@@ -498,6 +838,204 @@
498838 "updated_at"
499839 ]
500840 },
841 "Deal": {
842 "type": "object",
843 "properties": {
844 "id": {
845 "type": "integer"
846 },
847 "address": {
848 "type": "string"
849 },
850 "contract_date": {
851 "type": "string",
852 "format": "date"
853 },
854 "closing": {
855 "type": "string",
856 "format": "date"
857 },
858 "business_days": {
859 "enum": [
860 0,
861 1
862 ]
863 },
864 "author_id": {
865 "type": "string"
866 },
867 "author_name": {
868 "type": "string"
869 },
870 "created_at": {
871 "type": "string",
872 "format": "date-time"
873 },
874 "parties": {
875 "type": "array",
876 "items": {
877 "type": "object",
878 "properties": {
879 "id": {
880 "type": "integer"
881 },
882 "role": {
883 "enum": [
884 "buyer",
885 "seller",
886 "lender",
887 "title",
888 "other_agent"
889 ]
890 },
891 "name": {
892 "type": "string"
893 },
894 "contact": {
895 "type": "string"
896 }
897 }
898 }
899 },
900 "deadlines": {
901 "type": "array",
902 "items": {
903 "type": "object",
904 "properties": {
905 "id": {
906 "type": "integer"
907 },
908 "kind": {
909 "enum": [
910 "inspection",
911 "appraisal",
912 "financing",
913 "title",
914 "walkthrough",
915 "closing",
916 "custom"
917 ]
918 },
919 "label": {
920 "type": "string"
921 },
922 "due": {
923 "type": "string",
924 "format": "date"
925 },
926 "owes": {
927 "enum": [
928 "buyer",
929 "seller",
930 "lender",
931 "title",
932 "other_agent"
933 ]
934 },
935 "what": {
936 "type": "string"
937 },
938 "done_at": {
939 "type": [
940 "string",
941 "null"
942 ]
943 },
944 "moves": {
945 "type": "array",
946 "items": {
947 "type": "object"
948 }
949 }
950 }
951 }
952 },
953 "sent": {
954 "type": "array",
955 "items": {
956 "type": "object"
957 }
958 }
959 },
960 "required": [
961 "id",
962 "address",
963 "contract_date",
964 "closing",
965 "parties",
966 "deadlines"
967 ]
968 },
969 "Reminder": {
970 "type": "object",
971 "properties": {
972 "deal_id": {
973 "type": "integer"
974 },
975 "address": {
976 "type": "string"
977 },
978 "deadline_id": {
979 "type": "integer"
980 },
981 "label": {
982 "type": "string"
983 },
984 "due": {
985 "type": "string",
986 "format": "date"
987 },
988 "party_id": {
989 "type": "integer"
990 },
991 "party_name": {
992 "type": "string"
993 },
994 "party_role": {
995 "enum": [
996 "buyer",
997 "seller",
998 "lender",
999 "title",
1000 "other_agent"
1001 ]
1002 },
1003 "contact": {
1004 "type": "string"
1005 },
1006 "moment": {
1007 "enum": [
1008 "before",
1009 "day_of"
1010 ]
1011 },
1012 "on": {
1013 "type": "string",
1014 "format": "date"
1015 },
1016 "subject": {
1017 "type": "string"
1018 },
1019 "body": {
1020 "type": "string"
1021 },
1022 "sent_at": {
1023 "type": [
1024 "string",
1025 "null"
1026 ]
1027 }
1028 },
1029 "required": [
1030 "deal_id",
1031 "deadline_id",
1032 "party_id",
1033 "moment",
1034 "on",
1035 "subject",
1036 "body"
1037 ]
1038 },
5011039 "AuditRow": {
5021040 "type": "object",
5031041 "properties": {
design/tokens.json +202 −35
@@ -3,93 +3,260 @@
33 "color": {
44 "$type": "color",
55 "bg": {
6 "$value": "#f6f6f3",
7 "$extensions": { "mode": { "dark": "#131312" } }
6 "$value": "#f6f3ec",
7 "$extensions": {
8 "mode": {
9 "dark": "#121516"
10 }
11 }
812 },
913 "surface": {
10 "$value": "#ffffff",
11 "$extensions": { "mode": { "dark": "#1d1d1b" } }
14 "$value": "#fffdf8",
15 "$extensions": {
16 "mode": {
17 "dark": "#1a1f20"
18 }
19 }
1220 },
1321 "fg": {
14 "$value": "#1c1c1a",
15 "$extensions": { "mode": { "dark": "#ecece7" } }
22 "$value": "#1d2a2c",
23 "$extensions": {
24 "mode": {
25 "dark": "#e9ece9"
26 }
27 }
1628 },
1729 "muted": {
18 "$value": "#6b6b65",
19 "$extensions": { "mode": { "dark": "#9a9a93" } }
30 "$value": "#5a6866",
31 "$extensions": {
32 "mode": {
33 "dark": "#9aa6a3"
34 }
35 }
2036 },
2137 "line": {
22 "$value": "#e3e3dd",
23 "$extensions": { "mode": { "dark": "#2c2c29" } }
38 "$value": "#e3ddd0",
39 "$extensions": {
40 "mode": {
41 "dark": "#2b3335"
42 }
43 }
2444 },
2545 "accent": {
26 "$value": "#2f5bea",
27 "$extensions": { "mode": { "dark": "#7c96ff" } }
46 "$value": "#1d5c57",
47 "$extensions": {
48 "mode": {
49 "dark": "#7fcbc2"
50 }
51 }
2852 },
2953 "accent-fg": {
3054 "$value": "#ffffff",
31 "$extensions": { "mode": { "dark": "#0f1a4d" } }
55 "$extensions": {
56 "mode": {
57 "dark": "#0d2422"
58 }
59 }
3260 },
3361 "danger": {
34 "$value": "#c2410c",
35 "$extensions": { "mode": { "dark": "#fb923c" } }
62 "$value": "#b3261e",
63 "$extensions": {
64 "mode": {
65 "dark": "#ff8b80"
66 }
67 }
3668 },
3769 "toast-bg": {
38 "$value": "#1c1c1a",
39 "$extensions": { "mode": { "dark": "#ecece7" } }
70 "$value": "#1d2a2c",
71 "$extensions": {
72 "mode": {
73 "dark": "#e9ece9"
74 }
75 }
4076 },
4177 "toast-fg": {
42 "$value": "#f6f6f3",
43 "$extensions": { "mode": { "dark": "#131312" } }
78 "$value": "#f6f3ec",
79 "$extensions": {
80 "mode": {
81 "dark": "#121516"
82 }
83 }
4484 },
4585 "shadow": {
4686 "$value": "#0000002e",
47 "$extensions": { "mode": { "dark": "#00000080" } }
87 "$extensions": {
88 "mode": {
89 "dark": "#00000080"
90 }
91 }
92 },
93 "lane": {
94 "$value": "#faf8f2",
95 "$extensions": {
96 "mode": {
97 "dark": "#161b1c"
98 }
99 }
100 },
101 "soon": {
102 "$value": "#8a5300",
103 "$extensions": {
104 "mode": {
105 "dark": "#f2b84b"
106 }
107 }
108 },
109 "soon-bg": {
110 "$value": "#fcefd4",
111 "$extensions": {
112 "mode": {
113 "dark": "#33270e"
114 }
115 }
116 },
117 "overdue": {
118 "$value": "#b3261e",
119 "$extensions": {
120 "mode": {
121 "dark": "#ff8b80"
122 }
123 }
124 },
125 "overdue-bg": {
126 "$value": "#fbe5e1",
127 "$extensions": {
128 "mode": {
129 "dark": "#3a1714"
130 }
131 }
132 },
133 "done": {
134 "$value": "#9aa19f",
135 "$extensions": {
136 "mode": {
137 "dark": "#55605e"
138 }
139 }
140 },
141 "done-bg": {
142 "$value": "#eeeeea",
143 "$extensions": {
144 "mode": {
145 "dark": "#232a2b"
146 }
147 }
148 },
149 "later-bg": {
150 "$value": "#e3efed",
151 "$extensions": {
152 "mode": {
153 "dark": "#15302d"
154 }
155 }
48156 }
49157 },
50158 "space": {
51159 "$type": "dimension",
52 "1": { "$value": "0.25rem" },
53 "2": { "$value": "0.5rem" },
54 "3": { "$value": "0.75rem" },
55 "4": { "$value": "1rem" },
56 "5": { "$value": "1.5rem" },
57 "6": { "$value": "2.5rem" }
160 "1": {
161 "$value": "0.25rem"
162 },
163 "2": {
164 "$value": "0.5rem"
165 },
166 "3": {
167 "$value": "0.75rem"
168 },
169 "4": {
170 "$value": "1rem"
171 },
172 "5": {
173 "$value": "1.5rem"
174 },
175 "6": {
176 "$value": "2.5rem"
177 }
58178 },
59179 "radius": {
60180 "$type": "dimension",
61 "md": { "$value": "10px" },
62 "pill": { "$value": "999px" }
181 "md": {
182 "$value": "10px"
183 },
184 "pill": {
185 "$value": "999px"
186 },
187 "sm": {
188 "$value": "6px"
189 }
63190 },
64191 "size": {
65192 "$type": "dimension",
66193 "tap": {
67194 "$value": "44px",
68195 "$description": "The least a control measures on a side."
196 },
197 "day": {
198 "$value": "2.25rem",
199 "$description": "One day's width on the clock."
69200 }
70201 },
71202 "font": {
72203 "$type": "fontFamily",
73204 "sans": {
74 "$value": ["system-ui", "-apple-system", "Segoe UI", "sans-serif"]
205 "$value": [
206 "system-ui",
207 "-apple-system",
208 "Segoe UI",
209 "sans-serif"
210 ]
75211 },
76212 "mono": {
77 "$value": ["ui-monospace", "SFMono-Regular", "Menlo", "monospace"]
213 "$value": [
214 "ui-monospace",
215 "SFMono-Regular",
216 "Menlo",
217 "monospace"
218 ]
219 },
220 "display": {
221 "$value": [
222 "Iowan Old Style",
223 "Palatino Linotype",
224 "Book Antiqua",
225 "Palatino",
226 "Georgia",
227 "serif"
228 ]
78229 }
79230 },
80231 "text": {
81232 "$type": "dimension",
82 "sm": { "$value": "0.875rem" },
233 "xs": {
234 "$value": "0.75rem"
235 },
236 "sm": {
237 "$value": "0.875rem"
238 },
83239 "base": {
84240 "$value": "1rem",
85241 "$description": "Never below 16px: a phone zooms into a smaller input."
86242 },
87 "lg": { "$value": "1.125rem" },
88 "xl": { "$value": "1.5rem" }
243 "lg": {
244 "$value": "1.125rem"
245 },
246 "xl": {
247 "$value": "1.5rem"
248 },
249 "2xl": {
250 "$value": "1.875rem"
251 }
89252 },
90253 "leading": {
91254 "$type": "number",
92 "body": { "$value": 1.55 },
93 "tight": { "$value": 1.2 }
255 "body": {
256 "$value": 1.55
257 },
258 "tight": {
259 "$value": 1.2
260 }
94261 }
95262 }
src/actions.ts +4 −43
@@ -7,11 +7,14 @@
77 */
88
99 import type { Database } from "bun:sqlite";
10 import { record, type AuditRow } from "./audit.ts";
10 import type { AuditRow } from "./audit.ts";
1111 import { permit } from "./contract.ts";
1212 import { emit } from "./live.ts";
13 import { audited, fail, ok, refuse, type Result } from "./result.ts";
1314 import type { Who } from "./who.ts";
1415
16 export type { Failure, Result } from "./result.ts";
17
1518 export interface Note {
1619 readonly id: number;
1720 readonly body: string;
@@ -21,46 +24,8 @@ export interface Note {
2124 readonly updated_at: string;
2225 }
2326
24 export type Failure = "signin_required" | "forbidden" | "not_found" | "invalid";
25 export type Result<T> =
26 | { ok: true; value: T }
27 | { ok: false; error: Failure; message: string };
28 const ok = <T>(value: T): Result<T> => ({ ok: true, value });
29 const fail = <T>(error: Failure, message: string): Result<T> => ({
30 ok: false,
31 error,
32 message,
33 });
34
3527 export const BODY_MAX = 500;
3628
37 /** The refusal for a "no": who is not signed in is asked to; who is, is told. */
38 const refuse = <T>(who: Who, signIn: string, no: string): Result<T> =>
39 who.role === "anon" ? fail("signin_required", signIn) : fail("forbidden", no);
40
41 /**
42 * A change, written into the audit trail whichever way it went: the row it
43 * made or touched, or the one it was refused. Every action that changes
44 * something returns through here, so the trail holds at every door.
45 */
46 const audited = <T extends { readonly id: number }>(
47 db: Database,
48 who: Who,
49 resource: string,
50 verb: "create" | "update" | "delete",
51 target: number | undefined,
52 result: Result<T>,
53 ): Result<T> => {
54 record(db, {
55 who,
56 resource,
57 verb,
58 target: result.ok ? result.value.id : target,
59 outcome: result.ok ? "ok" : result.error,
60 });
61 return result;
62 };
63
6429 export function listNotes(
6530 db: Database,
6631 who: Who,
@@ -210,10 +175,6 @@ function remove(
210175 return ok({ id: found.value.id });
211176 }
212177
213 /** Whether `who` may remove `note`: the table's answer, for the page and the terminal to draw from. */
214 export const canDelete = (who: Who, note: Note): boolean =>
215 permit(who, "note", "delete", { ...note }) === "yes";
216
217178 /**
218179 * The audit trail, newest first, for whoever the table lets read it (an
219180 * admin, as the scaffold has it). `before` pages back by id. Audit rows name
src/contract.test.ts +30
@@ -18,6 +18,13 @@ import {
1818 updateNote,
1919 } from "./actions.ts";
2020 import { record } from "./audit.ts";
21 import {
22 createDeal,
23 deleteDeal,
24 getDeal,
25 listDeals,
26 updateDeal,
27 } from "./deals.ts";
2128 import { actingAs, identities, table, type Verb } from "./can.ts";
2229 import { contract } from "./contract.ts";
2330 import { openDb } from "./db.ts";
@@ -42,6 +49,14 @@ const noteBy = (authorId: string): number =>
4249 >("INSERT INTO note (body, author_id, author_name) VALUES ('n', ?1, ?1) RETURNING id")
4350 .get(authorId)!.id;
4451
52 const dealBy = (authorId: string): number =>
53 db
54 .query<
55 { id: number },
56 [string]
57 >("INSERT INTO deal (address, contract_date, author_id, author_name) VALUES ('1 Test St', '2026-10-01', ?1, ?1) RETURNING id")
58 .get(authorId)!.id;
59
4560 const auditRow = (): number => {
4661 record(db, {
4762 who: { role: "anon" },
@@ -66,6 +81,21 @@ const doors: Record<
6681 updateNote(db, who, { id: noteBy(authorId), body: "changed" }).ok,
6782 delete: (who, authorId) => deleteNote(db, who, { id: noteBy(authorId) }).ok,
6883 },
84 deal: {
85 create: (who) =>
86 createDeal(db, who, {
87 address: "1 Test St",
88 buyer: "B",
89 seller: "S",
90 contractDate: "2026-10-01",
91 closingDate: "2026-11-01",
92 }).ok,
93 list: (who) => listDeals(db, who).ok,
94 read: (who, authorId) => getDeal(db, who, { id: dealBy(authorId) }).ok,
95 update: (who, authorId) =>
96 updateDeal(db, who, { id: dealBy(authorId), address: "2 Test St" }).ok,
97 delete: (who, authorId) => deleteDeal(db, who, { id: dealBy(authorId) }).ok,
98 },
6999 // The trail is written by the app itself, never through a door: there
70100 // is no action that creates, changes or removes a row of it.
71101 audit: {
src/dates.test.ts added +104
@@ -0,0 +1,104 @@
1 /**
2 * The date math a deal stands on: contingency lengths, calendar days by
3 * default and business days when asked, and urgency on the clock.
4 */
5 import { expect, test } from "bun:test";
6 import {
7 addBusinessDays,
8 addDays,
9 daysBetween,
10 isDate,
11 relative,
12 urgency,
13 } from "./dates.ts";
14 import { DEFAULT_LENGTHS, schedule } from "./deadlines.ts";
15
16 test("a date is a real YYYY-MM-DD and nothing else", () => {
17 expect(isDate("2026-10-12")).toBe(true);
18 expect(isDate("2028-02-29")).toBe(true);
19 for (const bad of ["2026-02-30", "2026-13-01", "12/10/2026", "", 20261012, null])
20 expect([bad, isDate(bad)]).toEqual([bad, false]);
21 });
22
23 test("calendar days cross months, years and daylight saving", () => {
24 expect(addDays("2026-10-12", 10)).toBe("2026-10-22");
25 expect(addDays("2026-12-25", 10)).toBe("2027-01-04");
26 expect(addDays("2026-11-01", 1)).toBe("2026-11-02");
27 expect(addDays("2026-03-08", -1)).toBe("2026-03-07");
28 expect(daysBetween("2026-10-12", "2026-11-11")).toBe(30);
29 expect(daysBetween("2026-11-11", "2026-10-12")).toBe(-30);
30 });
31
32 test("business days step over weekends", () => {
33 // Friday + 1 business day is Monday; Monday − 1 is Friday.
34 expect(addBusinessDays("2026-10-16", 1)).toBe("2026-10-19");
35 expect(addBusinessDays("2026-10-19", -1)).toBe("2026-10-16");
36 // Monday + 10 business days is two weeks on.
37 expect(addBusinessDays("2026-10-12", 10)).toBe("2026-10-26");
38 expect(addBusinessDays("2026-10-12", 0)).toBe("2026-10-12");
39 });
40
41 test("the standard lengths: inspection 10, appraisal 21, financing 30, walkthrough closing − 1", () => {
42 expect(DEFAULT_LENGTHS).toMatchObject({
43 inspection: 10,
44 appraisal: 21,
45 financing: 30,
46 walkthrough: 1,
47 });
48 const dates = Object.fromEntries(
49 schedule({
50 contractDate: "2026-10-12",
51 closingDate: "2026-11-20",
52 lengths: DEFAULT_LENGTHS,
53 businessDays: false,
54 }).map((p) => [p.kind, p.due]),
55 );
56 expect(dates).toEqual({
57 inspection: "2026-10-22",
58 title: "2026-10-26",
59 appraisal: "2026-11-02",
60 financing: "2026-11-11",
61 walkthrough: "2026-11-19",
62 closing: "2026-11-20",
63 });
64 });
65
66 test("business days are off by default, and change every contingency when on", () => {
67 const input = {
68 contractDate: "2026-10-12",
69 closingDate: "2026-11-23",
70 lengths: { ...DEFAULT_LENGTHS, inspection: 5 },
71 };
72 const calendar = schedule({ ...input, businessDays: false });
73 const business = schedule({ ...input, businessDays: true });
74 const due = (s: typeof calendar, kind: string) =>
75 s.find((p) => p.kind === kind)?.due;
76 expect(due(calendar, "inspection")).toBe("2026-10-17"); // a Saturday, counted
77 expect(due(business, "inspection")).toBe("2026-10-19"); // Monday
78 // Walkthrough counts back from a Monday closing: Sunday, or Friday.
79 expect(due(calendar, "walkthrough")).toBe("2026-11-22");
80 expect(due(business, "walkthrough")).toBe("2026-11-20");
81 expect(due(business, "closing")).toBe("2026-11-23");
82 });
83
84 test("a schedule is in date order", () => {
85 const s = schedule({
86 contractDate: "2026-10-01",
87 closingDate: "2026-10-20",
88 lengths: DEFAULT_LENGTHS,
89 businessDays: false,
90 });
91 const dues = s.map((p) => p.due);
92 expect(dues).toEqual([...dues].sort());
93 });
94
95 test("urgency: done is grey, past due red, within three days amber", () => {
96 const on = "2026-10-12";
97 expect(urgency("2026-10-01", on, true)).toBe("done");
98 expect(urgency("2026-10-11", on, false)).toBe("overdue");
99 expect(urgency("2026-10-12", on, false)).toBe("soon");
100 expect(urgency("2026-10-15", on, false)).toBe("soon");
101 expect(urgency("2026-10-16", on, false)).toBe("later");
102 expect(relative("2026-10-15", on)).toBe("in 3 days");
103 expect(relative("2026-10-10", on)).toBe("2 days ago");
104 });
src/dates.ts added +92
@@ -0,0 +1,92 @@
1 /**
2 * Calendar dates as plain `YYYY-MM-DD` strings: what a contract speaks in.
3 * No times and no zones inside — a date is a day, computed in UTC so that
4 * adding days never trips over daylight saving. `today` is the one place a
5 * clock is read, in the zone the process runs in (`TZ`).
6 */
7
8 const ISO = /^(\d{4})-(\d{2})-(\d{2})$/;
9 const DAY_MS = 86_400_000;
10
11 /** Is this a real calendar date, written `YYYY-MM-DD`? */
12 export function isDate(value: unknown): value is string {
13 if (typeof value !== "string") return false;
14 const m = ISO.exec(value);
15 if (m === null) return false;
16 const d = new Date(Date.UTC(+m[1]!, +m[2]! - 1, +m[3]!));
17 return d.toISOString().slice(0, 10) === value;
18 }
19
20 const toMs = (date: string): number => Date.parse(`${date}T00:00:00Z`);
21 const fromMs = (ms: number): string => new Date(ms).toISOString().slice(0, 10);
22
23 /** `date` moved by `days` calendar days (negative goes back). */
24 export const addDays = (date: string, days: number): string =>
25 fromMs(toMs(date) + days * DAY_MS);
26
27 /** Days from `a` to `b`: positive when `b` is later. */
28 export const daysBetween = (a: string, b: string): number =>
29 Math.round((toMs(b) - toMs(a)) / DAY_MS);
30
31 /** Saturday or Sunday. */
32 export const isWeekend = (date: string): boolean => {
33 const day = new Date(toMs(date)).getUTCDay();
34 return day === 0 || day === 6;
35 };
36
37 /** `date` moved by `days` weekdays: weekends are stepped over, not counted. */
38 export function addBusinessDays(date: string, days: number): string {
39 const step = days < 0 ? -1 : 1;
40 let at = date;
41 for (let left = Math.abs(days); left > 0; ) {
42 at = addDays(at, step);
43 if (!isWeekend(at)) left--;
44 }
45 return at;
46 }
47
48 /** The date in this process's zone, now. */
49 export function today(now = new Date()): string {
50 const y = now.getFullYear();
51 const m = String(now.getMonth() + 1).padStart(2, "0");
52 const d = String(now.getDate()).padStart(2, "0");
53 return `${y}-${m}-${d}`;
54 }
55
56 // Formatters are costly to make and cheap to use: made once.
57 const SPOKEN = new Intl.DateTimeFormat("en-US", {
58 weekday: "short",
59 month: "short",
60 day: "numeric",
61 timeZone: "UTC",
62 });
63 const SHORT = new Intl.DateTimeFormat("en-US", {
64 month: "short",
65 day: "numeric",
66 timeZone: "UTC",
67 });
68
69 /** "Fri, Oct 16" — how a person reads a date in a sentence. */
70 export const spoken = (date: string): string => SPOKEN.format(toMs(date));
71
72 /** "Oct 16" — for tight places. */
73 export const short = (date: string): string => SHORT.format(toMs(date));
74
75 /** "in 3 days", "today", "2 days ago". */
76 export function relative(date: string, from: string): string {
77 const n = daysBetween(from, date);
78 if (n === 0) return "today";
79 if (n === 1) return "tomorrow";
80 if (n === -1) return "yesterday";
81 return n > 0 ? `in ${n} days` : `${-n} days ago`;
82 }
83
84 export type Urgency = "done" | "overdue" | "soon" | "later";
85 /** How a deadline looks on the clock: grey when done, red past due, amber within three days. */
86 export function urgency(due: string, on: string, done: boolean): Urgency {
87 if (done) return "done";
88 const n = daysBetween(on, due);
89 if (n < 0) return "overdue";
90 if (n <= 3) return "soon";
91 return "later";
92 }
src/db.test.ts +9
@@ -21,3 +21,12 @@ test("migrations apply once, in order, and the file checks out", () => {
2121 ?.foreign_keys,
2222 ).toBe(1);
2323 });
24
25 test("the sample deals are written once, however many processes open a new file", () => {
26 const dir = mkdtempSync(join(tmpdir(), "app-seed-"));
27 const [a, b] = [openDb(dir), openDb(dir)];
28 openDb(dir);
29 const count = (db: typeof a) =>
30 db.query<{ n: number }, []>("SELECT count(*) AS n FROM deal WHERE author_id = 'sample'").get()!.n;
31 expect([count(a), count(b)]).toEqual([4, 4]);
32 });
src/db.ts +54
@@ -12,6 +12,7 @@ import { Database } from "bun:sqlite";
1212 import { mkdirSync } from "node:fs";
1313 import { join } from "node:path";
1414 import { dataDir } from "./env.ts";
15 import { seed } from "./sample.ts";
1516
1617 /** Append, never edit: a migration that has run is history. */
1718 export const migrations: string[] = [
@@ -38,6 +39,58 @@ export const migrations: string[] = [
3839 allowed INTEGER NOT NULL CHECK (allowed IN (0, 1)),
3940 outcome TEXT NOT NULL
4041 )`,
42 // A deal is an address under contract; its dates and parties hang off it.
43 // The closing date is the `closing` deadline, so it moves like any other.
44 `CREATE TABLE deal (
45 id INTEGER PRIMARY KEY,
46 address TEXT NOT NULL CHECK (length(address) BETWEEN 1 AND 200),
47 contract_date TEXT NOT NULL,
48 business_days INTEGER NOT NULL DEFAULT 0 CHECK (business_days IN (0, 1)),
49 author_id TEXT NOT NULL,
50 author_name TEXT NOT NULL,
51 created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
52 )`,
53 `CREATE TABLE party (
54 id INTEGER PRIMARY KEY,
55 deal_id INTEGER NOT NULL REFERENCES deal (id) ON DELETE CASCADE,
56 role TEXT NOT NULL,
57 name TEXT NOT NULL CHECK (length(name) BETWEEN 1 AND 100),
58 contact TEXT NOT NULL DEFAULT ''
59 )`,
60 `CREATE TABLE deadline (
61 id INTEGER PRIMARY KEY,
62 deal_id INTEGER NOT NULL REFERENCES deal (id) ON DELETE CASCADE,
63 kind TEXT NOT NULL,
64 label TEXT NOT NULL CHECK (length(label) BETWEEN 1 AND 100),
65 due TEXT NOT NULL,
66 owes TEXT NOT NULL,
67 what TEXT NOT NULL DEFAULT '',
68 done_at TEXT
69 )`,
70 `CREATE INDEX deadline_deal ON deadline (deal_id, due)`,
71 // Every move of a date, with the reason the agent gave: history, never edited.
72 `CREATE TABLE deadline_move (
73 id INTEGER PRIMARY KEY,
74 deadline_id INTEGER NOT NULL REFERENCES deadline (id) ON DELETE CASCADE,
75 from_due TEXT NOT NULL,
76 to_due TEXT NOT NULL,
77 reason TEXT NOT NULL CHECK (length(reason) BETWEEN 1 AND 200),
78 by_name TEXT NOT NULL,
79 at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
80 )`,
81 // A reminder marked sent, for the date it was about: moving the date makes
82 // the reminders for the new date unsent again.
83 `CREATE TABLE reminder (
84 id INTEGER PRIMARY KEY,
85 deadline_id INTEGER NOT NULL REFERENCES deadline (id) ON DELETE CASCADE,
86 party_id INTEGER NOT NULL REFERENCES party (id) ON DELETE CASCADE,
87 moment TEXT NOT NULL CHECK (moment IN ('before', 'day_of')),
88 due TEXT NOT NULL,
89 by_name TEXT NOT NULL,
90 sent_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
91 UNIQUE (deadline_id, party_id, moment, due)
92 )`,
93 `CREATE TABLE app_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)`,
4194 ];
4295
4396 export function openDb(dir = dataDir): Database {
@@ -47,6 +100,7 @@ export function openDb(dir = dataDir): Database {
47100 db.exec("PRAGMA foreign_keys = ON");
48101 db.exec("PRAGMA busy_timeout = 5000");
49102 migrate(db);
103 seed(db);
50104 return db;
51105 }
52106
src/deadlines.ts added +148
@@ -0,0 +1,148 @@
1 /**
2 * What a purchase contract's dates are: the standard kinds, who owes each,
3 * who hears about it, and how a contract date and a closing date become a
4 * schedule. Plain data and one pure function, `schedule`; nothing here
5 * reads a database or a clock.
6 */
7
8 import { addBusinessDays, addDays, daysBetween } from "./dates.ts";
9
10 export const PARTY_ROLES = [
11 "buyer",
12 "seller",
13 "lender",
14 "title",
15 "other_agent",
16 ] as const;
17 export type PartyRole = (typeof PARTY_ROLES)[number];
18 export const PARTY_LABEL: Readonly<Record<PartyRole, string>> = {
19 buyer: "Buyer",
20 seller: "Seller",
21 lender: "Lender",
22 title: "Title company",
23 other_agent: "Other agent",
24 };
25 export const isPartyRole = (v: unknown): v is PartyRole =>
26 PARTY_ROLES.includes(v as PartyRole);
27
28 export const KINDS = [
29 "inspection",
30 "appraisal",
31 "financing",
32 "title",
33 "walkthrough",
34 "closing",
35 "custom",
36 ] as const;
37 export type Kind = (typeof KINDS)[number];
38
39 export interface KindInfo {
40 readonly label: string;
41 /** Two or three letters for a marker on the clock. */
42 readonly tag: string;
43 /** Who owes it, by default. */
44 readonly owes: PartyRole;
45 /** What they owe, said to a person. */
46 readonly what: string;
47 /** Who is reminded. */
48 readonly notify: readonly PartyRole[];
49 }
50
51 export const KIND: Readonly<Record<Kind, KindInfo>> = {
52 inspection: {
53 label: "Inspection period ends",
54 tag: "Insp",
55 owes: "buyer",
56 what: "Inspections finished and any objection notice delivered",
57 notify: ["buyer", "seller", "other_agent"],
58 },
59 appraisal: {
60 label: "Appraisal due",
61 tag: "Appr",
62 owes: "lender",
63 what: "Appraisal completed and delivered",
64 notify: ["lender", "buyer", "other_agent"],
65 },
66 financing: {
67 label: "Financing contingency ends",
68 tag: "Fin",
69 owes: "lender",
70 what: "Written loan commitment in hand",
71 notify: ["lender", "buyer", "other_agent"],
72 },
73 title: {
74 label: "Title commitment due",
75 tag: "Title",
76 owes: "title",
77 what: "Title commitment delivered and objections raised",
78 notify: ["title", "buyer", "other_agent"],
79 },
80 walkthrough: {
81 label: "Final walkthrough",
82 tag: "Walk",
83 owes: "buyer",
84 what: "Walk the property and confirm its condition",
85 notify: ["buyer", "seller", "other_agent"],
86 },
87 closing: {
88 label: "Closing",
89 tag: "Close",
90 owes: "title",
91 what: "Sign, fund and record; keys change hands",
92 notify: ["buyer", "seller", "lender", "title", "other_agent"],
93 },
94 custom: {
95 label: "Contract date",
96 tag: "Date",
97 owes: "buyer",
98 what: "As the contract says",
99 notify: ["other_agent"],
100 },
101 };
102
103 /** The contingency lengths a new deal starts from, each editable on the form. */
104 export interface Lengths {
105 readonly inspection: number;
106 readonly appraisal: number;
107 readonly financing: number;
108 readonly title: number;
109 /** Days before closing. */
110 readonly walkthrough: number;
111 }
112 export const DEFAULT_LENGTHS: Lengths = {
113 inspection: 10,
114 appraisal: 21,
115 financing: 30,
116 title: 14,
117 walkthrough: 1,
118 };
119 export const LENGTH_MAX = 180;
120
121 export interface Planned {
122 readonly kind: Kind;
123 readonly due: string;
124 }
125
126 /**
127 * The standard dates of a contract. Contingencies count from the contract
128 * date; the walkthrough counts back from closing. Calendar days unless
129 * `businessDays`, which steps over weekends instead of counting them.
130 */
131 export function schedule(input: {
132 contractDate: string;
133 closingDate: string;
134 lengths: Lengths;
135 businessDays: boolean;
136 }): Planned[] {
137 const { contractDate, closingDate, lengths, businessDays } = input;
138 const add = businessDays ? addBusinessDays : addDays;
139 const planned: Planned[] = [
140 { kind: "inspection", due: add(contractDate, lengths.inspection) },
141 { kind: "appraisal", due: add(contractDate, lengths.appraisal) },
142 { kind: "financing", due: add(contractDate, lengths.financing) },
143 { kind: "title", due: add(contractDate, lengths.title) },
144 { kind: "walkthrough", due: add(closingDate, -lengths.walkthrough) },
145 { kind: "closing", due: closingDate },
146 ];
147 return planned.sort((a, b) => daysBetween(b.due, a.due));
148 }
src/deals.test.ts added +261
@@ -0,0 +1,261 @@
1 /**
2 * Deals through their actions: opening one computes its dates, moving a
3 * date moves nothing else and keeps the reason, mark done, parties and
4 * custom dates, reminders drafted and marked sent — and what `/tick` says.
5 */
6 import { expect, test } from "bun:test";
7 import { mkdtempSync } from "node:fs";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { addDays, today } from "./dates.ts";
11 import {
12 addDeadline,
13 addParty,
14 createDeal,
15 deleteDeal,
16 getDeal,
17 listDeals,
18 markDone,
19 moveDeadline,
20 sendReminder,
21 type DealView,
22 } from "./deals.ts";
23 import { openDb } from "./db.ts";
24 import { calendar, fold, icsText } from "./ics.ts";
25 import { drafts, dueOn, recipients } from "./reminders.ts";
26 import type { Who } from "./who.ts";
27
28 const db = openDb(mkdtempSync(join(tmpdir(), "app-deals-")));
29 const anon: Who = { role: "anon" };
30 const alice: Who = { role: "user", id: "u1", name: "alice" };
31 const bob: Who = { role: "user", id: "u2", name: "bob" };
32 const agent = { name: "Dana Whitfield", brokerage: "Harbor & Pine Realty" };
33
34 const open = (over: Record<string, unknown> = {}): DealView => {
35 const made = createDeal(db, alice, {
36 address: "12 Elm St",
37 buyer: "Ann Buyer",
38 seller: "Sam Seller",
39 contractDate: "2026-10-01",
40 closingDate: "2026-11-06",
41 ...over,
42 });
43 if (!made.ok) throw new Error(made.message);
44 return made.value;
45 };
46 const due = (deal: DealView, kind: string) =>
47 deal.deadlines.find((d) => d.kind === kind)!;
48 const fresh = (id: number): DealView => {
49 const got = getDeal(db, bob, { id });
50 if (!got.ok) throw new Error(got.message);
51 return got.value;
52 };
53
54 test("a new database carries four sample deals: one overdue, one closing this week", () => {
55 const all = listDeals(db, bob);
56 if (!all.ok) throw new Error(all.message);
57 const samples = all.value.filter((d) => d.author_id === "sample");
58 expect(samples.length).toBe(4);
59 const on = today();
60 expect(
61 samples.some((d) => d.deadlines.some((x) => x.done_at === null && x.due < on)),
62 ).toBe(true);
63 expect(samples.some((d) => d.closing >= on && d.closing <= addDays(on, 7))).toBe(true);
64 });
65
66 test("opening a deal computes its dates, with the buyer and seller as parties", () => {
67 const deal = open();
68 expect(deal.author_name).toBe("alice");
69 expect(Object.fromEntries(deal.deadlines.map((d) => [d.kind, d.due]))).toEqual({
70 inspection: "2026-10-11",
71 title: "2026-10-15",
72 appraisal: "2026-10-22",
73 financing: "2026-10-31",
74 walkthrough: "2026-11-05",
75 closing: "2026-11-06",
76 });
77 expect(deal.closing).toBe("2026-11-06");
78 expect(deal.parties.map((p) => [p.role, p.name])).toEqual([
79 ["buyer", "Ann Buyer"],
80 ["seller", "Sam Seller"],
81 ]);
82 const custom = open({ lengths: { inspection: "7" }, businessDays: "on" });
83 expect(due(custom, "inspection").due).toBe("2026-10-12"); // 7 weekdays from a Thursday
84 expect(custom.business_days).toBe(1);
85 });
86
87 test("a deal's facts are checked at the boundary", () => {
88 for (const bad of [
89 { address: "x" },
90 { buyer: "" },
91 { contractDate: "2026-02-30" },
92 { closingDate: "2026-09-01" },
93 { lengths: { financing: "-1" } },
94 { lengths: { appraisal: "2.5" } },
95 ]) {
96 const r = createDeal(db, alice, {
97 address: "12 Elm St",
98 buyer: "Ann",
99 seller: "Sam",
100 contractDate: "2026-10-01",
101 closingDate: "2026-11-06",
102 ...bad,
103 });
104 expect([bad, r.ok ? "ok" : r.error]).toEqual([bad, "invalid"]);
105 }
106 const refused = createDeal(db, anon, {
107 address: "12 Elm St",
108 buyer: "Ann",
109 seller: "Sam",
110 contractDate: "2026-10-01",
111 closingDate: "2026-11-06",
112 });
113 expect(refused.ok ? "ok" : refused.error).toBe("signin_required");
114 });
115
116 test("moving a date moves nothing else, and keeps the reason", () => {
117 const deal = open();
118 const before = deal.deadlines.map((d) => [d.id, d.due] as const);
119 const appraisal = due(deal, "appraisal");
120 const moved = moveDeadline(db, bob, {
121 id: appraisal.id,
122 due: "2026-10-27",
123 reason: "Appraiser out sick",
124 });
125 expect(moved.ok).toBe(true);
126 const after = fresh(deal.id);
127 expect(after.deadlines.map((d) => [d.id, d.due]).sort()).toEqual(
128 before.map(([id, d]) => [id, id === appraisal.id ? "2026-10-27" : d]).sort(),
129 );
130 expect(due(after, "appraisal").moves.map((m) => [m.from_due, m.to_due, m.reason, m.by_name])).toEqual([
131 ["2026-10-22", "2026-10-27", "Appraiser out sick", "bob"],
132 ]);
133 // Moving closing moves the deal's closing, and still nothing else.
134 const closing = due(after, "closing");
135 expect(moveDeadline(db, alice, { id: closing.id, due: "2026-11-13", reason: "Buyer's request" }).ok).toBe(true);
136 const later = fresh(deal.id);
137 expect(later.closing).toBe("2026-11-13");
138 expect(due(later, "walkthrough").due).toBe("2026-11-05");
139 });
140
141 test("a move needs a real date and a reason, from someone signed in", () => {
142 const deal = open();
143 const id = due(deal, "financing").id;
144 const tries = [
145 moveDeadline(db, alice, { id, due: "soon", reason: "x" }),
146 moveDeadline(db, alice, { id, due: "2026-11-02", reason: " " }),
147 moveDeadline(db, alice, { id, due: due(deal, "financing").due, reason: "same" }),
148 moveDeadline(db, anon, { id, due: "2026-11-02", reason: "x" }),
149 moveDeadline(db, alice, { id: 999_999, due: "2026-11-02", reason: "x" }),
150 ];
151 expect(tries.map((r) => (r.ok ? "ok" : r.error))).toEqual([
152 "invalid",
153 "invalid",
154 "invalid",
155 "signin_required",
156 "not_found",
157 ]);
158 expect(fresh(deal.id).deadlines.every((d) => d.moves.length === 0)).toBe(true);
159 });
160
161 test("mark done, and reopen", () => {
162 const deal = open();
163 const id = due(deal, "inspection").id;
164 const done = markDone(db, bob, { id, done: true });
165 expect(done.ok && done.value.done_at !== null).toBe(true);
166 expect(drafts(fresh(deal.id), agent).some((r) => r.deadline_id === id)).toBe(false);
167 const reopened = markDone(db, bob, { id, done: false });
168 expect(reopened.ok && reopened.value.done_at).toBeNull();
169 expect(markDone(db, anon, { id, done: true }).ok).toBe(false);
170 });
171
172 test("a party and a custom date join the deal; reminders follow who is on it", () => {
173 const deal = open();
174 const inspection = due(deal, "inspection");
175 expect(recipients(deal, inspection).map((p) => p.role)).toEqual(["buyer", "seller"]);
176 const agentParty = addParty(db, alice, { dealId: deal.id, role: "other_agent", name: "Jo Ellis", contact: "[email protected]" });
177 expect(agentParty.ok).toBe(true);
178 expect(addParty(db, alice, { dealId: deal.id, role: "plumber", name: "X" }).ok).toBe(false);
179 const hoa = addDeadline(db, alice, { dealId: deal.id, label: "HOA review ends", due: "2026-10-09", owes: "buyer", what: "Read the HOA docs" });
180 expect(hoa.ok && hoa.value.kind).toBe("custom");
181 expect(addDeadline(db, alice, { dealId: deal.id, label: "", due: "2026-10-09", owes: "buyer" }).ok).toBe(false);
182 const now = fresh(deal.id);
183 expect(recipients(now, due(now, "inspection")).map((p) => p.role)).toEqual(["buyer", "seller", "other_agent"]);
184 expect(now.deadlines.some((d) => d.label === "HOA review ends")).toBe(true);
185 });
186
187 test("reminders: three days before and the morning of, drafted in words, marked sent once", () => {
188 const deal = open({ contractDate: addDays(today(), -5), closingDate: addDays(today(), 30), lengths: { inspection: "8" } });
189 const inspection = due(deal, "inspection"); // due in three days
190 const mine = drafts(deal, agent).filter((r) => r.deadline_id === inspection.id);
191 expect(mine.map((r) => [r.party_name, r.moment, r.on])).toEqual([
192 ["Ann Buyer", "before", today()],
193 ["Sam Seller", "before", today()],
194 ["Ann Buyer", "day_of", inspection.due],
195 ["Sam Seller", "day_of", inspection.due],
196 ]);
197 const buyer = mine[0]!;
198 expect(buyer.body).toContain("Hi Ann,");
199 expect(buyer.body).toContain("in three days");
200 expect(buyer.body).toContain("This one is yours");
201 expect(buyer.body).toContain("Dana Whitfield, Harbor & Pine Realty");
202 expect(mine[1]!.body).toContain("Ann Buyer (buyer) is on it");
203
204 const tick = () => dueOn([fresh(deal.id)], today(), agent).filter((r) => r.deadline_id === inspection.id);
205 expect(tick().length).toBe(2);
206 const sent = sendReminder(db, alice, { deadlineId: inspection.id, partyId: buyer.party_id, moment: "before" });
207 expect(sent.ok).toBe(true);
208 // Sending twice is still one send.
209 expect(sendReminder(db, alice, { deadlineId: inspection.id, partyId: buyer.party_id, moment: "before" }).ok).toBe(true);
210 expect(fresh(deal.id).sent.length).toBe(1);
211 expect(tick().map((r) => r.party_name)).toEqual(["Sam Seller"]);
212 expect(sendReminder(db, alice, { deadlineId: inspection.id, partyId: buyer.party_id, moment: "later" }).ok).toBe(false);
213 expect(sendReminder(db, anon, { deadlineId: inspection.id, partyId: buyer.party_id, moment: "before" }).ok).toBe(false);
214 // A party on another deal is not this deal's to remind.
215 const other = open();
216 expect(sendReminder(db, alice, { deadlineId: inspection.id, partyId: other.parties[0]!.id, moment: "before" }).ok).toBe(false);
217 // A moved date's reminders are unsent again.
218 moveDeadline(db, alice, { id: inspection.id, due: addDays(inspection.due, 2), reason: "Extension signed" });
219 const moved = drafts(fresh(deal.id), agent).filter((r) => r.deadline_id === inspection.id);
220 expect(moved.every((r) => r.sent_at === null)).toBe(true);
221 });
222
223 test("only the agent who opened a deal, or an admin, removes it", () => {
224 const deal = open();
225 expect(deleteDeal(db, bob, { id: deal.id }).ok).toBe(false);
226 expect(deleteDeal(db, { role: "admin", id: "u0", name: "root" }, { id: deal.id }).ok).toBe(true);
227 expect(getDeal(db, anon, { id: deal.id }).ok).toBe(false);
228 });
229
230 test("the calendar file: one all-day event per date, alarms, escaped and folded", () => {
231 const deal = open({ address: "4 Comma, Semi; Lane" });
232 const ics = calendar(deal, "clock.example", new Date("2026-10-12T08:00:00Z"));
233 expect(ics.startsWith("BEGIN:VCALENDAR\r\n")).toBe(true);
234 expect(ics.endsWith("END:VCALENDAR\r\n")).toBe(true);
235 expect(ics.split("BEGIN:VEVENT").length - 1).toBe(6);
236 expect(ics).toContain("DTSTART;VALUE=DATE:20261011\r\nDTEND;VALUE=DATE:20261012");
237 expect(ics).toContain("UID:deadline-");
238 expect(ics).toContain("TRIGGER:-P3D");
239 expect(ics).toContain("4 Comma\\, Semi\\; Lane");
240 for (const line of ics.split("\r\n")) expect(new TextEncoder().encode(line).length).toBeLessThanOrEqual(75);
241 expect(icsText("a\\b\nc")).toBe("a\\\\b\\nc");
242 expect(fold("x".repeat(80))).toBe(`${"x".repeat(75)}\r\n ${"x".repeat(5)}`);
243 });
244
245 test("deals are for signed-in agents: a guest sees none, and no contacts", () => {
246 const deal = open();
247 addParty(db, alice, { dealId: deal.id, role: "lender", name: "Lee Lender", contact: "[email protected]" });
248 const read = getDeal(db, anon, { id: deal.id });
249 expect(read.ok ? "ok" : read.error).toBe("signin_required");
250 const listed = listDeals(db, anon);
251 expect(listed.ok ? "ok" : listed.error).toBe("signin_required");
252 const mine = getDeal(db, bob, { id: deal.id });
253 if (!mine.ok) throw new Error(mine.message);
254 expect(mine.value.parties.map((p) => p.contact)).toContain("[email protected]");
255 expect(drafts(mine.value, agent).some((r) => r.contact === "[email protected]")).toBe(true);
256 });
257
258 test("a field keeps no control characters, C1 included", () => {
259 const deal = open({ address: "7 Oak\u009b31m Lane\u0007\u0085" });
260 expect(deal.address).toBe("7 Oak 31m Lane");
261 });
src/deals.ts added +507
@@ -0,0 +1,507 @@
1 /**
2 * Deals: every operation on a deal, its dates and its parties, as plain
3 * functions — `(db, who, input)` in, data or a named failure out, like
4 * `actions.ts`. Every door (page, API, MCP, terminal) calls these. Each asks
5 * `permit` about the `deal` resource; a change to a deal's dates, parties
6 * or reminders is an `update` of that deal, and is audited as one.
7 */
8
9 import type { Database } from "bun:sqlite";
10 import { permit } from "./contract.ts";
11 import { isDate } from "./dates.ts";
12 import {
13 DEFAULT_LENGTHS,
14 isPartyRole,
15 KIND,
16 LENGTH_MAX,
17 schedule,
18 type Kind,
19 type Lengths,
20 type PartyRole,
21 } from "./deadlines.ts";
22 import { emit } from "./live.ts";
23 import { audited, fail, ok, refuse, type Result } from "./result.ts";
24 import type { Who } from "./who.ts";
25
26 export interface Deal {
27 readonly id: number;
28 readonly address: string;
29 readonly contract_date: string;
30 readonly business_days: 0 | 1;
31 readonly author_id: string;
32 readonly author_name: string;
33 readonly created_at: string;
34 }
35 export interface Party {
36 readonly id: number;
37 readonly deal_id: number;
38 readonly role: PartyRole;
39 readonly name: string;
40 readonly contact: string;
41 }
42 export interface Move {
43 readonly id: number;
44 readonly deadline_id: number;
45 readonly from_due: string;
46 readonly to_due: string;
47 readonly reason: string;
48 readonly by_name: string;
49 readonly at: string;
50 }
51 export interface Sent {
52 readonly id: number;
53 readonly deadline_id: number;
54 readonly party_id: number;
55 readonly moment: Moment;
56 readonly due: string;
57 readonly by_name: string;
58 readonly sent_at: string;
59 }
60 export interface Deadline {
61 readonly id: number;
62 readonly deal_id: number;
63 readonly kind: Kind;
64 readonly label: string;
65 readonly due: string;
66 readonly owes: PartyRole;
67 readonly what: string;
68 readonly done_at: string | null;
69 }
70 export interface DeadlineView extends Deadline {
71 readonly moves: readonly Move[];
72 }
73 /** A deal with everything hanging off it: what every page and door shows. */
74 export interface DealView extends Deal {
75 /** The `closing` deadline's date, wherever it has moved. */
76 readonly closing: string;
77 readonly parties: readonly Party[];
78 readonly deadlines: readonly DeadlineView[];
79 readonly sent: readonly Sent[];
80 }
81
82 export type Moment = "before" | "day_of";
83 export const isMoment = (v: unknown): v is Moment =>
84 v === "before" || v === "day_of";
85
86 /** Text from a person: trimmed, one line, within bounds — or undefined. */
87 export function line(value: unknown, min: number, max: number): string | undefined {
88 if (typeof value !== "string") return undefined;
89 // Control characters (C0, DEL and C1) have no place in a field: they would
90 // reach a calendar file, or a terminal as an escape sequence.
outdated

Low: C1 controls (U+0080–U+009F, e.g. CSI U+009B) get through and are written raw by src/terminal.ts. /[\u0000-\u001f\u007f-\u009f]+/g closes it.

91 const text = value.replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ").replace(/\s+/g, " ").trim();
92 return text.length >= min && text.length <= max ? text : undefined;
93 }
94
95 /** The name a row is written under: the person, as the forge signed them. */
96 const authorOf = (who: Who): { id: string; name: string } =>
97 who.role === "anon" ? { id: "", name: "" } : { id: who.id, name: who.name };
98
99 /**
100 * A deal as `who` may see it. Parties' emails and phones are for whoever
101 * may work the deal; anyone who may only read it sees names, not contacts.
102 * With today's table (read and update both `user`) everyone who reads may
103 * work, so nothing is blanked; it holds the moment update narrows (to
104 * `author`, say) without read narrowing with it.
105 */
106 const shown = (who: Who, deal: DealView): DealView =>

Low: under today's table (read and update are both user), the contact-blanking branch never runs, so no test covers it. Either add a test that feeds shown a who/deal pair permit refuses update for, or drop the branch until the table needs it.

107 canChange(who, deal)
108 ? deal
109 : { ...deal, parties: deal.parties.map((p) => ({ ...p, contact: "" })) };
110
111 // ---- reading ----
112
113 function view(db: Database, deal: Deal): DealView {
114 const deadlines = db
115 .query<Deadline, [number]>(
116 "SELECT * FROM deadline WHERE deal_id = ?1 ORDER BY due, id",
117 )
118 .all(deal.id);
119 const moves = db
120 .query<Move, [number]>(
121 "SELECT m.* FROM deadline_move m JOIN deadline d ON d.id = m.deadline_id WHERE d.deal_id = ?1 ORDER BY m.id",
122 )
123 .all(deal.id);
124 return {
125 ...deal,
126 closing:
127 deadlines.find((d) => d.kind === "closing")?.due ?? deal.contract_date,
128 parties: db
129 .query<Party, [number]>(
130 "SELECT * FROM party WHERE deal_id = ?1 ORDER BY id",
131 )
132 .all(deal.id),
133 deadlines: deadlines.map((d) => ({
134 ...d,
135 moves: moves.filter((m) => m.deadline_id === d.id),
136 })),
137 sent: db
138 .query<Sent, [number]>(
139 "SELECT r.* FROM reminder r JOIN deadline d ON d.id = r.deadline_id WHERE d.deal_id = ?1 ORDER BY r.id",
140 )
141 .all(deal.id),
142 };
143 }
144
145 export function listDeals(db: Database, who: Who): Result<DealView[]> {
146 const may = permit(who, "deal", "list");
147 if (may === "no")
148 return refuse(who, "Sign in to see deals.", "You may not see these deals.");
149 const deals =
150 may === "yes"
151 ? db.query<Deal, []>("SELECT * FROM deal").all()
152 : db
153 .query<Deal, [string]>(
154 `SELECT * FROM deal WHERE ${may.where.map((c) => `${c} = ?1`).join(" OR ")}`,
155 )
156 .all(who.role === "anon" ? "" : who.id);
157 return ok(
158 deals
159 .map((d) => shown(who, view(db, d)))
160 .sort((a, b) => a.closing.localeCompare(b.closing) || a.id - b.id),
161 );
162 }
163
164 /**
165 * One deal, for `who` to do `verb` to. The table is asked before the row is
166 * looked for, so whoever may not learns nothing about what exists.
167 */
168 function dealFor(
169 db: Database,
170 who: Who,
171 verb: "read" | "update" | "delete",
172 id: number,
173 ): Result<Deal> {
174 const deal = Number.isInteger(id)
175 ? db.query<Deal, [number]>("SELECT * FROM deal WHERE id = ?1").get(id)
176 : null;
177 const row: Readonly<Record<string, unknown>> =
178 deal === null
179 ? { author_id: who.role === "anon" ? null : who.id }
180 : { ...deal };
181 if (permit(who, "deal", verb, row) !== "yes")
182 return verb === "read"
183 ? refuse(who, "Sign in to see this deal.", "You may not see this deal.")
184 : refuse(
185 who,
186 "Sign in to change this deal.",
187 verb === "delete"
188 ? "Only the agent who opened a deal, or an admin, can remove it."
189 : "You may not change this deal.",
190 );
191 if (deal !== null) return ok(deal);
192 if (!Number.isInteger(id)) return fail("invalid", "A deal id is a whole number.");
193 return fail("not_found", "No such deal.");
194 }
195
196 export function getDeal(
197 db: Database,
198 who: Who,
199 input: { id: number },
200 ): Result<DealView> {
201 const found = dealFor(db, who, "read", input.id);
202 return found.ok ? ok(shown(who, view(db, found.value))) : found;
203 }
204
205 /** Whether `who` may change `deal`: the table's answer, for a page to draw its controls from. */
206 export const canChange = (who: Who, deal: Deal): boolean =>
207 permit(who, "deal", "update", { ...deal }) === "yes";
208 export const canRemove = (who: Who, deal: Deal): boolean =>
209 permit(who, "deal", "delete", { ...deal }) === "yes";
210
211 // ---- opening a deal ----
212
213 export interface NewDeal {
214 readonly address: unknown;
215 readonly buyer: unknown;
216 readonly seller: unknown;
217 readonly contractDate: unknown;
218 readonly closingDate: unknown;
219 readonly lengths?: Partial<Record<keyof Lengths, unknown>>;
220 readonly businessDays?: unknown;
221 }
222
223 /** A deal's facts, checked, ready to write. */
224 export interface Plan {
225 readonly address: string;
226 readonly buyer: string;
227 readonly seller: string;
228 readonly contractDate: string;
229 readonly closingDate: string;
230 readonly lengths: Lengths;
231 readonly businessDays: boolean;
232 }
233
234 export function plan(input: NewDeal): Result<Plan> {
235 const address = line(input.address, 3, 200);
236 if (address === undefined)
237 return fail("invalid", "The address is 3 to 200 characters.");
238 const buyer = line(input.buyer, 1, 100);
239 const seller = line(input.seller, 1, 100);
240 if (buyer === undefined || seller === undefined)
241 return fail("invalid", "Name the buyer and the seller (up to 100 characters each).");
242 const { contractDate, closingDate } = input;
243 if (!isDate(contractDate) || !isDate(closingDate))
244 return fail("invalid", "The contract and closing dates are dates (YYYY-MM-DD).");
245 if (closingDate <= contractDate)
246 return fail("invalid", "Closing comes after the contract date.");
247 const lengths = { ...DEFAULT_LENGTHS };
248 for (const key of Object.keys(DEFAULT_LENGTHS) as (keyof Lengths)[]) {
249 const raw = input.lengths?.[key];
250 if (raw === undefined || raw === "") continue;
251 const n = Number(raw);
252 if (!Number.isInteger(n) || n < 0 || n > LENGTH_MAX)
253 return fail("invalid", `The ${key} length is a whole number of days, 0 to ${LENGTH_MAX}.`);
254 lengths[key] = n;
255 }
256 const businessDays =
257 input.businessDays === true || input.businessDays === "on" || input.businessDays === "1";
258 return ok({ address, buyer, seller, contractDate, closingDate, lengths, businessDays });
259 }
260
261 /** Write a planned deal: the deal, its buyer and seller, and the standard dates. */
262 export function insertDeal(
263 db: Database,
264 author: { id: string; name: string },
265 p: Plan,
266 ): Deal {
267 return db.transaction(() => {
268 const deal = db
269 .query<Deal, [string, string, number, string, string]>(
270 "INSERT INTO deal (address, contract_date, business_days, author_id, author_name) VALUES (?1, ?2, ?3, ?4, ?5) RETURNING *",
271 )
272 .get(p.address, p.contractDate, p.businessDays ? 1 : 0, author.id, author.name)!;
273 const party = db.query(
274 "INSERT INTO party (deal_id, role, name) VALUES (?1, ?2, ?3)",
275 );
276 party.run(deal.id, "buyer", p.buyer);
277 party.run(deal.id, "seller", p.seller);
278 const deadline = db.query(
279 "INSERT INTO deadline (deal_id, kind, label, due, owes, what) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
280 );
outdated

Low: a hand role check in an action. permit(who, "deal", "create") already refuses anon, so drop who.role === "anon" ||.

281 for (const { kind, due } of schedule(p)) {
282 const k = KIND[kind];
283 deadline.run(deal.id, kind, k.label, due, k.owes, k.what);
284 }
285 return deal;
286 })();
287 }
288
289 /**
290 * Whether `who` may open a deal: the table's answer, worded as `createDeal`
291 * would refuse — for a door to ask before it has a person type five answers.
292 */
293 export const mayOpen = (who: Who): Result<null> =>
294 permit(who, "deal", "create") === "yes"
295 ? ok(null)
296 : refuse(who, "Sign in to open a deal.", "You may not open a deal.");
297
298 export const createDeal = (
299 db: Database,
300 who: Who,
301 input: NewDeal,
302 ): Result<DealView> =>
303 audited(db, who, "deal", "create", undefined, create(db, who, input));
304
305 function create(db: Database, who: Who, input: NewDeal): Result<DealView> {
306 const may = mayOpen(who);
307 if (!may.ok) return may;
308 const planned = plan(input);
309 if (!planned.ok) return planned;
310 const deal = view(db, insertDeal(db, authorOf(who), planned.value));
311 emit("deal.changed", { id: deal.id });
312 return ok(deal);
313 }
314
315 export const updateDeal = (
316 db: Database,
317 who: Who,
318 input: { id: number; address: unknown },
319 ): Result<DealView> =>
320 audited(db, who, "deal", "update", input.id, update(db, who, input));
321
322 function update(
323 db: Database,
324 who: Who,
325 input: { id: number; address: unknown },
326 ): Result<DealView> {
327 const found = dealFor(db, who, "update", input.id);
328 if (!found.ok) return found;
329 const address = line(input.address, 3, 200);
330 if (address === undefined)
331 return fail("invalid", "The address is 3 to 200 characters.");
332 db.query("UPDATE deal SET address = ?1 WHERE id = ?2").run(address, found.value.id);
333 emit("deal.changed", { id: found.value.id });
334 return ok(view(db, { ...found.value, address }));
335 }
336
337 export const deleteDeal = (
338 db: Database,
339 who: Who,
340 input: { id: number },
341 ): Result<{ id: number }> =>
342 audited(db, who, "deal", "delete", input.id, remove(db, who, input));
343
344 function remove(db: Database, who: Who, input: { id: number }): Result<{ id: number }> {
345 const found = dealFor(db, who, "delete", input.id);
346 if (!found.ok) return found;
347 db.query("DELETE FROM deal WHERE id = ?1").run(found.value.id);
348 emit("deal.changed", { id: found.value.id });
349 return ok({ id: found.value.id });
350 }
351
352 // ---- a deal's dates, parties and reminders: each an update of the deal ----
353
354 /** A change inside deal `dealId`, audited as an update of that deal. */
355 function within<T extends { readonly id: number }>(
356 db: Database,
357 who: Who,
358 dealId: number | undefined,
359 result: Result<T>,
360 ): Result<T> {
361 const out = audited(db, who, "deal", "update", dealId, result);
362 if (out.ok && dealId !== undefined) emit("deal.changed", { id: dealId });
363 return out;
364 }
365
366 /** The deadline and its deal, when `who` may change the deal. */
367 function deadlineFor(
368 db: Database,
369 who: Who,
370 id: number,
371 ): { dealId?: number; found: Result<{ deal: Deal; deadline: Deadline }> } {
372 const deadline = Number.isInteger(id)
373 ? db.query<Deadline, [number]>("SELECT * FROM deadline WHERE id = ?1").get(id)
374 : null;
375 const deal = dealFor(db, who, "update", deadline?.deal_id ?? Number.NaN);
376 if (!deal.ok && (deal.error === "signin_required" || deal.error === "forbidden"))
377 return { found: deal };
378 if (deadline === null || !deal.ok)
379 return {
380 found: Number.isInteger(id)
381 ? fail("not_found", "No such date.")
382 : fail("invalid", "A date id is a whole number."),
383 };
384 return { dealId: deal.value.id, found: ok({ deal: deal.value, deadline }) };
385 }
386
387 const reread = (db: Database, id: number): Deadline =>
388 db.query<Deadline, [number]>("SELECT * FROM deadline WHERE id = ?1").get(id)!;
389
390 export function markDone(
391 db: Database,
392 who: Who,
393 input: { id: number; done: boolean },
394 ): Result<Deadline> {
395 const { dealId, found } = deadlineFor(db, who, input.id);
396 if (!found.ok) return within(db, who, dealId, found);
397 db.query(
398 "UPDATE deadline SET done_at = ?1 WHERE id = ?2",
399 ).run(input.done ? new Date().toISOString() : null, input.id);
400 return within(db, who, dealId, ok(reread(db, input.id)));
401 }
402
403 /** Move one date, and only that one; the reason is kept beside it. */
404 export function moveDeadline(
405 db: Database,
406 who: Who,
407 input: { id: number; due: unknown; reason: unknown },
408 ): Result<Deadline> {
409 const { dealId, found } = deadlineFor(db, who, input.id);
410 if (!found.ok) return within(db, who, dealId, found);
411 if (!isDate(input.due))
412 return within(db, who, dealId, fail("invalid", "The new date is a date (YYYY-MM-DD)."));
413 const reason = line(input.reason, 1, 200);
414 if (reason === undefined)
415 return within(db, who, dealId, fail("invalid", "Say why the date moved (up to 200 characters)."));
416 const { deadline } = found.value;
417 if (input.due === deadline.due)
418 return within(db, who, dealId, fail("invalid", "That is already its date."));
419 db.transaction(() => {
420 db.query("UPDATE deadline SET due = ?1 WHERE id = ?2").run(input.due as string, deadline.id);
421 db.query(
422 "INSERT INTO deadline_move (deadline_id, from_due, to_due, reason, by_name) VALUES (?1, ?2, ?3, ?4, ?5)",
423 ).run(deadline.id, deadline.due, input.due as string, reason, authorOf(who).name);
424 })();
425 return within(db, who, dealId, ok(reread(db, deadline.id)));
426 }
427
428 export function addDeadline(
429 db: Database,
430 who: Who,
431 input: { dealId: number; label: unknown; due: unknown; owes: unknown; what?: unknown },
432 ): Result<Deadline> {
433 const deal = dealFor(db, who, "update", input.dealId);
434 const dealId = deal.ok ? deal.value.id : undefined;
435 if (!deal.ok) return within(db, who, Number.isInteger(input.dealId) ? input.dealId : undefined, deal);
436 const label = line(input.label, 1, 100);
437 if (label === undefined)
438 return within(db, who, dealId, fail("invalid", "Name the date (up to 100 characters)."));
439 if (!isDate(input.due))
440 return within(db, who, dealId, fail("invalid", "The date is a date (YYYY-MM-DD)."));
441 if (!isPartyRole(input.owes))
442 return within(db, who, dealId, fail("invalid", "Say which party owes it."));
443 const what = input.what === undefined || input.what === "" ? "" : line(input.what, 1, 200);
444 if (what === undefined)
445 return within(db, who, dealId, fail("invalid", "What is owed is up to 200 characters."));
446 const made = db
447 .query<Deadline, [number, string, string, string, string]>(
448 "INSERT INTO deadline (deal_id, kind, label, due, owes, what) VALUES (?1, 'custom', ?2, ?3, ?4, ?5) RETURNING *",
449 )
450 .get(deal.value.id, label, input.due, input.owes, what)!;
451 return within(db, who, dealId, ok(made));
452 }
453
454 export function addParty(
455 db: Database,
456 who: Who,
457 input: { dealId: number; role: unknown; name: unknown; contact?: unknown },
458 ): Result<Party> {
459 const deal = dealFor(db, who, "update", input.dealId);
460 const dealId = deal.ok ? deal.value.id : undefined;
461 if (!deal.ok) return within(db, who, Number.isInteger(input.dealId) ? input.dealId : undefined, deal);
462 if (!isPartyRole(input.role))
463 return within(db, who, dealId, fail("invalid", "A party is a buyer, seller, lender, title company or the other agent."));
464 const name = line(input.name, 1, 100);
465 if (name === undefined)
466 return within(db, who, dealId, fail("invalid", "A name is 1 to 100 characters."));
467 const contact =
468 input.contact === undefined || input.contact === "" ? "" : line(input.contact, 1, 120);
469 if (contact === undefined)
470 return within(db, who, dealId, fail("invalid", "A contact is up to 120 characters."));
471 const made = db
472 .query<Party, [number, string, string, string]>(
473 "INSERT INTO party (deal_id, role, name, contact) VALUES (?1, ?2, ?3, ?4) RETURNING *",
474 )
475 .get(deal.value.id, input.role, name, contact)!;
476 return within(db, who, dealId, ok(made));
477 }
478
479 /**
480 * Mark a reminder sent. The prototype sends nothing: the draft is shown, and
481 * this records that the agent sent it, to that party, about that date.
482 */
483 export function sendReminder(
484 db: Database,
485 who: Who,
486 input: { deadlineId: number; partyId: number; moment: unknown },
487 ): Result<Sent> {
488 const { dealId, found } = deadlineFor(db, who, input.deadlineId);
489 if (!found.ok) return within(db, who, dealId, found);
490 if (!isMoment(input.moment))
491 return within(db, who, dealId, fail("invalid", "A reminder is for three days before, or the day of."));
492 const party = Number.isInteger(input.partyId)
493 ? db
494 .query<Party, [number, number]>("SELECT * FROM party WHERE id = ?1 AND deal_id = ?2")
495 .get(input.partyId, found.value.deal.id)
496 : null;
497 if (party === null)
498 return within(db, who, dealId, fail("not_found", "No such party on this deal."));
499 const { deadline } = found.value;
500 const sent = db
501 .query<Sent, [number, number, string, string, string]>(
502 `INSERT INTO reminder (deadline_id, party_id, moment, due, by_name) VALUES (?1, ?2, ?3, ?4, ?5)
503 ON CONFLICT (deadline_id, party_id, moment, due) DO UPDATE SET sent_at = sent_at RETURNING *`,
504 )
505 .get(deadline.id, party.id, input.moment, deadline.due, authorOf(who).name)!;
506 return within(db, who, dealId, ok(sent));
507 }
src/design.test.ts +8
@@ -70,6 +70,14 @@ test("every pair a person reads is at least 4.5:1, in both themes", () => {
7070 ["color-accent", "color-surface"],
7171 ["color-accent-fg", "color-accent"],
7272 ["color-toast-fg", "color-toast-bg"],
73 ["color-fg", "color-lane"],
74 ["color-muted", "color-lane"],
75 ["color-soon", "color-soon-bg"],
76 ["color-soon", "color-surface"],
77 ["color-overdue", "color-overdue-bg"],
78 ["color-overdue", "color-surface"],
79 ["color-accent", "color-later-bg"],
80 ["color-fg", "color-done-bg"],
7381 ] as const;
7482 for (const mode of ["light", "dark"] as const)
7583 for (const [fg, bg] of pairs) {
src/env.ts +5
@@ -30,3 +30,8 @@ export const publicOrigin: string = new URL(
3030 export const forgeUrl: string | undefined = process.env.FORGE_URL;
3131 /** The key the forge signs identities with (`who.ts`). Unset, everyone is anonymous. */
3232 export const identityKey: string = process.env.FORGE_APP_IDENTITY_KEY ?? "";
33 /** Whose deals these are: the agent and brokerage the header and every reminder name. */
34 export const agent = {
35 name: process.env.DEAL_CLOCK_AGENT || "Dana Whitfield",
36 brokerage: process.env.DEAL_CLOCK_BROKERAGE || "Harbor & Pine Realty",
37 } as const;
src/http.ts +23 −10
@@ -61,12 +61,12 @@ export const text = (body: string, status = 200): Response =>
6161 headers: { "content-type": "text/plain; charset=utf-8", ...SECURITY },
6262 });
6363
64 /** Back to the page, with a word for it to show once (`readNotice`). */
65 export const back = (notice?: string): Response =>
64 /** Back to a page (the clock, unless said), with a word for it to show once (`readNotice`). */
65 export const back = (notice?: string, to = "/"): Response =>
6666 new Response(null, {
6767 status: 303,
6868 headers: {
69 location: "/",
69 location: to,
7070 ...SECURITY,
7171 ...(notice === undefined
7272 ? {}
@@ -134,15 +134,28 @@ export async function readBody(
134134 return body;
135135 }
136136
137 /** The form fields of a capped body, decoded the way the browser sent them. */
138 export async function readForm(request: Request) {
137 /** Does the request say it carries a form, the way a browser sends one? */
138 export const isForm = (request: Request): boolean =>
139 /^(?:application\/x-www-form-urlencoded|multipart\/form-data)\b/i.test(
140 request.headers.get("content-type") ?? "",
141 );
142
143 /**
144 * The form fields of a capped body, decoded the way the browser sent them:
145 * `undefined` when too large, `null` when it is not a form that decodes.
146 */
147 export async function readForm(request: Request): Promise<FormData | null | undefined> {
139148 const body = await readBody(request);
140149 if (body === undefined) return undefined;
141 return new Request(request.url, {
142 method: "POST",
143 headers: { "content-type": request.headers.get("content-type") ?? "" },
144 body: new Uint8Array(body),
145 }).formData();
150 try {
151 return await new Request(request.url, {
152 method: "POST",
153 headers: { "content-type": request.headers.get("content-type") ?? "" },
154 body: new Uint8Array(body),
155 }).formData();
156 } catch {
157 return null;
158 }
146159 }
147160
148161 /** The JSON of a capped body: `undefined` when too large, `null` when not JSON. */
src/ics.ts added +79
@@ -0,0 +1,79 @@
1 /**
2 * A deal's dates as a calendar file (RFC 5545): one all-day event per date,
3 * each with two alarms — three days before, and 9 a.m. the day of — so the
4 * agent's own calendar keeps the clock too. Pure text out.
5 */
6
7 import { addDays } from "./dates.ts";
8 import { PARTY_LABEL } from "./deadlines.ts";
9 import type { DealView } from "./deals.ts";
10
11 /** Text as a property value: backslash, semicolon, comma and newline escaped. */
12 export const icsText = (s: string): string =>
13 s.replace(/\\/g, "\\\\").replace(/;/g, "\\;").replace(/,/g, "\\,").replace(/\r?\n/g, "\\n");
14
15 /** A content line folded at 75 octets, as the format asks. */
16 export function fold(line: string): string {
17 const bytes = new TextEncoder().encode(line);
18 if (bytes.length <= 75) return line;
19 const out: string[] = [];
20 let part = "";
21 let size = 0;
22 for (const ch of line) {
23 const n = new TextEncoder().encode(ch).length;
24 if (size + n > (out.length === 0 ? 75 : 74)) {
25 out.push(part);
26 part = "";
27 size = 0;
28 }
29 part += ch;
30 size += n;
31 }
32 out.push(part);
33 return out.join("\r\n ");
34 }
35
36 const compact = (date: string): string => date.replaceAll("-", "");
37
38 export function calendar(deal: DealView, host: string, stamp = new Date()): string {
39 const now = stamp.toISOString().replace(/[-:]/g, "").replace(/\.\d+/, "");
40 const lines = [
41 "BEGIN:VCALENDAR",
42 "VERSION:2.0",
43 "PRODID:-//deal-clock//EN",
44 "CALSCALE:GREGORIAN",
45 "METHOD:PUBLISH",
46 `X-WR-CALNAME:${icsText(deal.address)}`,
47 ];
48 for (const d of deal.deadlines) {
49 const owner = deal.parties.find((p) => p.role === d.owes);
50 const who = owner === undefined ? PARTY_LABEL[d.owes] : `${owner.name} (${PARTY_LABEL[d.owes]})`;
51 lines.push(
52 "BEGIN:VEVENT",
53 `UID:deadline-${d.id}@${host}`,
54 `DTSTAMP:${now}`,
55 `DTSTART;VALUE=DATE:${compact(d.due)}`,
56 `DTEND;VALUE=DATE:${compact(addDays(d.due, 1))}`,
57 `SUMMARY:${icsText(`${d.done_at === null ? "" : "Done: "}${d.label} — ${deal.address}`)}`,
58 `DESCRIPTION:${icsText(`${who} owes: ${d.what || d.label}`)}`,
59 "STATUS:CONFIRMED",
60 "TRANSP:TRANSPARENT",
61 );
62 if (d.done_at === null)
63 lines.push(
64 "BEGIN:VALARM",
65 "ACTION:DISPLAY",
66 `DESCRIPTION:${icsText(`${d.label} in three days`)}`,
67 "TRIGGER:-P3D",
68 "END:VALARM",
69 "BEGIN:VALARM",
70 "ACTION:DISPLAY",
71 `DESCRIPTION:${icsText(`${d.label} today`)}`,
72 "TRIGGER:PT9H",
73 "END:VALARM",
74 );
75 lines.push("END:VEVENT");
76 }
77 lines.push("END:VCALENDAR");
78 return `${lines.map(fold).join("\r\n")}\r\n`;
79 }
src/live.test.ts added +43
@@ -0,0 +1,43 @@
1 /**
2 * A write made by another process — the terminal — reaches the pages live:
3 * the server follows the database and speaks for it on the event bus.
4 */
5 import { afterAll, expect, test } from "bun:test";
6 import { mkdtempSync } from "node:fs";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { openDb } from "./db.ts";
10 import { follow, subscribe, type LiveEvent } from "./live.ts";
11 import { serve } from "./server.ts";
12
13 test("follow speaks once per change it sees, and not otherwise", async () => {
14 let version = 1;
15 const heard: LiveEvent[] = [];
16 const stop = subscribe((e) => {
17 if (e.type === "test.changed") heard.push(e);
18 });
19 const unfollow = follow(() => version, "test.changed", 5);
20 await Bun.sleep(30);
21 expect(heard.length).toBe(0);
22 version = 2;
23 await Bun.sleep(30);
24 expect(heard.length).toBe(1);
25 unfollow();
26 stop();
27 });
28
29 test("a commit from another connection reaches the server's event stream", async () => {
30 const dir = mkdtempSync(join(tmpdir(), "app-live-"));
31 const server = serve({ port: 0, dataDir: dir, identityKey: "k" });
32 afterAll(() => server.stop(true));
33 const heard: LiveEvent[] = [];
34 const stop = subscribe((e) => {
35 if (e.type === "deal.changed") heard.push(e);
36 });
37 // The terminal's process, in miniature: its own connection to the same file.
38 const elsewhere = openDb(dir);
39 elsewhere.query("UPDATE deadline SET done_at = '2026-10-12T09:00:00Z' WHERE id = 1").run();
40 for (let i = 0; i < 30 && heard.length === 0; i++) await Bun.sleep(100);
41 stop();
42 expect(heard.map((e) => e.data)).toContainEqual({ from: "elsewhere" });
43 });
src/live.ts +20 −2
@@ -3,8 +3,8 @@
33 * streams it to every open page as server-sent events, numbered, with the
44 * last hundred kept so a client that reconnects with `Last-Event-ID` (or
55 * `?since=`) hears what it missed. `static/live.js` turns the stream into
6 * DOM events. The bus is this process's: the terminal is another process,
7 * and its writes show on the next load rather than live.
6 * DOM events. The bus is this process's; the terminal is another process,
7 * so the server `follow`s the database and speaks for writes made elsewhere.
88 */
99
1010 export interface LiveEvent {
@@ -79,3 +79,21 @@ export function events(request: Request): Response {
7979 },
8080 });
8181 }
82
83 /**
84 * Writes another process made (the terminal) as events here. `version` is a
85 * number that changes when someone else commits — SQLite's `data_version` —
86 * read every `ms`; a change is `type`, and every open page catches up.
87 * Returns the stop.
88 */
89 export function follow(version: () => number, type: string, ms = 1000): () => void {
90 let last = version();
91 const timer = setInterval(() => {
92 const now = version();
93 if (now === last) return;
94 last = now;
95 emit(type, { from: "elsewhere" });
96 }, ms);
97 timer.unref?.();
98 return () => clearInterval(timer);
99 }
src/mcp.ts +64 −1
@@ -8,7 +8,10 @@
88
99 import type { Database } from "bun:sqlite";
1010 import { addNote, deleteNote, listNotes, type Result } from "./actions.ts";
11 import { title } from "./env.ts";
11 import { today } from "./dates.ts";
12 import { getDeal, listDeals, markDone, moveDeadline, sendReminder } from "./deals.ts";
13 import { agent, title } from "./env.ts";
14 import { dueOn } from "./reminders.ts";
1215 import { fields } from "./http.ts";
1316 import type { Who } from "./who.ts";
1417
@@ -62,6 +65,66 @@ export const tools: readonly Tool[] = [
6265 },
6366 run: (db, who, args) => deleteNote(db, who, { id: Number(args.id) }),
6467 },
68 {
69 name: "list_deals",
70 description: "Every deal with its dates, parties and sent reminders, soonest closing first.",
71 inputSchema: { type: "object", properties: {} },
72 run: (db, who) => listDeals(db, who),
73 },
74 {
75 name: "get_deal",
76 description: "One deal by id.",
77 inputSchema: { type: "object", properties: { id: { type: "integer" } }, required: ["id"] },
78 run: (db, who, args) => getDeal(db, who, { id: Number(args.id) }),
79 },
80 {
81 name: "reminders_today",
82 description: "The reminder drafts that go out today and have not been sent.",
83 inputSchema: { type: "object", properties: {} },
84 run: (db, who) => {
85 const deals = listDeals(db, who);
86 return deals.ok ? { ok: true, value: dueOn(deals.value, today(), agent) } : deals;
87 },
88 },
89 {
90 name: "mark_done",
91 description: "Mark a date done (or reopen it with done: false).",
92 inputSchema: {
93 type: "object",
94 properties: { id: { type: "integer" }, done: { type: "boolean", default: true } },
95 required: ["id"],
96 },
97 run: (db, who, args) => markDone(db, who, { id: Number(args.id), done: args.done !== false }),
98 },
99 {
100 name: "move_date",
101 description: "Move one date, and only that one, giving the reason.",
102 inputSchema: {
103 type: "object",
104 properties: {
105 id: { type: "integer" },
106 due: { type: "string", format: "date" },
107 reason: { type: "string", maxLength: 200 },
108 },
109 required: ["id", "due", "reason"],
110 },
111 run: (db, who, args) => moveDeadline(db, who, { id: Number(args.id), due: args.due, reason: args.reason }),
112 },
113 {
114 name: "send_reminder",
115 description: "Mark a reminder sent to one party (simulated: nothing is emailed).",
116 inputSchema: {
117 type: "object",
118 properties: {
119 deadline_id: { type: "integer" },
120 party_id: { type: "integer" },
121 moment: { enum: ["before", "day_of"] },
122 },
123 required: ["deadline_id", "party_id", "moment"],
124 },
125 run: (db, who, args) =>
126 sendReminder(db, who, { deadlineId: Number(args.deadline_id), partyId: Number(args.party_id), moment: args.moment }),
127 },
65128 ];
66129
67130 /** One JSON-RPC message in, an HTTP status and a body out (a notification gets 202 and no body). */
src/openapi.ts +3 −1
@@ -12,12 +12,14 @@
1212
1313 import { contract } from "./contract.ts";
1414 import { description, title, version } from "./env.ts";
15 import { AUDIT_ROW, ERROR, NOTE, routes, type Schema } from "./routes.ts";
15 import { AUDIT_ROW, DEAL, DRAFT, ERROR, NOTE, routes, type Schema } from "./routes.ts";
1616 import { doorOf } from "./security.ts";
1717
1818 // The shapes said once, under components, and referred to wherever they appear.
1919 const NAMED = new Map<Schema, string>([
2020 [NOTE, "Note"],
21 [DEAL, "Deal"],
22 [DRAFT, "Reminder"],
2123 [AUDIT_ROW, "AuditRow"],
2224 [ERROR, "Error"],
2325 ]);
src/page.ts deleted −123
@@ -1,123 +0,0 @@
1 /**
2 * The page, rendered on the server: the first paint is complete HTML, and
3 * `static/live.js` keeps the notes fresh afterwards. When a second page
4 * arrives, move `layout` to `src/pages/layout.ts` and give each page a file.
5 */
6
7 import { canDelete, type Note } from "./actions.ts";
8 import {
9 commit,
10 description,
11 env,
12 publicOrigin,
13 ssh,
14 title,
15 where,
16 } from "./env.ts";
17 import { asset, escape } from "./http.ts";
18 import { token, tokensHref } from "./tokens.ts";
19 import type { Who } from "./who.ts";
20
21 /**
22 * The frame every page shares: the tokens and the look, who you are, and
23 * what a link to the page says when it is shared — a title, a sentence
24 * and the address, for Open Graph and the card a chat app unfurls.
25 */
26 export function layout(body: string, who: Who, path = "/"): string {
27 const door =
28 who.role === "anon"
29 ? `<a class="button button-quiet" href="/__forge/signin?to=/">Sign in</a>`
30 : `<span class="you"><b>${escape(who.name)}</b>${who.role === "admin" ? " · admin" : ""}</span>
31 <a class="button button-quiet" href="/__forge/signout">Sign out</a>`;
32 return `<!doctype html>
33 <html lang="en">
34 <meta charset="utf-8">
35 <meta name="viewport" content="width=device-width, initial-scale=1">
36 <meta name="color-scheme" content="light dark">
37 <meta name="theme-color" content="${token("color-bg")}" media="(prefers-color-scheme: light)">
38 <meta name="theme-color" content="${token("color-bg", "dark")}" media="(prefers-color-scheme: dark)">
39 <link rel="icon" href="data:,">
40 <title>${escape(title)}</title>
41 <meta name="description" content="${escape(description)}">
42 <meta property="og:type" content="website">
43 <meta property="og:site_name" content="${escape(title)}">
44 <meta property="og:title" content="${escape(title)}">
45 <meta property="og:description" content="${escape(description)}">
46 <meta property="og:url" content="${escape(publicOrigin + path)}">
47 <meta name="twitter:card" content="summary">
48 <meta name="twitter:title" content="${escape(title)}">
49 <meta name="twitter:description" content="${escape(description)}">
50 <link rel="stylesheet" href="${tokensHref}">
51 <link rel="stylesheet" href="${asset("app.css")}">
52 <script type="module" src="${asset("live.js")}"></script>
53 <body>
54 <div class="page">
55 <header class="head">
56 <div>
57 <h1>${escape(title)}</h1>
58 <p class="muted">${escape(description)}</p>
59 </div>
60 <nav class="row">
61 <span class="pill" data-env="${escape(env)}">${escape(where)}</span>${commit ? `<span class="muted mono">${escape(commit)}</span>` : ""}
62 ${door}
63 </nav>
64 </header>
65 <main>${body}</main>
66 <footer class="muted">
67 ${ssh === undefined ? "" : `<p>Terminal: <code>${escape(ssh)}</code></p>`}
68 <p>Also at <a href="/api/notes">/api/notes</a> (<a href="/openapi.json">described</a>) and <code>POST /mcp</code>, with the same rules.</p>
69 <p>Something wrong? <a href="/__forge/report">Report a problem</a>, no account needed.</p>
70 </footer>
71 </div>
72 </body>
73 </html>
74 `;
75 }
76
77 export function home(input: {
78 who: Who;
79 notes: readonly Note[];
80 notice?: string | undefined;
81 }): string {
82 const { who, notes, notice } = input;
83 const composer =
84 who.role === "anon"
85 ? `<p class="muted">Reading as a guest. <a href="/__forge/signin?to=/">Sign in</a> to add a note.</p>`
86 : `<form class="row" method="post" action="/notes">
87 <input class="input" name="body" placeholder="Write a note" aria-label="New note" required maxlength="500" autocomplete="off" autofocus>
88 <button class="button">Add</button>
89 </form>`;
90 const list =
91 notes.length === 0
92 ? `<p class="empty">No notes yet. Notes written here stay in ${escape(where)} data.</p>`
93 : `<ul class="list">${notes.map((note) => item(note, who)).join("")}</ul>`;
94 return layout(
95 `<section class="card">${composer}</section>
96 <section id="notes" data-live="note.added note.removed">${list}</section>
97 ${notice === undefined ? "" : `<p class="toast" role="status">${escape(notice)}</p>`}`,
98 who,
99 );
100 }
101
102 const item = (note: Note, who: Who): string => `<li class="note">
103 <div>
104 <p>${escape(note.body)}</p>
105 <small class="muted">${escape(note.author_name)} · <time datetime="${escape(note.created_at)}">${ago(note.created_at)}</time></small>
106 </div>
107 ${
108 canDelete(who, note)
109 ? `<form method="post" action="/notes/${note.id}/delete"><button class="button button-quiet" aria-label="Remove this note">Remove</button></form>`
110 : ""
111 }
112 </li>`;
113
114 const ago = (iso: string): string => {
115 const s = Math.max(0, (Date.now() - Date.parse(iso)) / 1000);
116 if (s < 60) return "just now";
117 if (s < 3600) return `${Math.floor(s / 60)}m ago`;
118 if (s < 86400) return `${Math.floor(s / 3600)}h ago`;
119 return new Date(iso).toLocaleDateString("en", {
120 month: "short",
121 day: "numeric",
122 });
123 };
src/pages/clock.ts added +132
@@ -0,0 +1,132 @@
1 /**
2 * The first screen: every deal as a lane, left to right by time, today as a
3 * line down the middle of it all, and each date a marker coloured by how
4 * urgent it is. Tapping a marker opens its sheet (`sheet.ts`). Below the
5 * clock, the reminders that go out today.
6 */
7
8 import { addDays, daysBetween, isWeekend, relative, short, spoken, urgency } from "../dates.ts";
9 import type { DealView } from "../deals.ts";
10 import { KIND } from "../deadlines.ts";
11 import { agent } from "../env.ts";
12 import { escape } from "../http.ts";
13 import { drafts } from "../reminders.ts";
14 import type { Who } from "../who.ts";
15 import { layout } from "./layout.ts";
16 import { draftItem, sheet, sheetId, URGENCY_LABEL } from "./sheet.ts";
17 import { canChange } from "../deals.ts";
18
19 /** The days the clock shows: a week behind today (further, if something open is older), to a few days past the last closing. */
20 export function span(deals: readonly DealView[], on: string): { start: string; days: number } {
21 let start = addDays(on, -7);
22 let end = addDays(on, 21);
23 for (const deal of deals)
24 for (const d of deal.deadlines) {
25 if (d.done_at === null && d.due < addDays(start, 2)) start = addDays(d.due, -2);
26 if (d.due > addDays(end, -4)) end = addDays(d.due, 4);
27 }
28 return { start, days: daysBetween(start, end) + 1 };
29 }
30
31 /** Markers on one lane, each on the first row it does not crowd. */
32 function rows(deal: DealView, start: string): { row: number; x: number; i: number }[] {
33 const last: number[] = [];
34 return deal.deadlines.flatMap((d, i) => {
35 const x = daysBetween(start, d.due);
36 if (x < 0) return [];
37 let row = last.findIndex((at) => x - at >= 3);
38 if (row === -1) row = last.length;
39 last[row] = x;
40 return [{ row, x, i }];
41 });
42 }
43
44 const at = (days: number): string => `calc(${days} * var(--size-day))`;
45
46 function lane(deal: DealView, start: string, on: string): string {
47 const placed = rows(deal, start);
48 const height = Math.max(1, ...placed.map((p) => p.row + 1));
49 const markers = placed
50 .map(({ row, x, i }) => {
51 const d = deal.deadlines[i]!;
52 const u = urgency(d.due, on, d.done_at !== null);
53 const tag = d.kind === "custom" ? d.label.split(" ")[0]! : KIND[d.kind].tag;
54 return `<button class="marker" data-u="${u}" popovertarget="${sheetId(d)}" style="left:${at(x)};top:calc(${row} * 3rem)" aria-label="${escape(`${d.label}, ${spoken(d.due)} — ${URGENCY_LABEL[u]}`)}"><span class="dot"></span>${escape(tag)}</button>`;
55 })
56 .join("");
57 return `<li class="lane">
58 <div class="lane-head"><a href="/deals/${deal.id}">${escape(deal.address)}</a> <small class="muted">closes ${escape(spoken(deal.closing))} · ${escape(relative(deal.closing, on))}</small></div>
59 <div class="track" style="height:calc(${height} * 3rem)">${markers}</div>
60 </li>`;
61 }
62
63 /** Weekends shaded, each Monday labelled, today a line through every lane. */
64 function axis(start: string, days: number, on: string): string {
65 const out: string[] = [];
66 for (let i = 0; i < days; i++) {
67 const day = addDays(start, i);
68 const weekday = new Date(`${day}T00:00:00Z`).getUTCDay();
69 if (isWeekend(day)) out.push(`<span class="weekend" style="left:${at(i)}"></span>`);
70 // The first day is labelled too, unless a Monday label is close enough to crowd it.
71 if (weekday === 1 || (i === 0 && weekday >= 2 && weekday <= 5))
72 out.push(`<span class="tick" style="left:${at(i)}">${escape(short(day))}</span>`);
73 }
74 const t = daysBetween(start, on);
75 out.push(`<span class="today" style="left:${at(t + 0.5)}"><span>Today</span></span>`);
76 return out.join("");
77 }
78
79 export function clock(input: {
80 who: Who;
81 deals: readonly DealView[];
82 on: string;
83 notice?: string | undefined;
84 }): string {
85 const { who, deals, on, notice } = input;
86 const open = deals.flatMap((deal) => deal.deadlines.filter((d) => d.done_at === null));
87 const overdue = open.filter((d) => urgency(d.due, on, false) === "overdue").length;
88 const soon = open.filter((d) => urgency(d.due, on, false) === "soon").length;
89 const { start, days } = span(deals, on);
90 const today = deals.flatMap((deal) =>
91 drafts(deal, agent)
92 .filter((r) => r.on === on || (r.on < on && r.sent_at === null && r.due >= on))
93 .map((r) => ({ r, may: canChange(who, deal) })),
94 );
95 const unsent = today.filter(({ r }) => r.sent_at === null).length;
96 const timeline =
97 deals.length === 0
98 ? `<p class="empty">No deals yet. <a href="/deals/new">Open the first one</a>.</p>`
99 : `<div class="clock-scroll" tabindex="0" role="region" aria-label="Timeline of every deal's dates">
100 <div class="clock-inner" style="width:${at(days)}">
101 <div class="axis" aria-hidden="true">${axis(start, days, on)}</div>
102 <ol class="lanes">${deals.map((deal) => lane(deal, start, on)).join("")}</ol>
103 </div>
104 </div>
105 ${deals.flatMap((deal) => deal.deadlines.map((d) => sheet(deal, d, who, on, "/"))).join("")}`;
106 const body = `<section class="intro">
107 <div>
108 <h1>The clock</h1>
109 <p class="summary"><span>${escape(spoken(on))}</span> · <span>${deals.length} ${deals.length === 1 ? "deal" : "deals"}</span>${overdue > 0 ? ` · <b class="u-overdue">${overdue} overdue</b>` : ""}${soon > 0 ? ` · <b class="u-soon">${soon} due within 3 days</b>` : ""}</p>
110 </div>
111 ${who.role === "anon" ? "" : `<a class="button" href="/deals/new">New deal</a>`}
112 </section>
113 <section id="clock" class="card clock" data-live="deal.changed">
114 ${timeline}
115 <ul class="legend" aria-label="Legend">
116 <li><span class="dot" data-u="overdue"></span>Overdue</li>
117 <li><span class="dot" data-u="soon"></span>Due within 3 days</li>
118 <li><span class="dot" data-u="later"></span>Upcoming</li>
119 <li><span class="dot" data-u="done"></span>Done</li>
120 </ul>
121 </section>
122 <section id="today" class="card" data-live="deal.changed">
123 <h2>Reminders for today <span class="muted">· ${unsent === 0 ? "all sent" : `${unsent} to send`}</span></h2>
124 ${
125 today.length === 0
126 ? `<p class="muted">Nothing goes out today.</p>`
127 : `<ul class="drafts">${today.map(({ r, may }) => draftItem(r, on, may, "/", true, true)).join("")}</ul>`
128 }
129 <p class="muted small">Each date reminds its parties three days before and the morning of. Sending is simulated: the draft is shown and marked sent.</p>
130 </section>`;
131 return layout({ body, who, path: "/", notice });
132 }
src/pages/deal.ts added +141
@@ -0,0 +1,141 @@
1 /**
2 * One deal at `/deals/:id`: its dates in order, its parties, and — for
3 * whoever may change it — adding a date or a party. Each date opens the
4 * same sheet the clock does. And the form that opens a new deal.
5 */
6
7 import { addDays, relative, spoken } from "../dates.ts";
8 import { canChange, canRemove, type DealView } from "../deals.ts";
9 import { DEFAULT_LENGTHS, PARTY_LABEL, PARTY_ROLES } from "../deadlines.ts";
10 import { escape } from "../http.ts";
11 import type { Who } from "../who.ts";
12 import { layout } from "./layout.ts";
13 import { badge, dueLine, owedBy, sheet, sheetId } from "./sheet.ts";
14
15 const roleOptions = (selected?: string): string =>
16 PARTY_ROLES.map(
17 (r) => `<option value="${r}"${r === selected ? " selected" : ""}>${escape(PARTY_LABEL[r])}</option>`,
18 ).join("");
19
20 export function dealPage(input: {
21 who: Who;
22 deal: DealView;
23 on: string;
24 notice?: string | undefined;
25 }): string {
26 const { who, deal, on, notice } = input;
27 const path = `/deals/${deal.id}`;
28 const may = canChange(who, deal);
29 const dates = deal.deadlines
30 .map(
31 (d) => `<li class="date-row">
32 <div>
33 <p>${badge(d, on)} <b>${escape(d.label)}</b></p>
34 <p class="muted small">${escape(dueLine(d, on))}${d.moves.length > 0 ? ` · moved ${d.moves.length}×` : ""}</p>
35 <p class="small">${owedBy(deal, d)}</p>
36 </div>
37 <button class="button button-quiet" popovertarget="${sheetId(d)}">Open</button>
38 </li>`,
39 )
40 .join("");
41 const parties =
42 deal.parties.length === 0
43 ? `<p class="muted">No parties yet.</p>`
44 : `<ul class="parties">${deal.parties
45 .map(
46 (p) =>
47 `<li><span class="muted">${escape(PARTY_LABEL[p.role])}</span><b>${escape(p.name)}</b>${p.contact === "" ? "" : `<span class="mono">${escape(p.contact)}</span>`}</li>`,
48 )
49 .join("")}</ul>`;
50 const forms = may
51 ? `<section class="card">
52 <h2>Add a date</h2>
53 <p class="muted small">A date the contract adds: an HOA review, a repair deadline, a rate lock.</p>
54 <form class="stack" method="post" action="${path}/deadlines">
55 <label>What<input class="input" name="label" required maxlength="100" placeholder="HOA documents review ends"></label>
56 <div class="pair">
57 <label>Date<input class="input" type="date" name="due" required value="${escape(addDays(on, 7))}"></label>
58 <label>Owed by<select class="input" name="owes">${roleOptions("buyer")}</select></label>
59 </div>
60 <label>Details <span class="muted">(optional)</span><input class="input" name="what" maxlength="200"></label>
61 <button class="button">Add date</button>
62 </form>
63 </section>
64 <section class="card">
65 <h2>Add a party</h2>
66 <form class="stack" method="post" action="${path}/parties">
67 <div class="pair">
68 <label>Role<select class="input" name="role">${roleOptions("lender")}</select></label>
69 <label>Name<input class="input" name="name" required maxlength="100"></label>
70 </div>
71 <label>Email or phone <span class="muted">(optional)</span><input class="input" name="contact" maxlength="120"></label>
72 <button class="button">Add party</button>
73 </form>
74 </section>`
75 : `<p class="muted"><a href="/__forge/signin?to=${encodeURIComponent(path)}">Sign in</a> to add a date or a party.</p>`;
76 const body = `<p class="crumb"><a href="/">← The clock</a></p>
77 <section class="intro">
78 <div>
79 <h1>${escape(deal.address)}</h1>
80 <p class="summary">Under contract ${escape(spoken(deal.contract_date))} · closes ${escape(spoken(deal.closing))}, ${escape(relative(deal.closing, on))}${deal.business_days ? " · business days" : ""}</p>
81 </div>
82 <a class="button button-quiet" href="${path}/ics" download>Add to calendar</a>
83 </section>
84 <div id="deal" data-live="deal.changed">
85 <section class="card">
86 <h2>Dates</h2>
87 <ol class="dates">${dates}</ol>
88 </section>
89 <section class="card" id="parties">
90 <h2>Parties</h2>
91 ${parties}
92 </section>
93 ${deal.deadlines.map((d) => sheet(deal, d, who, on, path)).join("")}
94 </div>
95 ${forms}
96 ${
97 canRemove(who, deal)
98 ? `<form method="post" action="${path}/delete" class="remove"><button class="button button-quiet">Remove this deal</button></form>`
99 : ""
100 }`;
101 return layout({ body, who, path, heading: deal.address, notice });
102 }
103
104 export function newDealPage(input: { who: Who; on: string; notice?: string | undefined }): string {
105 const { who, on, notice } = input;
106 const length = (name: keyof typeof DEFAULT_LENGTHS, label: string) =>
107 `<label>${label}<input class="input" type="number" inputmode="numeric" name="${name}" min="0" max="180" value="${DEFAULT_LENGTHS[name]}" required></label>`;
108 const body =
109 who.role === "anon"
110 ? `<p class="crumb"><a href="/">← The clock</a></p><section class="card"><h1>New deal</h1><p><a href="/__forge/signin?to=/deals/new">Sign in</a> to open a deal.</p></section>`
111 : `<p class="crumb"><a href="/">← The clock</a></p>
112 <section class="card narrow">
113 <h1>New deal</h1>
114 <p class="muted">The contract and closing dates, and the contingency lengths, set every date. You can move any of them after.</p>
115 <form class="stack" method="post" action="/deals">
116 <label>Property address<input class="input" name="address" required minlength="3" maxlength="200" autocomplete="off" placeholder="1418 Alder Lane"></label>
117 <div class="pair">
118 <label>Buyer<input class="input" name="buyer" required maxlength="100"></label>
119 <label>Seller<input class="input" name="seller" required maxlength="100"></label>
120 </div>
121 <div class="pair">
122 <label>Contract date<input class="input" type="date" name="contract_date" required value="${escape(on)}"></label>
123 <label>Closing date<input class="input" type="date" name="closing_date" required value="${escape(addDays(on, 35))}"></label>
124 </div>
125 <fieldset>
126 <legend>Contingency lengths, in days from the contract date</legend>
127 <div class="lengths">
128 ${length("inspection", "Inspection")}
129 ${length("appraisal", "Appraisal")}
130 ${length("financing", "Financing")}
131 ${length("title", "Title")}
132 ${length("walkthrough", "Walkthrough, days before closing")}
133 </div>
134 <label class="check"><input type="checkbox" name="business_days"> Count business days (skip weekends)</label>
135 </fieldset>
136 <button class="button">Open deal</button>
137 </form>
138 <p class="muted small">Reading these from the contract PDF is phase two.</p>
139 </section>`;
140 return layout({ body, who, path: "/deals/new", heading: "New deal", notice });
141 }
src/pages/layout.ts added +83
@@ -0,0 +1,83 @@
1 /**
2 * The frame every page shares: the tokens and the look, the agent whose
3 * deals these are, who is signed in, and what a link to the page says when
4 * it is shared — a title, a sentence and the address, for Open Graph and
5 * the card a chat app unfurls.
6 */
7
8 import {
9 agent,
10 commit,
11 description,
12 env,
13 publicOrigin,
14 ssh,
15 title,
16 where,
17 } from "../env.ts";
18 import { asset, escape } from "../http.ts";
19 import { token, tokensHref } from "../tokens.ts";
20 import type { Who } from "../who.ts";
21
22 export function layout(input: {
23 body: string;
24 who: Who;
25 path: string;
26 heading?: string;
27 notice?: string | undefined;
28 }): string {
29 const { body, who, path, notice } = input;
30 const pageTitle = input.heading === undefined ? title : `${input.heading} · ${title}`;
31 const to = encodeURIComponent(path);
32 const door =
33 who.role === "anon"
34 ? `<a class="button button-quiet" href="/__forge/signin?to=${to}">Sign in</a>`
35 : `<span class="you"><b>${escape(who.name)}</b>${who.role === "admin" ? " · admin" : ""}</span>
36 <a class="button button-quiet" href="/__forge/signout">Sign out</a>`;
37 return `<!doctype html>
38 <html lang="en">
39 <meta charset="utf-8">
40 <meta name="viewport" content="width=device-width, initial-scale=1">
41 <meta name="color-scheme" content="light dark">
42 <meta name="theme-color" content="${token("color-bg")}" media="(prefers-color-scheme: light)">
43 <meta name="theme-color" content="${token("color-bg", "dark")}" media="(prefers-color-scheme: dark)">
44 <link rel="icon" href="data:,">
45 <title>${escape(pageTitle)}</title>
46 <meta name="description" content="${escape(description)}">
47 <meta property="og:type" content="website">
48 <meta property="og:site_name" content="${escape(title)}">
49 <meta property="og:title" content="${escape(pageTitle)}">
50 <meta property="og:description" content="${escape(description)}">
51 <meta property="og:url" content="${escape(publicOrigin + path)}">
52 <meta name="twitter:card" content="summary">
53 <meta name="twitter:title" content="${escape(pageTitle)}">
54 <meta name="twitter:description" content="${escape(description)}">
55 <link rel="stylesheet" href="${tokensHref}">
56 <link rel="stylesheet" href="${asset("app.css")}">
57 <script type="module" src="${asset("live.js")}"></script>
58 <body>
59 <div class="page">
60 <header class="head">
61 <a class="brand" href="/">
62 <span class="brand-mark" aria-hidden="true"></span>
63 <span><b>${escape(agent.name)}</b><small>${escape(agent.brokerage)}</small></span>
64 </a>
65 <nav class="row">
66 ${env === "production" ? "" : `<span class="pill" data-env="${escape(env)}">${escape(where)}</span>`}
67 ${door}
68 </nav>
69 </header>
70 <main>${body}</main>
71 <footer class="muted">
72 <p>${escape(title)}${commit ? ` <span class="mono">${escape(commit)}</span>` : ""} — reminders here are drafted and marked sent; nothing is emailed or texted yet.</p>
73 ${ssh === undefined ? "<p>The terminal is off.</p>" : `<p>Terminal: <code>${escape(ssh)}</code></p>`}
74 <p>Also at <a href="/api/deals">/api/deals</a> (<a href="/openapi.json">described</a>), <code>POST /tick</code> and <code>POST /mcp</code>, with the same rules.</p>
75 <p>Something wrong? <a href="/__forge/report">Report a problem</a>, no account needed.</p>
76 </footer>
77 </div>
78 ${notice === undefined ? "" : `<p class="toast" role="status">${escape(notice)}</p>`}
79 </body>
80 </html>
81 `;
82 }
83
src/pages/refused.ts added +25
@@ -0,0 +1,25 @@
1 /**
2 * The page for a "no": a stranger is asked to sign in and sent back here
3 * after; anyone else is told plainly. What a deal holds is for signed-in
4 * agents only, so a guest at the clock or at a deal meets this.
5 */
6
7 import type { Failure } from "../result.ts";
8 import { escape } from "../http.ts";
9 import type { Who } from "../who.ts";
10 import { layout } from "./layout.ts";
11
12 export function refusedPage(input: {
13 who: Who;
14 path: string;
15 heading: string;
16 error: Failure;
17 message: string;
18 }): string {
19 const { who, path, heading, error, message } = input;
20 const body =
21 error === "signin_required"
22 ? `<section class="card narrow"><h1>${escape(heading)}</h1><p>${escape(message)}</p><p><a class="button" href="/__forge/signin?to=${encodeURIComponent(path)}">Sign in</a></p></section>`
23 : `<section class="card narrow"><h1>${escape(heading)}</h1><p>${escape(message)} <a href="/">Back to the clock</a>.</p></section>`;
24 return layout({ body, who, path, heading });
25 }
src/pages/sheet.ts added +131
@@ -0,0 +1,131 @@
1 /**
2 * One date, opened: who owes what, what it has moved through, the reminder
3 * drafts, and — for whoever may change the deal — mark done and move. A
4 * native popover, so it opens from the clock or the deal page with no
5 * script; the forms post and come back.
6 */
7
8 import { canChange, type DealView, type DeadlineView } from "../deals.ts";
9 import { relative, short, spoken, urgency, type Urgency } from "../dates.ts";
10 import { PARTY_LABEL } from "../deadlines.ts";
11 import { agent } from "../env.ts";
12 import { escape } from "../http.ts";
13 import { draftsFor, MOMENT_LABEL, MOMENTS, type Draft } from "../reminders.ts";
14 import type { Who } from "../who.ts";
15
16 export const sheetId = (d: DeadlineView): string => `sheet-${d.id}`;
17
18 export const URGENCY_LABEL: Readonly<Record<Urgency, string>> = {
19 done: "Done",
20 overdue: "Overdue",
21 soon: "Due soon",
22 later: "Upcoming",
23 };
24
25 /** "Due Thu, Oct 15 · in 3 days", or "Done". */
26 export function dueLine(d: DeadlineView, on: string): string {
27 if (d.done_at !== null) return `Done · was due ${spoken(d.due)}`;
28 return `Due ${spoken(d.due)} · ${relative(d.due, on)}`;
29 }
30
31 export const badge = (d: DeadlineView, on: string): string => {
32 const u = urgency(d.due, on, d.done_at !== null);
33 return `<span class="badge" data-u="${u}">${URGENCY_LABEL[u]}</span>`;
34 };
35
36 /** Who owes it, by name when the deal has that party. */
37 export function owedBy(deal: DealView, d: DeadlineView): string {
38 const party = deal.parties.find((p) => p.role === d.owes);
39 const role = PARTY_LABEL[d.owes];
40 return party === undefined
41 ? `<b>${escape(role)}</b> <span class="muted">(none on file yet)</span>`
42 : `<b>${escape(party.name)}</b> <span class="muted">· ${escape(role)}</span>`;
43 }
44
45 const hidden = (fields: Record<string, string | number>): string =>
46 Object.entries(fields)
47 .map(([k, v]) => `<input type="hidden" name="${k}" value="${escape(String(v))}">`)
48 .join("");

Low: this doc comment is orphaned. It sits on top of draftText's own doc comment and duplicates draftItem's. Remove it.

49
50 /** The words of a draft, as the party will read them. */
51 const draftText = (draft: Draft): string => `<div class="draft-text">
52 <p class="muted">To ${escape(draft.contact || draft.party_name)}</p>
53 <p><b>${escape(draft.subject)}</b></p>
54 <p class="draft-body">${escape(draft.body)}</p>
55 </div>`;
56
57 /**
58 * One reminder: who, when, and the one tap that marks it sent. `withText`
59 * folds its words in beneath; a sheet shows the words once per moment instead.
60 */
61 export function draftItem(draft: Draft, on: string, may: boolean, to: string, withText = true, withDeal = false): string {
62 const state =
63 draft.sent_at !== null
64 ? `<span class="state" data-sent>Sent ${escape(short(draft.sent_at.slice(0, 10)))}</span>`
65 : draft.on < on
66 ? `<span class="state" data-late>Was due ${escape(short(draft.on))}</span>`
67 : draft.on === on
68 ? `<span class="state" data-today>Goes out today</span>`
69 : `<span class="state">Goes out ${escape(short(draft.on))}</span>`;
70 const send =
71 may && draft.sent_at === null
72 ? `<form method="post" action="/reminders">${hidden({ deadline: draft.deadline_id, party: draft.party_id, moment: draft.moment, to })}<button class="button button-small">Send</button></form>`
73 : "";
74 const who = `<span><b>${escape(draft.party_name)}</b> <span class="muted">· ${escape(PARTY_LABEL[draft.party_role])}${withDeal ? ` · ${escape(draft.label)}, ${escape(draft.address)}` : ""}</span></span>${state}`;
75 return `<li class="draft">${withText ? `<details><summary>${who}</summary>${draftText(draft)}</details>` : `<div class="draft-who">${who}</div>`}${send}</li>`;
76 }
77
78 export function sheet(deal: DealView, d: DeadlineView, who: Who, on: string, to: string): string {
79 const id = sheetId(d);
80 const may = canChange(who, deal);
81 const drafts = d.done_at === null ? draftsFor(deal, d, agent) : [];
82 const reminders =
83 d.done_at !== null
84 ? `<p class="muted">Done, so no reminders go out.</p>`
85 : drafts.length === 0
86 ? `<p class="muted">No one to remind yet — <a href="/deals/${deal.id}#parties">add the parties</a>.</p>`
87 : MOMENTS.map((m) => {
88 const these = drafts.filter((r) => r.moment === m);
89 const head = `<h4>${MOMENT_LABEL[m]} <span class="muted">· ${escape(spoken(these[0]!.on))}</span></h4>`;
90 if (these.every((r) => r.sent_at !== null))
91 return `${head}<p class="muted small">Sent to all ${these.length}.</p>`;
92 return `${head}<details class="draft-preview"><summary>Read the draft</summary>${draftText(these[0]!)}<p class="muted small">Each party gets it addressed to them.</p></details>
93 <ul class="drafts">${these.map((r) => draftItem(r, on, may, to, false)).join("")}</ul>`;
94 }).join("");
95 const moves =
96 d.moves.length === 0
97 ? ""
98 : `<section><h3>Moved</h3><ul class="moves">${d.moves
99 .map(
100 (m) =>
101 `<li>${escape(short(m.from_due))} → ${escape(short(m.to_due))}: ${escape(m.reason)} <span class="muted">· ${escape(m.by_name)}</span></li>`,
102 )
103 .join("")}</ul></section>`;
104 const actions = may
105 ? `<section class="sheet-actions">
106 <form method="post" action="/deadlines/${d.id}/done">${hidden({ done: d.done_at === null ? 1 : 0, to })}
107 <button class="button${d.done_at === null ? "" : " button-quiet"}">${d.done_at === null ? "Mark done" : "Reopen"}</button>
108 </form>
109 <form class="move" method="post" action="/deadlines/${d.id}/move">${hidden({ to })}
110 <label>New date<input class="input" type="date" name="due" value="${escape(d.due)}" required></label>
111 <label>Why it moved<input class="input" name="reason" maxlength="200" required placeholder="e.g. Lender asked for 3 more days"></label>
112 <button class="button button-quiet">Move this date</button>
113 </form>
114 <p class="muted small">Moving a date moves nothing else; the reason is kept.</p>
115 </section>`
116 : `<p class="muted"><a href="/__forge/signin?to=${encodeURIComponent(to)}">Sign in</a> to mark it done, move it, or send reminders.</p>`;
117 return `<div popover id="${id}" class="sheet" aria-labelledby="${id}-h">
118 <header class="sheet-head">
119 <div>
120 <p class="eyebrow"><a href="/deals/${deal.id}">${escape(deal.address)}</a></p>
121 <h2 id="${id}-h">${escape(d.label)}</h2>
122 <p>${badge(d, on)} <span class="muted">${escape(dueLine(d, on))}</span></p>
123 </div>
124 <button class="button button-quiet" popovertarget="${id}" popovertargetaction="hide" aria-label="Close">✕</button>
125 </header>
126 <section><h3>Who owes what</h3><p>${owedBy(deal, d)}</p>${d.what === "" ? "" : `<p>${escape(d.what)}</p>`}</section>
127 ${moves}
128 <section><h3>Reminders</h3>${reminders}</section>
129 ${actions}
130 </div>`;
131 }
src/reminders.ts added +109
@@ -0,0 +1,109 @@
1 /**
2 * Reminders, drafted. Every open date of a deal reminds each party it
3 * concerns twice: three days before, and the morning of. A draft is plain
4 * data — who, when, the words — computed from a deal; nothing is sent
5 * anywhere. `sendReminder` (`deals.ts`) records that the agent sent one.
6 */
7
8 import { addDays, spoken } from "./dates.ts";
9 import { KIND, PARTY_LABEL, type PartyRole } from "./deadlines.ts";
10 import type { DealView, DeadlineView, Moment, Party } from "./deals.ts";
11
12 export interface Agent {
13 readonly name: string;
14 readonly brokerage: string;
15 }
16
17 export interface Draft {
18 readonly deal_id: number;
19 readonly address: string;
20 readonly deadline_id: number;
21 readonly label: string;
22 readonly due: string;
23 readonly party_id: number;
24 readonly party_name: string;
25 readonly party_role: PartyRole;
26 readonly contact: string;
27 readonly moment: Moment;
28 /** The morning it goes out. */
29 readonly on: string;
30 readonly subject: string;
31 readonly body: string;
32 /** When the agent marked it sent, for this date; null while unsent. */
33 readonly sent_at: string | null;
34 }
35
36 export const MOMENTS: readonly Moment[] = ["before", "day_of"];
37 export const MOMENT_LABEL: Readonly<Record<Moment, string>> = {
38 before: "3 days before",
39 day_of: "Morning of",
40 };
41 export const sendOn = (due: string, moment: Moment): string =>
42 moment === "before" ? addDays(due, -3) : due;
43
44 /** The parties a date concerns: whoever owes it, then whoever its kind tells. */
45 export function recipients(deal: DealView, deadline: DeadlineView): Party[] {
46 const roles = new Set<PartyRole>([deadline.owes, ...KIND[deadline.kind].notify]);
47 return deal.parties.filter((p) => roles.has(p.role));
48 }
49
50 const first = (name: string): string => name.split(" ")[0] ?? name;
51
52 function words(
53 deal: DealView,
54 deadline: DeadlineView,
55 party: Party,
56 moment: Moment,
57 agent: Agent,
58 ): { subject: string; body: string } {
59 const when = moment === "before" ? `in three days, on ${spoken(deadline.due)}` : `today, ${spoken(deadline.due)}`;
60 const owner = deal.parties.find((p) => p.role === deadline.owes);
61 const yours = party.role === deadline.owes;
62 const owed = deadline.what === "" ? "" : `${deadline.what}. `;
63 const ask = yours
64 ? "This one is yours — please let me know right away if anything could hold it up."
65 : `${owner === undefined ? PARTY_LABEL[deadline.owes] : owner.name} (${PARTY_LABEL[deadline.owes].toLowerCase()}) is on it; nothing is needed from you unless you hear otherwise.`;
66 return {
67 subject: `${deadline.label} — ${deal.address} — ${moment === "before" ? spoken(deadline.due) : "today"}`,
68 body: `Hi ${first(party.name)}, a reminder that the ${deadline.label.toLowerCase()} for ${deal.address} is ${when}. ${owed}${ask}\n\n${agent.name}, ${agent.brokerage}`,
69 };
70 }
71
72 /** Every reminder an open date of this deal has, sent or not. */
73 export function drafts(deal: DealView, agent: Agent): Draft[] {
74 return deal.deadlines
75 .filter((d) => d.done_at === null)
76 .flatMap((deadline) => draftsFor(deal, deadline, agent));
77 }
78
79 /** The reminders one date has, sent or not. */
80 export function draftsFor(deal: DealView, deadline: DeadlineView, agent: Agent): Draft[] {
81 return MOMENTS.flatMap((moment) =>
82 recipients(deal, deadline).map((party) => ({
83 deal_id: deal.id,
84 address: deal.address,
85 deadline_id: deadline.id,
86 label: deadline.label,
87 due: deadline.due,
88 party_id: party.id,
89 party_name: party.name,
90 party_role: party.role,
91 contact: party.contact,
92 moment,
93 on: sendOn(deadline.due, moment),
94 ...words(deal, deadline, party, moment, agent),
95 sent_at:
96 deal.sent.find(
97 (s) =>
98 s.deadline_id === deadline.id &&
99 s.party_id === party.id &&
100 s.moment === moment &&
101 s.due === deadline.due,
102 )?.sent_at ?? null,
103 })),
104 );
105 }
106
107 /** What goes out on `day` and has not gone yet: `POST /tick`'s answer. */
108 export const dueOn = (deals: readonly DealView[], day: string, agent: Agent): Draft[] =>
109 deals.flatMap((deal) => drafts(deal, agent)).filter((d) => d.on === day && d.sent_at === null);
src/result.ts added +49
@@ -0,0 +1,49 @@
1 /**
2 * What an action answers: the value, or a named failure with a sentence for
3 * a person. Shared by every module of actions (`actions.ts`, `deals.ts`),
4 * with the two habits they all keep: a refusal that asks a stranger to sign
5 * in, and a change that is written into the audit trail either way.
6 */
7
8 import type { Database } from "bun:sqlite";
9 import { record } from "./audit.ts";
10 import type { Who } from "./who.ts";
11
12 export type Failure = "signin_required" | "forbidden" | "not_found" | "invalid";
13 export type Result<T> =
14 | { ok: true; value: T }
15 | { ok: false; error: Failure; message: string };
16 export const ok = <T>(value: T): Result<T> => ({ ok: true, value });
17 export const fail = <T>(error: Failure, message: string): Result<T> => ({
18 ok: false,
19 error,
20 message,
21 });
22
23 /** The refusal for a "no": who is not signed in is asked to; who is, is told. */
24 export const refuse = <T>(who: Who, signIn: string, no: string): Result<T> =>
25 who.role === "anon" ? fail("signin_required", signIn) : fail("forbidden", no);
26
27 /**
28 * A change, written into the audit trail whichever way it went: the row it
29 * made or touched, or the one it was refused. Every action that changes
30 * something returns through here, so the trail holds at every door. With no
31 * `target` (a create), the row made is the target.
32 */
33 export const audited = <T extends { readonly id: number }>(
34 db: Database,
35 who: Who,
36 resource: string,
37 verb: "create" | "update" | "delete",
38 target: number | undefined,
39 result: Result<T>,
40 ): Result<T> => {
41 record(db, {
42 who,
43 resource,
44 verb,
45 target: target ?? (result.ok ? result.value.id : undefined),
46 outcome: result.ok ? "ok" : result.error,
47 });
48 return result;
49 };
src/routes.ts +323 −19
@@ -25,12 +25,13 @@ import {
2525 type Failure,
2626 type Result,
2727 } from "./actions.ts";
28 import { commit, env, forgeUrl, startedAt, version } from "./env.ts";
28 import { agent, commit, env, forgeUrl, publicOrigin, startedAt, version } from "./env.ts";
2929 import {
3030 back,
3131 fields,
3232 html,
3333 json,
34 isForm,
3435 readForm,
3536 readJson,
3637 readNotice,
@@ -39,8 +40,26 @@ import {
3940 text,
4041 } from "./http.ts";
4142 import { events } from "./live.ts";
43 import { today } from "./dates.ts";
44 import {
45 addDeadline,
46 addParty,
47 createDeal,
48 deleteDeal,
49 getDeal,
50 listDeals,
51 markDone,
52 moveDeadline,
53 sendReminder,
54 updateDeal,
55 type NewDeal,
56 } from "./deals.ts";
57 import { calendar } from "./ics.ts";
4258 import { rpc } from "./mcp.ts";
43 import { home } from "./page.ts";
59 import { clock } from "./pages/clock.ts";
60 import { dealPage, newDealPage } from "./pages/deal.ts";
61 import { refusedPage } from "./pages/refused.ts";
62 import { dueOn } from "./reminders.ts";
4463 import { tokensCss } from "./tokens.ts";
4564 import type { Who } from "./who.ts";
4665
@@ -115,6 +134,84 @@ export const AUDIT_ROW: Schema = {
115134 },
116135 required: ["id", "at", "role", "resource", "verb", "allowed", "outcome"],
117136 };
137 const DATE: Schema = { type: "string", format: "date" };
138 const ROLE: Schema = { enum: ["buyer", "seller", "lender", "title", "other_agent"] };
139 export const DEAL: Schema = {
140 type: "object",
141 properties: {
142 id: { type: "integer" },
143 address: { type: "string" },
144 contract_date: DATE,
145 closing: DATE,
146 business_days: { enum: [0, 1] },
147 author_id: { type: "string" },
148 author_name: { type: "string" },
149 created_at: { type: "string", format: "date-time" },
150 parties: {
151 type: "array",
152 items: {
153 type: "object",
154 properties: { id: { type: "integer" }, role: ROLE, name: { type: "string" }, contact: { type: "string" } },
155 },
156 },
157 deadlines: {
158 type: "array",
159 items: {
160 type: "object",
161 properties: {
162 id: { type: "integer" },
163 kind: { enum: ["inspection", "appraisal", "financing", "title", "walkthrough", "closing", "custom"] },
164 label: { type: "string" },
165 due: DATE,
166 owes: ROLE,
167 what: { type: "string" },
168 done_at: { type: ["string", "null"] },
169 moves: { type: "array", items: { type: "object" } },
170 },
171 },
172 },
173 sent: { type: "array", items: { type: "object" } },
174 },
175 required: ["id", "address", "contract_date", "closing", "parties", "deadlines"],
176 };
177 const NEW_DEAL: Schema = {
178 type: "object",
179 properties: {
180 address: { type: "string", minLength: 3, maxLength: 200 },
181 buyer: { type: "string", minLength: 1, maxLength: 100 },
182 seller: { type: "string", minLength: 1, maxLength: 100 },
183 contract_date: DATE,
184 closing_date: DATE,
185 inspection: { type: "integer", minimum: 0, maximum: 180, default: 10 },
186 appraisal: { type: "integer", minimum: 0, maximum: 180, default: 21 },
187 financing: { type: "integer", minimum: 0, maximum: 180, default: 30 },
188 title: { type: "integer", minimum: 0, maximum: 180, default: 14 },
189 walkthrough: { type: "integer", minimum: 0, maximum: 180, default: 1 },
190 business_days: { type: "boolean", default: false },
191 },
192 required: ["address", "buyer", "seller", "contract_date", "closing_date"],
193 };
194 export const DRAFT: Schema = {
195 type: "object",
196 properties: {
197 deal_id: { type: "integer" },
198 address: { type: "string" },
199 deadline_id: { type: "integer" },
200 label: { type: "string" },
201 due: DATE,
202 party_id: { type: "integer" },
203 party_name: { type: "string" },
204 party_role: ROLE,
205 contact: { type: "string" },
206 moment: { enum: ["before", "day_of"] },
207 on: DATE,
208 subject: { type: "string" },
209 body: { type: "string" },
210 sent_at: { type: ["string", "null"] },
211 },
212 required: ["deal_id", "deadline_id", "party_id", "moment", "on", "subject", "body"],
213 };
214 const list = (items: Schema): Schema => ({ type: "array", items });
118215 export const ERROR: Schema = {
119216 type: "object",
120217 properties: { error: { type: "string" }, message: { type: "string" } },
@@ -126,7 +223,6 @@ const LIMIT: Schema = {
126223 maximum: 500,
127224 default: 100,
128225 };
129 const list = (items: Schema): Schema => ({ type: "array", items });
130226
131227 const STATUS: Record<Failure, number> = {
132228 signin_required: 401,
@@ -144,9 +240,45 @@ const answer = <T>(result: Result<T>, status = 200): Response =>
144240 STATUS[result.error],
145241 );
146242
147 /** A result for a form: back to the page, with what went wrong if it did. */
148 const done = <T>(result: Result<T>): Response =>
149 result.ok ? back() : back(result.message);
243 /** A result for a form: back to the page, with what went wrong — or what went right — said once. */
244 const done = <T>(result: Result<T>, to = "/", said?: string): Response =>
245 result.ok ? back(said, to) : back(result.message, to);
246
247 /** Where a form asks to go back to: the clock or a deal's page, nothing else. */
248 export const backTo = (value: unknown): string =>
249 typeof value === "string" && /^\/(?:deals\/\d+)?$/.test(value) ? value : "/";
250
251 /**
252 * A form's fields as plain data — or the refusal: 415 when the request does
253 * not say it is a form (checked before a byte is read), 413 past the cap,
outdated

Medium: readForm throws ERR_FORMDATA_PARSE_ERROR when the content-type is missing or isn't a form type, so all seven form routes return 500 (reproduced with curl -X POST -H 'origin: …' /deadlines/1/done). Catch it here, or check the content-type first, and return a 415 (or 400). Add a test that would fail today.

254 * 400 when it says form and does not decode as one.
255 */
256 async function form(c: Context): Promise<Record<string, string> | Response> {
257 if (!isForm(c.request)) return text("expected a form", 415);
258 const read = await readForm(c.request);
259 if (read === undefined) return text("too large", 413);
260 if (read === null) return text("not a form that decodes", 400);
261 const out: Record<string, string> = {};
262 for (const [key, value] of read) if (typeof value === "string") out[key] = value;
263 return out;
264 }
265
266 /** A new deal from a form or a JSON body: the same names either way. */
267 const newDeal = (f: Record<string, unknown>): NewDeal => ({
268 address: f.address,
269 buyer: f.buyer,
270 seller: f.seller,
271 contractDate: f.contract_date,
272 closingDate: f.closing_date,
273 lengths: {
274 inspection: f.inspection,
275 appraisal: f.appraisal,
276 financing: f.financing,
277 title: f.title,
278 walkthrough: f.walkthrough,
279 },
280 businessDays: f.business_days,
281 });
150282
151283 /** A whole number from the query, or undefined. */
152284 const whole = (value: string | null): number | undefined =>
@@ -157,35 +289,156 @@ const OPENAPI = new URL("../contract/openapi.json", import.meta.url);
157289 const openapi = existsSync(OPENAPI) ? readFileSync(OPENAPI, "utf8") : undefined;
158290
159291 export const routes: readonly Route[] = [
160 // The page. Forms post and come back; the list stays live over /events.
292 // The pages. Forms post and come back; the clock stays live over /events.
161293 {
162294 method: "GET",
163295 path: "/",
164296 handle: (c) => {
165297 const { notice, clear } = readNotice(c.request);
166 const notes = listNotes(c.db, c.who);
167 return html(
168 home({ who: c.who, notes: notes.ok ? notes.value : [], notice }),
169 200,
170 clear,
171 );
298 const deals = listDeals(c.db, c.who);
299 if (!deals.ok)
300 return html(
301 refusedPage({ who: c.who, path: "/", heading: "The clock", error: deals.error, message: deals.message }),
302 200,
303 clear,
304 );
305 return html(clock({ who: c.who, deals: deals.value, on: today(), notice }), 200, clear);
306 },
307 },
308 {
309 method: "GET",
310 path: "/deals/new",
311 handle: (c) => {
312 const { notice, clear } = readNotice(c.request);
313 return html(newDealPage({ who: c.who, on: today(), notice }), 200, clear);
314 },
315 },
316 {
317 method: "GET",
318 path: "/deals/:id",
319 handle: (c) => {
320 const found = getDeal(c.db, c.who, { id: Number(c.params.id) });
321 if (!found.ok)
322 return html(
323 refusedPage({
324 who: c.who,
325 path: c.url.pathname,
326 heading: found.error === "not_found" || found.error === "invalid" ? "No such deal" : "A deal",
327 error: found.error,
328 message: found.message,
329 }),
330 STATUS[found.error],
331 );
332 const { notice, clear } = readNotice(c.request);
333 return html(dealPage({ who: c.who, deal: found.value, on: today(), notice }), 200, clear);
334 },
335 },
336 {
337 method: "GET",
338 path: "/deals/:id/ics",
339 handle: (c) => {
340 const found = getDeal(c.db, c.who, { id: Number(c.params.id) });
341 if (!found.ok) return text(found.message, STATUS[found.error]);
342 const name = found.value.address.replace(/[^A-Za-z0-9]+/g, "-").replace(/^-|-$/g, "").toLowerCase() || "deal";
343 return new Response(calendar(found.value, new URL(publicOrigin).hostname), {
344 headers: {
345 "content-type": "text/calendar; charset=utf-8",
346 "content-disposition": `attachment; filename="${name}.ics"`,
347 "cache-control": "no-store",
348 ...SECURITY,
349 },
350 });
172351 },
173352 },
174353 {
175354 method: "POST",
176 path: "/notes",
355 path: "/deals",
177356 handle: async (c) => {
178 const form = await readForm(c.request);
179 if (form === undefined) return text("too large", 413);
357 const f = await form(c);
358 if (f instanceof Response) return f;
359 const made = createDeal(c.db, c.who, newDeal(f));
360 return made.ok ? back("Deal opened. Every date is on the clock.", `/deals/${made.value.id}`) : back(made.message, "/deals/new");
361 },
362 },
363 {
364 method: "POST",
365 path: "/deals/:id/deadlines",
366 handle: async (c) => {
367 const f = await form(c);
368 if (f instanceof Response) return f;
369 const id = Number(c.params.id);
370 return done(addDeadline(c.db, c.who, { dealId: id, label: f.label, due: f.due, owes: f.owes, what: f.what }), backTo(`/deals/${id}`), "Date added.");
371 },
372 },
373 {
374 method: "POST",
375 path: "/deals/:id/parties",
376 handle: async (c) => {
377 const f = await form(c);
378 if (f instanceof Response) return f;
379 const id = Number(c.params.id);
380 return done(addParty(c.db, c.who, { dealId: id, role: f.role, name: f.name, contact: f.contact }), backTo(`/deals/${id}`), "Party added.");
381 },
382 },
383 {
384 method: "POST",
385 path: "/deals/:id/delete",
386 handle: (c) => {
387 const id = Number(c.params.id);
388 const removed = deleteDeal(c.db, c.who, { id });
389 return removed.ok ? back("Deal removed.") : back(removed.message, backTo(`/deals/${id}`));
390 },
391 },
392 {
393 method: "POST",
394 path: "/deadlines/:id/done",
395 handle: async (c) => {
396 const f = await form(c);
397 if (f instanceof Response) return f;
398 const isDone = f.done !== "0";
399 return done(markDone(c.db, c.who, { id: Number(c.params.id), done: isDone }), backTo(f.to), isDone ? "Marked done." : "Reopened.");
400 },
401 },
402 {
403 method: "POST",
404 path: "/deadlines/:id/move",
405 handle: async (c) => {
406 const f = await form(c);
407 if (f instanceof Response) return f;
408 return done(moveDeadline(c.db, c.who, { id: Number(c.params.id), due: f.due, reason: f.reason }), backTo(f.to), "Date moved; nothing else did.");
409 },
410 },
411 {
412 method: "POST",
413 path: "/reminders",
414 handle: async (c) => {
415 const f = await form(c);
416 if (f instanceof Response) return f;
180417 return done(
181 addNote(c.db, c.who, { body: String(form.get("body") ?? "") }),
418 sendReminder(c.db, c.who, { deadlineId: Number(f.deadline), partyId: Number(f.party), moment: f.moment }),
419 backTo(f.to),
420 "Reminder sent (simulated).",
182421 );
183422 },
184423 },
185424 {
186425 method: "POST",
187 path: "/notes/:id/delete",
188 handle: (c) => done(deleteNote(c.db, c.who, { id: Number(c.params.id) })),
426 path: "/tick",
427 handle: (c) => {
428 const deals = listDeals(c.db, c.who);
429 if (!deals.ok) return answer(deals);
430 const on = today();
431 return json({ on, reminders: dueOn(deals.value, on, agent) });
432 },
433 api: {
434 summary:
435 "The reminders that go out today and have not been sent: call it each morning. It sends nothing and changes nothing.",
436 answer: {
437 type: "object",
438 properties: { on: { type: "string", format: "date" }, reminders: list(DRAFT) },
439 required: ["on", "reminders"],
440 },
441 },
189442 },
190443
191444 // The JSON API: the same actions, the same identity, plain status codes.
@@ -257,6 +510,57 @@ export const routes: readonly Route[] = [
257510 },
258511 },
259512
513 {
514 method: "GET",
515 path: "/api/deals",
516 handle: (c) => answer(listDeals(c.db, c.who)),
517 api: { summary: "Every deal with its dates, parties and sent reminders, soonest closing first.", answer: list(DEAL) },
518 },
519 {
520 method: "POST",
521 path: "/api/deals",
522 handle: async (c) => {
523 const body = await readJson(c.request);
524 if (body === undefined) return json({ error: "too_large" }, 413);
525 return answer(createDeal(c.db, c.who, newDeal(fields(body))), 201);
526 },
527 api: {
528 summary: "Open a deal: its standard dates are computed from the contract date, the closing date and the contingency lengths.",
529 body: NEW_DEAL,
530 answer: DEAL,
531 status: 201,
532 },
533 },
534 {
535 method: "GET",
536 path: "/api/deals/:id",
537 handle: (c) => answer(getDeal(c.db, c.who, { id: Number(c.params.id) })),
538 api: { summary: "One deal.", answer: DEAL },
539 },
540 {
541 method: "PATCH",
542 path: "/api/deals/:id",
543 handle: async (c) => {
544 const body = await readJson(c.request);
545 if (body === undefined) return json({ error: "too_large" }, 413);
546 return answer(updateDeal(c.db, c.who, { id: Number(c.params.id), address: fields(body).address }));
547 },
548 api: {
549 summary: "Correct a deal's address. Dates move one at a time, with a reason (POST /deadlines/:id/move).",
550 body: { type: "object", properties: { address: { type: "string", minLength: 3, maxLength: 200 } }, required: ["address"] },
551 answer: DEAL,
552 },
553 },
554 {
555 method: "DELETE",
556 path: "/api/deals/:id",
557 handle: (c) => answer(deleteDeal(c.db, c.who, { id: Number(c.params.id) })),
558 api: {
559 summary: "Remove a deal and everything on it.",
560 answer: { type: "object", properties: { id: { type: "integer" } }, required: ["id"] },
561 },
562 },
563
260564 // Who tried to change what: the audit trail, for whoever the table lets read it.
261565 {
262566 method: "GET",
src/sample.ts added +117
@@ -0,0 +1,117 @@
1 /**
2 * Four sample deals, written once into a new database so the first screen
3 * shows the job: one with a date gone overdue, one closing this week, one
4 * with a moved date, and one just signed. Dates are set relative to the
5 * day the database is created, so a fresh preview always looks like today.
6 */
7
8 import type { Database } from "bun:sqlite";
9 import { addDays, today } from "./dates.ts";
10 import { DEFAULT_LENGTHS, type PartyRole } from "./deadlines.ts";
11 import { insertDeal } from "./deals.ts";
12
13 const SAMPLE = { id: "sample", name: "Sample data" };
14
15 interface Sample {
16 readonly address: string;
17 readonly buyer: string;
18 readonly seller: string;
19 /** Days from today. */
20 readonly contract: number;
21 readonly closing: number;
22 readonly lengths?: Partial<typeof DEFAULT_LENGTHS>;
23 readonly parties: readonly [PartyRole, string, string][];
24 readonly done?: readonly string[];
25 readonly custom?: readonly [string, number, PartyRole, string][];
26 readonly moved?: readonly [string, number, string];
27 }
28
29 const SAMPLES: readonly Sample[] = [
30 {
31 address: "1418 Alder Lane",
32 buyer: "Maya & Tom Okafor",
33 seller: "Ruth Lindqvist",
34 contract: -26,
35 closing: 4,
36 lengths: { financing: 28 },
37 parties: [
38 ["lender", "Priya Nair, Coastline Mortgage", "[email protected]"],
39 ["title", "Marcus Lee, Bayside Title", "[email protected]"],
40 ["other_agent", "Jordan Ellis, Crestline Homes", "(555) 014-2290"],
41 ],
42 done: ["inspection", "title", "appraisal"],
43 },
44 {
45 address: "77 Harbor View Dr, Unit 4B",
46 buyer: "Samuel Reyes",
47 seller: "Grace & Henry Whitcombe",
48 contract: -12,
49 closing: 33,
50 parties: [
51 ["lender", "Owen Brandt, First Keel Bank", "[email protected]"],
52 ["title", "Bayside Title", "[email protected]"],
53 ["other_agent", "Alicia Moreno, Moreno & Co.", "[email protected]"],
54 ],
55 custom: [["HOA documents review ends", 1, "buyer", "Read the HOA budget, rules and minutes; object in writing if needed"]],
56 },
57 {
58 address: "9 Orchard Row",
59 buyer: "Leah Brennan",
60 seller: "Estate of Walter Pike",
61 contract: -20,
62 closing: 18,
63 parties: [
64 ["lender", "Priya Nair, Coastline Mortgage", "[email protected]"],
65 ["title", "Northgate Title & Escrow", "[email protected]"],
66 ["other_agent", "Ben Adeyemi, Lantern Realty", "[email protected]"],
67 ],
68 done: ["inspection", "title"],
69 custom: [["Repair credit agreed", 5, "seller", "Signed amendment for the roof repair credit"]],
70 moved: ["appraisal", 2, "Appraiser rescheduled — access to the property"],
71 },
72 {
73 address: "2210 Juniper Court",
74 buyer: "Dev & Anika Rao",
75 seller: "Carla Mendes",
76 contract: -3,
77 closing: 40,
78 parties: [
79 ["lender", "Owen Brandt, First Keel Bank", "[email protected]"],
80 ["other_agent", "Jordan Ellis, Crestline Homes", "(555) 014-2290"],
81 ],
82 },
83 ];
84
85 /** Write the samples into an empty database, once; a database that has had them never gets them again. */
86 export function seed(db: Database, on = today()): void {
87 // Asked and written in one write transaction, taken before the question:
outdated

Low: the seeded check runs outside the transaction. On a fresh database, the server and a terminal session both call openDb → seed. If they start at the same moment, both can see no seeded row and both write the four samples. Fix: do the check inside the transaction and start it with db.transaction(...).immediate() (or insert app_meta with INSERT OR IGNORE first and seed only when changes === 1).

88 // the server and a terminal opening a new file at once seed it once.
89 db.transaction(() => {
90 if (db.query("SELECT 1 FROM app_meta WHERE key = 'seeded'").get() !== null) return;
91 for (const s of SAMPLES) {
92 const deal = insertDeal(db, SAMPLE, {
93 address: s.address,
94 buyer: s.buyer,
95 seller: s.seller,
96 contractDate: addDays(on, s.contract),
97 closingDate: addDays(on, s.closing),
98 lengths: { ...DEFAULT_LENGTHS, ...s.lengths },
99 businessDays: false,
100 });
101 for (const [role, name, contact] of s.parties)
102 db.query("INSERT INTO party (deal_id, role, name, contact) VALUES (?1, ?2, ?3, ?4)").run(deal.id, role, name, contact);
103 for (const kind of s.done ?? [])
104 db.query("UPDATE deadline SET done_at = ?1 WHERE deal_id = ?2 AND kind = ?3").run(`${addDays(on, -1)}T17:00:00.000Z`, deal.id, kind);
105 for (const [label, days, owes, what] of s.custom ?? [])
106 db.query("INSERT INTO deadline (deal_id, kind, label, due, owes, what) VALUES (?1, 'custom', ?2, ?3, ?4, ?5)").run(deal.id, label, addDays(on, days), owes, what);
107 if (s.moved !== undefined) {
108 const [kind, days, reason] = s.moved;
109 const d = db.query<{ id: number; due: string }, [number, string]>("SELECT id, due FROM deadline WHERE deal_id = ?1 AND kind = ?2").get(deal.id, kind)!;
110 const to = addDays(on, days);
111 db.query("UPDATE deadline SET due = ?1 WHERE id = ?2").run(to, d.id);
112 db.query("INSERT INTO deadline_move (deadline_id, from_due, to_due, reason, by_name) VALUES (?1, ?2, ?3, ?4, ?5)").run(d.id, d.due, to, reason, SAMPLE.name);
113 }
114 }
115 db.query("INSERT INTO app_meta (key, value) VALUES ('seeded', ?1)").run(on);
116 }).immediate();
117 }
src/server.test.ts +149 −22
@@ -48,22 +48,33 @@ const rpc = (message: unknown, who: Record<string, string> = {}) =>
4848 (r) => r.json() as Promise<any>,
4949 );
5050
51 test("the page knows who you are and offers the right door", async () => {
51 test("the clock knows who you are and offers the right door", async () => {
5252 const guest = await (await fetch(base + "/")).text();
53 expect(guest).toContain("<h1>");
54 expect(guest).toContain("/__forge/signin?to=/");
53 expect(guest).toContain("<h1>The clock</h1>");
54 expect(guest).toContain("/__forge/signin?to=%2F");
5555 expect(guest).toContain('href="/__forge/report"');
56 expect(guest).not.toContain('action="/notes"');
56 expect(guest).not.toContain('href="/deals/new"');
57 expect(guest).not.toContain('action="/deadlines/');
58 expect(guest).toContain("Sign in to see deals.");
59 expect(guest).not.toContain("Alder Lane");
5760 const signed = await (await api("/", {}, alice)).text();
5861 expect(signed).toContain("<b>alice</b>");
5962 expect(signed).toContain("/__forge/signout");
60 expect(signed).toContain('action="/notes"');
63 expect(signed).toContain('href="/deals/new"');
64 expect(signed).toContain('action="/deadlines/');
6165 });
6266
63 test("a form post adds as the person; a guest is sent to sign in", async () => {
67 test("a form post opens a deal as the person; a guest is sent to sign in", async () => {
6468 const form = new FormData();
65 form.set("body", "hello from a form");
66 const refused = await api("/notes", {
69 for (const [k, v] of Object.entries({
70 address: "5 Form Street",
71 buyer: "Ann Buyer",
72 seller: "Sam Seller",
73 contract_date: "2026-10-01",
74 closing_date: "2026-11-05",
75 }))
76 form.set(k, v);
77 const refused = await api("/deals", {
6778 method: "POST",
6879 body: form,
6980 redirect: "manual",
@@ -71,19 +82,18 @@ test("a form post adds as the person; a guest is sent to sign in", async () => {
7182 expect(refused.status).toBe(303);
7283 expect(refused.headers.get("set-cookie")).toContain("notice=");
7384 expect(refused.headers.get("set-cookie")).toContain("SameSite=Lax");
74 expect(await (await fetch(base + "/")).text()).not.toContain(
75 "hello from a form",
76 );
85 expect(await (await fetch(base + "/")).text()).not.toContain("5 Form Street");
7786 const posted = await api(
78 "/notes",
87 "/deals",
7988 { method: "POST", body: form, redirect: "manual" },
8089 alice,
8190 );
8291 expect(posted.status).toBe(303);
83 expect(posted.headers.get("set-cookie")).toBeNull();
84 const page = await (await api("/", {}, alice)).text();
85 expect(page).toContain("hello from a form");
86 expect(page).toContain("alice ·");
92 expect(posted.headers.get("location")).toMatch(/^\/deals\/\d+$/);
93 const page = await (await api(posted.headers.get("location")!, {}, alice)).text();
94 expect(page).toContain("5 Form Street");
95 expect(page).toContain("Inspection period ends");
96 expect(page).toContain("Ann Buyer");
8797 });
8898
8999 test("the JSON API is the same actions with the same identity", async () => {
@@ -136,6 +146,12 @@ test("the MCP server lists the tools and calls them as the caller", async () =>
136146 "list_notes",
137147 "add_note",
138148 "delete_note",
149 "list_deals",
150 "get_deal",
151 "reminders_today",
152 "mark_done",
153 "move_date",
154 "send_reminder",
139155 ]);
140156 const call = (name: string, args: unknown, who = {}) =>
141157 rpc(
@@ -160,6 +176,12 @@ test("the MCP server lists the tools and calls them as the caller", async () =>
160176 expect(
161177 (await call("delete_note", { id: note.id }, root)).result.isError,
162178 ).toBeUndefined();
179 expect((await call("list_deals", {})).result.isError).toBe(true);
180 const deals = JSON.parse((await call("list_deals", {}, alice)).result.content[0].text);
181 const open = deals[0].deadlines.find((d: { done_at: unknown }) => d.done_at === null);
182 expect((await call("mark_done", { id: open.id })).result.isError).toBe(true);
183 expect((await call("mark_done", { id: open.id }, root)).result.isError).toBeUndefined();
184 expect((await call("mark_done", { id: open.id, done: false }, root)).result.isError).toBeUndefined();
163185 expect(
164186 (await rpc({ jsonrpc: "2.0", id: 4, method: "nothing" })).error.code,
165187 ).toBe(-32601);
@@ -179,8 +201,10 @@ test("a change is on the event stream, and a late client hears what it missed",
179201 for (;;) {
180202 const { value } = await reader.read();
181203 buffer += new TextDecoder().decode(value);
182 const frame = /id: (\d+)\ndata: (.*)\n\n/.exec(buffer);
183 if (frame) return { id: frame[1]!, type: JSON.parse(frame[2]!).type };
204 // Earlier tests' events replay first; this one listens for its own.
205 for (const frame of buffer.matchAll(/id: (\d+)\ndata: (.*)\n\n/g))
206 if (JSON.parse(frame[2]!).type === "note.added")
207 return { id: frame[1]!, type: "note.added" };
184208 }
185209 };
186210 await api(
@@ -230,11 +254,11 @@ test("stands on the security floor", async () => {
230254
231255 test("a body is capped by the bytes read, whatever it claims", async () => {
232256 const response = await api(
233 "/notes",
257 "/deals",
234258 {
235259 method: "POST",
236260 headers: { "content-type": "application/x-www-form-urlencoded" },
237 body: "body=" + "x".repeat(1024 * 1024),
261 body: "address=" + "x".repeat(1024 * 1024),
238262 },
239263 alice,
240264 );
@@ -249,9 +273,9 @@ test("HEAD sees the app up", async () => {
249273
250274 test("refuses a cross-site post", async () => {
251275 const form = new FormData();
252 form.set("body", "from another site");
276 form.set("address", "from another site");
253277 const posted = await api(
254 "/notes",
278 "/deals",
255279 {
256280 method: "POST",
257281 body: form,
@@ -340,3 +364,106 @@ test("what the web expects: robots.txt, and security.txt from the forge that run
340364 );
341365 }
342366 });
367
368 test("a deal's page, its calendar file, and a 404 for one that is not there", async () => {
369 const deals = (await (await api("/api/deals", {}, alice)).json()) as {
370 id: number;
371 address: string;
372 }[];
373 const deal = deals[0]!;
374 // A guest is asked to sign in, and learns nothing of the deal.
375 const guest = await fetch(`${base}/deals/${deal.id}`);
376 expect(guest.status).toBe(401);
377 const guestPage = await guest.text();
378 expect(guestPage).toContain(`/__forge/signin?to=${encodeURIComponent(`/deals/${deal.id}`)}`);
379 expect(guestPage).not.toContain(deal.address.replace("&", "&amp;"));
380 expect((await fetch(`${base}/deals/${deal.id}/ics`)).status).toBe(401);
381 expect((await fetch(`${base}/api/deals`)).status).toBe(401);
382 const page = await (await api(`/deals/${deal.id}`, {}, alice)).text();
383 expect(page).toContain(deal.address.replace("&", "&amp;"));
384 expect(page).toContain(`href="/deals/${deal.id}/ics"`);
385 expect(page).toContain('popover id="sheet-');
386 const ics = await api(`/deals/${deal.id}/ics`, {}, alice);
387 expect(ics.headers.get("content-type")).toContain("text/calendar");
388 expect(ics.headers.get("content-disposition")).toMatch(/^attachment; filename="[a-z0-9-]+\.ics"$/);
389 expect(ics.headers.get("x-content-type-options")).toBe("nosniff");
390 expect(await ics.text()).toContain("BEGIN:VEVENT");
391 expect((await api(`/deals/999999`, {}, alice)).status).toBe(404);
392 expect((await api(`/deals/999999/ics`, {}, alice)).status).toBe(404);
393 const fresh = await (await fetch(`${base}/deals/new`)).text();
394 expect(fresh).toContain("Sign in");
395 const form = await (await api("/deals/new", {}, alice)).text();
396 expect(form).toContain('name="inspection"');
397 expect(form).toContain('value="10"');
398 expect(form).toContain("phase two");
399 });
400
401 test("the clock's forms: mark done, move with a reason, send a reminder, and come back", async () => {
402 const deals = (await (await api("/api/deals", {}, alice)).json()) as {
403 id: number;
404 deadlines: { id: number; due: string; done_at: string | null }[];
405 parties: { id: number }[];
406 }[];
407 const deal = deals.find((d) => d.deadlines.some((x) => x.done_at === null))!;
408 const [first, second] = deal.deadlines.filter((x) => x.done_at === null);
409 const post = (path: string, fields: Record<string, string>, who = alice) => {
410 const body = new FormData();
411 for (const [k, v] of Object.entries(fields)) body.set(k, v);
412 return api(path, { method: "POST", body, redirect: "manual" }, who);
413 };
414 const done = await post(`/deadlines/${first!.id}/done`, { done: "1", to: `/deals/${deal.id}` });
415 expect(done.status).toBe(303);
416 expect(done.headers.get("location")).toBe(`/deals/${deal.id}`);
417 // Where to come back to is ours to say: anywhere else is the clock.
418 const away = await post(`/deadlines/${first!.id}/done`, { done: "0", to: "https://evil.example/" });
419 expect(away.headers.get("location")).toBe("/");
420 const moved = await post(`/deadlines/${second!.id}/move`, { due: "2027-01-04", reason: "Lender extension", to: "/" });
421 expect(moved.status).toBe(303);
422 const guest = await post(`/deadlines/${second!.id}/move`, { due: "2027-01-05", reason: "x" }, {});
423 expect(decodeURIComponent(guest.headers.get("set-cookie") ?? "")).toContain("Sign in");
424 const sent = await post("/reminders", { deadline: String(second!.id), party: String(deal.parties[0]!.id), moment: "before" });
425 expect(sent.status).toBe(303);
426 const after = (await (await api(`/api/deals/${deal.id}`, {}, alice)).json()) as {
427 deadlines: { id: number; due: string; moves: { reason: string }[] }[];
428 sent: { deadline_id: number }[];
429 };
430 const movedRow = after.deadlines.find((x) => x.id === second!.id)!;
431 expect(movedRow.due).toBe("2027-01-04");
432 expect(movedRow.moves.map((m) => m.reason)).toEqual(["Lender extension"]);
433 expect(after.sent.some((s) => s.deadline_id === second!.id)).toBe(true);
434 });
435
436 test("POST /tick answers today's unsent reminders, and changes nothing", async () => {
437 expect((await fetch(base + "/tick", { method: "POST" })).status).toBe(401);
438 const first = await api("/tick", { method: "POST" }, alice);
439 expect(first.status).toBe(200);
440 const body = (await first.json()) as { on: string; reminders: { on: string; sent_at: null }[] };
441 expect(body.on).toMatch(/^\d{4}-\d{2}-\d{2}$/);
442 expect(body.reminders.length).toBeGreaterThan(0);
443 expect(body.reminders.every((r) => r.on === body.on && r.sent_at === null)).toBe(true);
444 const again = (await (await api("/tick", { method: "POST" }, alice)).json()) as typeof body;
445 expect(again.reminders.length).toBe(body.reminders.length);
446 });
447
448 test("the clock is gzipped for whoever asks, and plain for whoever does not", async () => {
449 const zipped = await fetch(base + "/", { headers: { "accept-encoding": "gzip" }, decompress: false } as RequestInit);
450 expect(zipped.headers.get("content-encoding")).toBe("gzip");
451 expect(zipped.headers.get("content-security-policy")).toContain("default-src");
452 const plain = await fetch(base + "/", { headers: { "accept-encoding": "identity" } });
453 expect(plain.headers.get("content-encoding")).toBeNull();
454 expect(await plain.text()).toContain("The clock");
455 });
456
457 test("a form route answers 4xx, never 500, to a body that is not a form", async () => {
458 // Its own person, so the writes earlier tests made are not rationed against it.
459 const formless = as("u8", "formless");
460 const post = (headers: Record<string, string>, body?: string) =>
461 api("/deadlines/1/done", { method: "POST", headers, body, redirect: "manual" }, formless);
462 const none = await post({});
463 expect(none.status).toBe(415);
464 expect(none.headers.get("content-security-policy")).toContain("default-src");
465 expect((await post({ "content-type": "application/json" }, "{}")).status).toBe(415);
466 expect((await post({ "content-type": "multipart/form-data; boundary=x" }, "garbage")).status).toBe(400);
467 for (const path of ["/deals", "/reminders", "/deals/1/deadlines", "/deals/1/parties", "/deadlines/1/move"])
468 expect([path, (await api(path, { method: "POST", redirect: "manual" }, formless)).status]).toEqual([path, 415]);
469 });
src/server.ts +32 −2
@@ -10,6 +10,7 @@
1010 import { openDb } from "./db.ts";
1111 import { dataDir, identityKey, title, where } from "./env.ts";
1212 import { html, text } from "./http.ts";
13 import { follow } from "./live.ts";
1314 import { match } from "./routes.ts";
1415 import { door } from "./security.ts";
1516 import { who } from "./who.ts";
@@ -23,7 +24,13 @@ export interface ServeOptions {
2324
2425 export function serve(options: ServeOptions) {
2526 const db = openDb(options.dataDir);
26 return Bun.serve({
27 // The terminal writes from its own process: when the file changes under
28 // us, every open page hears it, as if the change were made here.
29 const unfollow = follow(
30 () => db.query<{ data_version: number }, []>("PRAGMA data_version").get()!.data_version,
31 "deal.changed",
32 );
33 const server = Bun.serve({
2734 port: options.port,
2835 hostname: options.hostname ?? "127.0.0.1",
2936 // A connection that says nothing for a minute is dropped. The event
@@ -52,7 +59,7 @@ export function serve(options: ServeOptions) {
5259 who: me,
5360 params: found.params,
5461 });
55 return head(request, response);
62 return head(request, await squeeze(request, response));
5663 },
5764 // A bug answers with the floor and nothing else: never the runtime's
5865 // own error page, which carries source and paths, and never without
@@ -63,6 +70,29 @@ export function serve(options: ServeOptions) {
6370 return html("<h1>Something went wrong</h1>", 500);
6471 },
6572 });
73 const stop = server.stop.bind(server);
74 server.stop = (closeActiveConnections?: boolean) => {
75 unfollow();
76 return stop(closeActiveConnections);
77 };
78 return server;
79 }
80
81 // A page is mostly repeated markup: gzipped, the clock is a tenth the size.
82 // Only HTML, only when asked for, and only past a size worth the trouble.
83 async function squeeze(request: Request, response: Response): Promise<Response> {
84 if (
85 !(response.headers.get("content-type") ?? "").startsWith("text/html") ||
86 !/\bgzip\b/.test(request.headers.get("accept-encoding") ?? "")
87 )
88 return response;
89 const body = new Uint8Array(await response.arrayBuffer());
90 if (body.byteLength < 2048)
91 return new Response(body, { status: response.status, headers: response.headers });
92 const headers = new Headers(response.headers);
93 headers.set("content-encoding", "gzip");
94 headers.append("vary", "accept-encoding");
95 return new Response(Bun.gzipSync(body), { status: response.status, headers });
6696 }
6797
6898 // HEAD is GET without the body: a health check sees the app up.
src/terminal.test.ts added +147
@@ -0,0 +1,147 @@
1 /**
2 * The terminal is a second door: each key, pressed against a real
3 * database, does what the page's button does, through the same action.
4 */
5 import { expect, test } from "bun:test";
6 import { mkdtempSync } from "node:fs";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { addDays, today } from "./dates.ts";
10 import { createDeal, getDeal, listDeals, type DealView } from "./deals.ts";
11 import { openDb } from "./db.ts";
12 import { terminal, type Terminal } from "./terminal.ts";
13 import type { Who } from "./who.ts";
14
15 const db = openDb(mkdtempSync(join(tmpdir(), "app-terminal-")));
16 const alice: Who = { role: "user", id: "u1", name: "alice" };
17 const context = { title: "deal-clock", where: "test", agent: { name: "Dana", brokerage: "HP" } };
18 const plain = (s: string): string => s.replace(/\x1b\[[0-9;]*m/g, "");
19 const lines = (t: Terminal): string[] => t.screen().map(plain);
20 const under = (t: Terminal): string => lines(t).find((l) => l.startsWith("▸")) ?? "";
21 /** Move the cursor to the row that says `text`. */
22 function goTo(t: Terminal, text: string): void {
23 t.press("d");
24 for (let i = 0; i < 200 && !under(t).includes(text); i++) t.press("j");
25 expect(under(t)).toContain(text);
26 }
27 const press = (t: Terminal, ...chunks: string[]) => chunks.forEach((c) => t.press(c));
28
29 const made = createDeal(db, alice, {
30 address: "12 Elm St",
31 buyer: "Ann Buyer",
32 seller: "Sam Seller",
33 contractDate: today(),
34 closingDate: addDays(today(), 45),
35 });
36 if (!made.ok) throw new Error(made.message);
37 const id = made.value.id;
38 const deal = (): DealView => {
39 const got = getDeal(db, alice, { id });
40 if (!got.ok) throw new Error(got.message);
41 return got.value;
42 };
43 const date = (kind: string) => deal().deadlines.find((d) => d.kind === kind)!;
44
45 test("x marks the date under the cursor done; h shows done dates; u reopens", () => {
46 const t = terminal(db, alice, context);
47 goTo(t, "Inspection period ends — 12 Elm St");
48 t.press("x");
49 expect(date("inspection").done_at).not.toBeNull();
50 expect(lines(t).join("\n")).toContain("Done: Inspection period ends, 12 Elm St.");
51 expect(lines(t).some((l) => l.includes("Inspection period ends — 12 Elm St"))).toBe(false);
52 t.press("h");
53 goTo(t, "Inspection period ends — 12 Elm St");
54 t.press("u");
55 expect(date("inspection").done_at).toBeNull();
56 });
57
58 test("m moves one date with a reason, and nothing else; esc cancels", () => {
59 const t = terminal(db, alice, context);
60 const before = deal().deadlines.map((d) => [d.id, d.due] as const);
61 goTo(t, "Appraisal due — 12 Elm St");
62 press(t, "m", "2099", "\x1b");
63 expect(lines(t).join("\n")).toContain("Cancelled.");
64 expect(date("appraisal").moves.length).toBe(0);
65 const to = addDays(today(), 25);
66 press(t, "m", to, "\r", "Lender asked for more time", "\r");
67 const after = deal();
68 expect(after.deadlines.map((d) => [d.id, d.due]).sort()).toEqual(
69 before.map(([i, d]) => [i, i === date("appraisal").id ? to : d]).sort(),
70 );
71 expect(date("appraisal").moves.map((m) => m.reason)).toEqual(["Lender asked for more time"]);
72 // A bad date is the action's to refuse, and says so.
73 goTo(t, "Financing contingency ends — 12 Elm St");
74 press(t, "m", "soon\r", "x\r");
75 expect(lines(t).join("\n")).toContain("The new date is a date");
76 });
77
78 test("o opens a deal; a adds a date, p a party; D removes it after a yes", () => {
79 const t = terminal(db, alice, context);
80 goTo(t, "Closing — 12 Elm St");
81 t.press("o");
82 expect(lines(t)).toContain("12 Elm St");
83 press(t, "a", "HOA review ends\r", `${addDays(today(), 5)}\r`, "buyer\r", "\r");
84 expect(deal().deadlines.some((d) => d.label === "HOA review ends" && d.kind === "custom")).toBe(true);
85 press(t, "p", "lender\r", "Lee Lender\r", "[email protected]\r");
86 expect(deal().parties.some((p) => p.role === "lender" && p.contact === "[email protected]")).toBe(true);
87 expect(lines(t).join("\n")).toContain("[email protected]");
88 press(t, "D", "no\r");
89 expect(lines(t).join("\n")).toContain("Kept.");
90 expect(getDeal(db, alice, { id }).ok).toBe(true);
91 const other = createDeal(db, alice, {
92 address: "99 Gone Rd",
93 buyer: "B",
94 seller: "S",
95 contractDate: today(),
96 closingDate: addDays(today(), 30),
97 });
98 if (!other.ok) throw new Error(other.message);
99 goTo(t, "Closing — 99 Gone Rd");
100 press(t, "o", "D", "yes\r");
101 expect(getDeal(db, alice, { id: other.value.id }).ok).toBe(false);
102 expect(lines(t).join("\n")).toContain("Removed 99 Gone Rd.");
103 });
104
105 test("r shows today's reminders; enter reads a draft; s sends it", () => {
106 const t = terminal(db, alice, context);
107 t.press("r");
108 const row = under(t);
109 expect(row).toMatch(/\b(to send|late)\b/);
110 t.press("\r");
111 expect(lines(t).join("\n")).toContain("Hi ");
112 t.press("s");
113 expect(lines(t).join("\n")).toContain("(simulated)");
114 // A late reminder, once sent, leaves today's list; one due today stays, marked sent.
115 expect(under(t)).not.toBe(row);
116 const sent = db.query<{ n: number }, []>("SELECT count(*) AS n FROM reminder").get()!.n;
117 expect(sent).toBe(1);
118 });
119
120 test("n opens a deal from five answers, and shows it", () => {
121 const t = terminal(db, alice, context);
122 press(t, "n", "31 Birch Row\r", "Kim Buyer\r", "Lou Seller\r", `${today()}\r`, `${addDays(today(), 40)}\r`);
123 const listed = listDeals(db, alice);
124 if (!listed.ok) throw new Error(listed.message);
125 const made = listed.value.find((d) => d.address === "31 Birch Row");
126 expect(made?.parties.map((p) => p.name)).toEqual(["Kim Buyer", "Lou Seller"]);
127 expect(made?.deadlines.length).toBe(6);
128 expect(lines(t).join("\n")).toContain("Opened 31 Birch Row");
129 expect(lines(t)).toContain("31 Birch Row");
130 // A bad answer is the action's to refuse, and nothing is opened.
131 press(t, "d", "n", "x\r", "A\r", "B\r", "soon\r", "later\r");
132 expect(lines(t).join("\n")).toContain("The address is 3 to 200 characters.");
133 });
134
135 test("a guest sees no deals, and is asked to sign in before anything — n included", () => {
136 const t = terminal(db, { role: "anon" }, context);
137 expect(lines(t).join("\n")).toContain("Sign in to see deals.");
138 expect(lines(t).some((l) => l.includes("12 Elm St"))).toBe(false);
139 t.press("n");
140 expect(lines(t).join("\n")).toContain("Sign in to open a deal.");
141 expect(lines(t).join("\n")).not.toContain("Property address");
142 t.press("x");
143 expect(date("closing").done_at).toBeNull();
144 // Keys that arrive together are pressed one by one.
145 t.press("rdq");
146 expect(t.done).toBe(true);
147 });
src/terminal.ts added +330
@@ -0,0 +1,330 @@
1 /**
2 * The clock as a terminal: keys in, a screen of lines out, over the same
3 * actions as the page, as the account at the keyboard. `tty.ts` wires it to
4 * a pty; a test presses keys and reads the screen. Three views:
5 *
6 * dates every open date of every deal, soonest first (h shows done ones)
7 * reminders what goes out today; enter reads a draft, s sends it
8 * deal one deal's dates and parties; a adds a date, p a party, D removes it
9 *
10 * On a date (dates or deal view): x marks it done, u reopens it, m moves it
11 * (a new date, then the reason). o or enter opens its deal; n opens a new
12 * deal (address, buyer, seller, contract and closing dates); d, r and b move
13 * between views; esc cancels a prompt; q leaves.
14 */
15
16 import type { Database } from "bun:sqlite";
17 import { isDate, relative, spoken, today, urgency, type Urgency } from "./dates.ts";
18 import {
19 addDeadline,
20 addParty,
21 canChange,
22 createDeal,
23 deleteDeal,
24 getDeal,
25 listDeals,
26 markDone,
27 mayOpen,
28 moveDeadline,
29 sendReminder,
30 type DealView,
31 type DeadlineView,
32 } from "./deals.ts";
33 import { PARTY_LABEL, PARTY_ROLES } from "./deadlines.ts";
34 import { drafts, MOMENT_LABEL, type Agent, type Draft } from "./reminders.ts";
35 import type { Result } from "./result.ts";
36 import type { Who } from "./who.ts";
37
38 const esc = "\x1b[";
39 const dim = (s: string): string => `${esc}2m${s}${esc}0m`;
40 const bold = (s: string): string => `${esc}1m${s}${esc}0m`;
41 const COLOUR: Readonly<Record<Urgency, string>> = { overdue: "31", soon: "33", later: "36", done: "2" };
42 const tint = (u: Urgency, s: string): string => `${esc}${COLOUR[u]}m${s}${esc}0m`;
43
44 type View = "dates" | "reminders" | "deal";
45 interface Row {
46 readonly deal: DealView;
47 readonly date: DeadlineView;
48 }
49 interface Prompt {
50 readonly steps: readonly string[];
51 readonly answers: string[];
52 text: string;
53 readonly finish: (answers: readonly string[]) => string;
54 }
55
56 export interface Terminal {
57 /** One chunk from the keyboard: a key, an arrow, or pasted text. */
58 press(chunk: string): void;
59 /** The screen, as lines (ANSI-coloured). */
60 screen(): string[];
61 readonly done: boolean;
62 }
63
64 export function terminal(
65 db: Database,
66 me: Who,
67 context: { title: string; where: string; ssh?: string | undefined; agent: Agent; on?: () => string },
68 ): Terminal {
69 const on = context.on ?? today;
70 let view: View = "dates";
71 let cursor = 0;
72 let dealId: number | undefined;
73 let showDone = false;
74 let reading: number | undefined;
75 let prompt: Prompt | undefined;
76 let said = "";
77 let done = false;
78
79 const deals = (): DealView[] => {
80 const listed = listDeals(db, me);
81 return listed.ok ? listed.value : [];
82 };
83 const openDeal = (): DealView | undefined => {
84 if (dealId === undefined) return undefined;
85 const got = getDeal(db, me, { id: dealId });
86 return got.ok ? got.value : undefined;
87 };
88 const dateRows = (): Row[] => {
89 if (view === "deal") {
90 const deal = openDeal();
91 return deal === undefined ? [] : deal.deadlines.map((date) => ({ deal, date }));
92 }
93 return deals()
94 .flatMap((deal) =>
95 deal.deadlines.filter((d) => showDone || d.done_at === null).map((date) => ({ deal, date })),
96 )
97 .sort((a, b) => a.date.due.localeCompare(b.date.due) || a.date.id - b.date.id);
98 };
99 /** Today's reminders: what goes out today, and what should have and has not, for dates still ahead. */
100 const reminderRows = (): { deal: DealView; draft: Draft }[] => {
101 const day = on();
102 return deals().flatMap((deal) =>
103 drafts(deal, context.agent)
104 .filter((r) => r.on === day || (r.on < day && r.sent_at === null && r.due >= day))
105 .map((draft) => ({ deal, draft })),
106 );
107 };
108 const rowCount = (): number => (view === "reminders" ? reminderRows().length : dateRows().length);
109
110 const report = <T>(result: Result<T>, success: string): string => (result.ok ? success : result.message);
111 /** Only someone who may work the deal is asked to type anything. */
112 const ask = (deal: DealView, steps: string[], finish: Prompt["finish"]): void => {
113 if (!canChange(me, deal)) {
114 said = me.role === "anon" ? "Sign in to change a deal." : "You may not change this deal.";
115 return;
116 }
117 prompt = { steps, answers: [], text: "", finish };
118 };
119
120 function onDate(key: string): boolean {
121 const row = dateRows()[cursor];
122 if (!["x", "u", "m", "o", "\r"].includes(key)) return false;
123 if (row === undefined) {
124 said = "No date here.";
125 return true;
126 }
127 const { deal, date } = row;
128 if (key === "x") said = report(markDone(db, me, { id: date.id, done: true }), `Done: ${date.label}, ${deal.address}.`);
129 if (key === "u") said = report(markDone(db, me, { id: date.id, done: false }), `Reopened: ${date.label}, ${deal.address}.`);
130 if (key === "m")
131 ask(deal, [`New date for ${date.label} (YYYY-MM-DD, now ${date.due})`, "Why it moved"], ([due, reason]) =>
132 report(moveDeadline(db, me, { id: date.id, due, reason }), `Moved ${date.label} to ${isDate(due) ? spoken(due!) : due}; nothing else moved.`),
133 );
134 if ((key === "o" || key === "\r") && view === "dates") {
135 view = "deal";
136 dealId = deal.id;
137 cursor = 0;
138 }
139 return true;
140 }
141
outdated

The deal view offers a/p/D and the date list x/u/m/o, but no key opens a deal: createDeal is never called from the terminal, though it is the page's main write (New deal). Add n → address, buyer, seller, contract date, closing date → createDeal, plus a test in terminal.test.ts that presses it.

142 function onDeal(key: string): boolean {
143 const deal = openDeal();
144 if (deal === undefined || !["a", "p", "D"].includes(key)) return false;
145 if (key === "a")
146 ask(deal, ["What is the date (e.g. HOA review ends)", "Date (YYYY-MM-DD)", `Owed by (${PARTY_ROLES.join(", ")})`, "Details (optional)"], ([label, due, owes, what]) =>
147 report(addDeadline(db, me, { dealId: deal.id, label, due, owes, what }), `Added ${label}.`),
148 );
149 if (key === "p")
150 ask(deal, [`Role (${PARTY_ROLES.join(", ")})`, "Name", "Email or phone (optional)"], ([role, name, contact]) =>
151 report(addParty(db, me, { dealId: deal.id, role, name, contact }), `Added ${name}.`),
152 );
153 if (key === "D") {
154 prompt = {
155 steps: [`Type yes to remove ${deal.address} and every date on it`],
156 answers: [],
157 text: "",
158 finish: ([yes]) => {
159 if (yes !== "yes") return "Kept.";
160 const removed = deleteDeal(db, me, { id: deal.id });
161 if (!removed.ok) return removed.message;
162 view = "dates";
163 dealId = undefined;
164 cursor = 0;
165 return `Removed ${deal.address}.`;
166 },
167 };
168 }
169 return true;
170 }
171
172 function onReminder(key: string): boolean {
173 if (key !== "\r" && key !== "s") return false;
174 const row = reminderRows()[cursor];
175 if (row === undefined) {
176 said = "No reminder here.";
177 return true;
178 }
179 const { draft } = row;
180 if (key === "\r") reading = reading === cursor ? undefined : cursor;
181 if (key === "s")
182 said = report(
183 sendReminder(db, me, { deadlineId: draft.deadline_id, partyId: draft.party_id, moment: draft.moment }),
184 `Sent to ${draft.party_name} (simulated): ${draft.label}, ${draft.address}.`,
185 );
186 return true;
187 }
188
189 function typing(chunk: string): void {
190 const p = prompt!;
191 if (chunk === "\x1b" || chunk === "\x03") {
192 prompt = undefined;
193 said = "Cancelled.";
194 return;
195 }
196 if (chunk === "\x7f" || chunk === "\b") {
197 p.text = p.text.slice(0, -1);
198 return;
199 }
200 if (chunk.startsWith("\x1b")) return;
201 for (const ch of chunk) {
202 if (ch === "\r" || ch === "\n") {
203 p.answers.push(p.text.trim());
204 p.text = "";
205 if (p.answers.length === p.steps.length) {
206 prompt = undefined;
207 said = p.finish(p.answers);
208 return;
209 }
210 } else if (ch >= " " && p.text.length < 200) p.text += ch;
211 }
212 }
213
214 function press(chunk: string): void {
215 if (prompt !== undefined) return typing(chunk);
216 // Keys typed fast, or pasted, arrive together: each is its own press, and
217 // once one opens a prompt the rest are typed into it.
218 if (chunk.length > 1 && !chunk.startsWith("\x1b")) {
219 for (const ch of chunk) press(ch);
220 return;
221 }
222 said = "";
223 const key = chunk === "\x1b[B" ? "j" : chunk === "\x1b[A" ? "k" : chunk === "\n" ? "\r" : chunk;
224 if (key === "q" || key === "\x03") {
225 done = true;
226 return;
227 }
228 if (key === "j") cursor = Math.min(cursor + 1, Math.max(0, rowCount() - 1));
229 else if (key === "k") cursor = Math.max(cursor - 1, 0);
230 else if (key === "d" || key === "b" || key === "\x1b") {
231 view = "dates";
232 cursor = 0;
233 } else if (key === "r") {
234 view = "reminders";
235 cursor = 0;
236 reading = undefined;
237 } else if (key === "n") {
238 const may = mayOpen(me);
239 if (!may.ok) said = may.message;
240 else
241 prompt = {
242 steps: ["Property address", "Buyer", "Seller", "Contract date (YYYY-MM-DD)", "Closing date (YYYY-MM-DD)"],
243 answers: [],
244 text: "",
245 finish: ([address, buyer, seller, contractDate, closingDate]) => {
246 const made = createDeal(db, me, { address, buyer, seller, contractDate, closingDate });
247 if (!made.ok) return made.message;
248 view = "deal";
249 dealId = made.value.id;
250 cursor = 0;
251 return `Opened ${made.value.address}: every date is on the clock.`;
252 },
253 };
254 } else if (key === "h" && view === "dates") {
255 showDone = !showDone;
256 cursor = 0;
257 } else if (view === "reminders") onReminder(key);
258 else if (!(view === "deal" && onDeal(key))) onDate(key);
259 cursor = Math.min(cursor, Math.max(0, rowCount() - 1));
260 }
261
262 const dateLine = (row: Row, i: number, withDeal: boolean): string => {
263 const { date, deal } = row;
264 const u = urgency(date.due, on(), date.done_at !== null);
265 const when = tint(u, `${spoken(date.due).padEnd(12)} ${(date.done_at === null ? relative(date.due, on()) : "done").padEnd(12)}`);
266 const text = withDeal ? `${date.label} — ${deal.address}` : date.label;
267 const moved = date.moves.length > 0 ? dim(` moved: ${date.moves.at(-1)!.reason}`) : "";
268 return `${i === cursor ? "▸" : " "} ${when} ${i === cursor ? bold(text) : text}${moved}`;
269 };
270
271 function screen(): string[] {
272 const day = on();
273 const all = deals();
274 const lines = [
275 `${bold(context.title)} ${context.agent.name}, ${context.agent.brokerage} ${dim(context.where)} ${dim(me.role === "anon" ? "guest" : `${me.name}${me.role === "admin" ? " (admin)" : ""}`)}`,
276 context.ssh === undefined ? dim("The terminal is off.") : dim(`connect: ${context.ssh}`),
277 `${spoken(day)} · ${all.length} deals · ${view === "dates" ? bold("[d] dates") : "[d] dates"} · ${view === "reminders" ? bold("[r] reminders today") : "[r] reminders today"}`,
278 "",
279 ];
280 if (view === "dates") {
281 const rows = dateRows();
282 const listed = listDeals(db, me);
283 if (!listed.ok) lines.push(listed.message);
284 else if (rows.length === 0) lines.push(dim("Nothing open. Every date is done."));
285 rows.forEach((row, i) => lines.push(dateLine(row, i, true)));
286 } else if (view === "deal") {
287 const deal = openDeal();
288 if (deal === undefined) lines.push(dim("That deal is gone."));
289 else {
290 lines.push(bold(deal.address), dim(`under contract ${spoken(deal.contract_date)} · closes ${spoken(deal.closing)}, ${relative(deal.closing, day)}`), "");
291 deal.deadlines.forEach((date, i) => lines.push(dateLine({ deal, date }, i, false)));
292 lines.push("", bold("Parties"));
293 for (const p of deal.parties)
294 lines.push(` ${PARTY_LABEL[p.role].padEnd(14)} ${p.name}${p.contact === "" ? "" : dim(` ${p.contact}`)}`);
295 }
296 } else {
297 const rows = reminderRows();
298 if (rows.length === 0) lines.push(dim("Nothing goes out today."));
299 rows.forEach(({ draft }, i) => {
300 const state = draft.sent_at !== null ? dim("sent") : draft.on < day ? tint("overdue", "late") : tint("soon", "to send");
301 const text = `${draft.party_name} (${PARTY_LABEL[draft.party_role].toLowerCase()}) · ${draft.label}, ${draft.address} · ${MOMENT_LABEL[draft.moment].toLowerCase()}`;
302 lines.push(`${i === cursor ? "▸" : " "} ${state.padEnd(16)} ${i === cursor ? bold(text) : text}`);
303 if (reading === i)
304 lines.push("", ` ${bold(draft.subject)}`, ...draft.body.split("\n").map((l) => ` ${l}`), "");
305 });
306 }
307 lines.push("");
308 if (prompt !== undefined)
309 lines.push(`${prompt.steps[prompt.answers.length]}: ${prompt.text}${esc}7m ${esc}0m`, dim("enter to go on · esc to cancel"));
310 else {
311 if (said !== "") lines.push(said);
312 const keys =
313 view === "reminders"
314 ? "j/k move · enter read · s send · d dates · q quit"
315 : view === "deal"
316 ? "j/k move · x done · u reopen · m move · a add date · p add party · D remove · b back · q quit"
317 : `j/k move · x done · u reopen · m move · o open deal · n new deal · h ${showDone ? "hide" : "show"} done · r reminders · q quit`;
318 lines.push(dim(me.role === "anon" ? `${keys} · sign in with a key the forge knows to change anything` : keys));
319 }
320 return lines;
321 }
322
323 return {
324 press,
325 screen,
326 get done() {
327 return done;
328 },
329 };
330 }
src/tty.ts +13 −97
@@ -1,115 +1,31 @@
11 /**
2 * The app in a terminal. The forge runs this on a pty when someone
3 * `ssh`es to the app, over the same data as the page and through the same
4 * actions, as the account at the keyboard. j/k move, a adds, d removes the
5 * note under the cursor, q leaves. Plain ANSI, no dependencies.
2 * The app on a pty. The forge runs this when someone `ssh`es to the app, as
3 * the account at the keyboard; everything it can do is `terminal.ts`, over
4 * the same data and actions as the page. A write here reaches web viewers
5 * live: the server notices the database changed (`follow` in `live.ts`).
66 */
77
8 import {
9 addNote,
10 canDelete,
11 deleteNote,
12 listNotes,
13 type Note,
14 } from "./actions.ts";
158 import { openDb } from "./db.ts";
16 import { ssh, title, where } from "./env.ts";
9 import { agent, ssh, title, where } from "./env.ts";
10 import { terminal } from "./terminal.ts";
1711 import { whoAtTty } from "./who.ts";
1812
19 const db = openDb();
20 const me = whoAtTty();
2113 const esc = "\x1b[";
22 const dim = (s: string): string => `${esc}2m${s}${esc}0m`;
23 const bold = (s: string): string => `${esc}1m${s}${esc}0m`;
24 const out = (s: string): void => {
25 process.stdout.write(s);
14 const term = terminal(openDb(), whoAtTty(), { title, where, ssh, agent });
15 const draw = (): void => {
16 process.stdout.write(`${esc}2J${esc}H${term.screen().join("\r\n")}`);
2617 };
2718
28 let cursor = 0;
29 let typing: string | undefined;
30 let said = "";
31
32 const notes = (): Note[] => {
33 const listed = listNotes(db, me);
34 return listed.ok ? listed.value : [];
35 };
36
37 function draw(): void {
38 const rows = notes();
39 const lines = [
40 `${bold(title)} ${dim(where)} ${dim(me.role === "anon" ? "guest" : `${me.name}${me.role === "admin" ? " (admin)" : ""}`)}`,
41 ssh === undefined ? "" : dim(`connect: ${ssh}`),
42 "",
43 ];
44 if (rows.length === 0)
45 lines.push(
46 dim(
47 me.role === "anon"
48 ? "No notes yet."
49 : "No notes yet. Press a to add one.",
50 ),
51 );
52 rows.forEach((note, i) => {
53 const body = i === cursor ? bold(note.body) : note.body;
54 lines.push(
55 `${i === cursor ? "▸" : " "} ${body} ${dim(`${note.author_name} · ${note.created_at.slice(0, 16).replace("T", " ")}`)}`,
56 );
57 });
58 lines.push("");
59 if (typing !== undefined) lines.push(`New note: ${typing}${esc}7m ${esc}0m`);
60 else if (said !== "") lines.push(said);
61 else
62 lines.push(
63 dim(
64 me.role === "anon"
65 ? "j/k move · q quit · sign in with a key the forge knows to add"
66 : "j/k move · a add · d delete · q quit",
67 ),
68 );
69 out(`${esc}2J${esc}H${lines.join("\r\n")}`);
70 }
71
7219 process.stdin.setRawMode?.(true);
7320 process.stdin.resume();
7421 process.stdin.setEncoding("utf8");
7522 draw();
76 process.stdin.on("data", (key: string) => {
77 said = "";
78 if (typing !== undefined) {
79 if (key === "\r") {
80 const added = addNote(db, me, { body: typing });
81 if (!added.ok) said = added.message;
82 typing = undefined;
83 cursor = 0;
84 } else if (key === "\x1b") typing = undefined;
85 else if (key === "\x7f") typing = typing.slice(0, -1);
86 else if (key >= " ") typing += key;
87 draw();
88 return;
89 }
90 if (key === "q" || key === "\x03") {
91 out(`${esc}2J${esc}H`);
23 process.stdin.on("data", (chunk: string) => {
24 term.press(chunk);
25 if (term.done) {
26 process.stdout.write(`${esc}2J${esc}H`);
9227 process.exit(0);
9328 }
94 const rows = notes();
95 if (key === "j" || key === "\x1b[B")
96 cursor = Math.min(cursor + 1, Math.max(0, rows.length - 1));
97 if (key === "k" || key === "\x1b[A") cursor = Math.max(cursor - 1, 0);
98 if (key === "a") {
99 if (me.role === "anon") said = "Sign in to add a note.";
100 else typing = "";
101 }
102 if (key === "d") {
103 const note = rows[cursor];
104 if (note === undefined) said = "Nothing to remove.";
105 else if (!canDelete(me, note))
106 said = "Only the author or an admin can remove a note.";
107 else {
108 const removed = deleteNote(db, me, { id: note.id });
109 if (!removed.ok) said = removed.message;
110 cursor = Math.min(cursor, Math.max(0, rows.length - 2));
111 }
112 }
11329 draw();
11430 });
11531 process.stdout.on("resize", draw);
static/app.css +529 −5
@@ -15,7 +15,7 @@ body {
1515 font: var(--text-base) / var(--leading-body) var(--font-sans);
1616 }
1717 .page {
18 max-width: 40rem;
18 max-width: 64rem;
1919 margin: 0 auto;
2020 padding: var(--space-5) var(--space-4) var(--space-6);
2121 }
@@ -27,13 +27,34 @@ body {
2727 gap: var(--space-3) var(--space-4);
2828 margin-bottom: var(--space-5);
2929 }
30 h1 {
30 h1,
31 h2 {
3132 margin: 0;
32 font-size: var(--text-xl);
33 font-weight: 650;
34 letter-spacing: -0.01em;
33 font-family: var(--font-display);
34 font-weight: 600;
35 letter-spacing: -0.005em;
3536 line-height: var(--leading-tight);
3637 }
38 h1 {
39 font-size: var(--text-2xl);
40 }
41 h2 {
42 font-size: var(--text-lg);
43 margin-bottom: var(--space-3);
44 }
45 h3 {
46 margin: var(--space-4) 0 var(--space-2);
47 font-size: var(--text-sm);
48 font-weight: 650;
49 text-transform: uppercase;
50 letter-spacing: 0.06em;
51 color: var(--color-muted);
52 }
53 h4 {
54 margin: var(--space-3) 0 var(--space-1);
55 font-size: var(--text-sm);
56 font-weight: 650;
57 }
3758 p {
3859 margin: 0;
3960 }
@@ -207,3 +228,506 @@ footer code {
207228 animation: none;
208229 }
209230 }
231
232 /* The header: whose deals these are. */
233 .brand {
234 display: flex;
235 align-items: center;
236 gap: var(--space-3);
237 color: var(--color-fg);
238 text-decoration: none;
239 min-height: var(--size-tap);
240 }
241 .brand b {
242 display: block;
243 font-family: var(--font-display);
244 font-size: var(--text-lg);
245 font-weight: 600;
246 line-height: var(--leading-tight);
247 }
248 .brand small {
249 display: block;
250 color: var(--color-muted);
251 font-size: var(--text-sm);
252 }
253 /* A clock face, drawn: a ring and two hands. */
254 .brand-mark {
255 position: relative;
256 width: 2.25rem;
257 height: 2.25rem;
258 flex: none;
259 border: 2px solid var(--color-accent);
260 border-radius: var(--radius-pill);
261 }
262 .brand-mark::before,
263 .brand-mark::after {
264 content: "";
265 position: absolute;
266 left: calc(50% - 1px);
267 bottom: 50%;
268 width: 2px;
269 background: var(--color-accent);
270 transform-origin: bottom center;
271 border-radius: 1px;
272 }
273 .brand-mark::before {
274 height: 38%;
275 }
276 .brand-mark::after {
277 height: 28%;
278 transform: rotate(120deg);
279 }
280 .small {
281 font-size: var(--text-sm);
282 }
283 .crumb {
284 margin-bottom: var(--space-3);
285 }
286 .crumb a {
287 display: inline-flex;
288 align-items: center;
289 min-height: var(--size-tap);
290 }
291 .intro {
292 display: flex;
293 flex-wrap: wrap;
294 justify-content: space-between;
295 align-items: flex-end;
296 gap: var(--space-3);
297 margin-bottom: var(--space-4);
298 }
299 .summary {
300 color: var(--color-muted);
301 margin-top: var(--space-1);
302 }
303 .u-overdue {
304 color: var(--color-overdue);
305 }
306 .u-soon {
307 color: var(--color-soon);
308 }
309 .card h2 .muted {
310 font-family: var(--font-sans);
311 font-size: var(--text-sm);
312 font-weight: 400;
313 }
314
315 /* The clock: lanes over a scrolling time axis, today a line through all of them. */
316 .clock {
317 padding: 0;
318 overflow: hidden;
319 }
320 .clock-scroll {
321 overflow-x: auto;
322 overscroll-behavior-x: contain;
323 }
324 .clock-inner {
325 position: relative;
326 min-width: 100%;
327 padding-bottom: var(--space-3);
328 }
329 .axis {
330 position: absolute;
331 inset: 0;
332 pointer-events: none;
333 }
334 .tick {
335 position: absolute;
336 top: 0;
337 padding: var(--space-2) 0 0 var(--space-1);
338 border-left: 1px solid var(--color-line);
339 font-size: var(--text-xs);
340 font-weight: 650;
341 font-variant-numeric: tabular-nums;
342 color: var(--color-muted);
343 white-space: nowrap;
344 }
345 .weekend {
346 position: absolute;
347 top: 0;
348 bottom: 0;
349 width: var(--size-day);
350 background: var(--color-lane);
351 }
352 .today {
353 position: absolute;
354 top: 0;
355 bottom: 0;
356 width: 2px;
357 margin-left: -1px;
358 background: var(--color-fg);
359 }
360 .today span {
361 position: absolute;
362 top: var(--space-5);
363 left: 50%;
364 transform: translateX(-50%);
365 padding: 0 var(--space-2);
366 font-size: var(--text-xs);
367 font-weight: 650;
368 color: var(--color-bg);
369 background: var(--color-fg);
370 border-radius: var(--radius-pill);
371 white-space: nowrap;
372 }
373 .lanes {
374 position: relative;
375 list-style: none;
376 margin: 0;
377 padding: calc(var(--space-6) + var(--space-5)) 0 0;
378 }
379 .lane {
380 border-top: 1px solid var(--color-line);
381 padding: var(--space-2) 0 var(--space-3);
382 }
383 .lane-head {
384 position: sticky;
385 left: 0;
386 z-index: 3;
387 display: inline-block;
388 max-width: min(36rem, 100vw - 3rem);
389 padding: var(--space-1) var(--space-4);
390 background: var(--color-surface);
391 border-radius: 0 var(--radius-pill) var(--radius-pill) 0;
392 }
393 .lane-head a {
394 font-family: var(--font-display);
395 font-weight: 600;
396 font-size: var(--text-lg);
397 color: var(--color-fg);
398 text-decoration: none;
399 }
400 .lane-head a:hover {
401 text-decoration: underline;
402 }
403 .lane-head small {
404 display: block;
405 font-size: var(--text-sm);
406 }
407 .track {
408 position: relative;
409 margin-top: var(--space-2);
410 }
411 .marker {
412 position: absolute;
413 display: inline-flex;
414 align-items: center;
415 gap: var(--space-1);
416 min-height: var(--size-tap);
417 padding: 0 var(--space-2);
418 font: inherit;
419 font-size: var(--text-sm);
420 font-weight: 600;
421 white-space: nowrap;
422 border: 1px solid transparent;
423 border-radius: var(--radius-pill);
424 cursor: pointer;
425 z-index: 1;
426 /* The marker's dot sits on its day. */
427 margin-left: calc(var(--size-day) / 2 - var(--space-2) - 0.3rem);
428 }
429 .marker:hover,
430 .marker:focus-visible {
431 z-index: 4;
432 border-color: currentColor;
433 }
434 .marker[data-u="later"],
435 .badge[data-u="later"] {
436 color: var(--color-accent);
437 background: var(--color-later-bg);
438 }
439 .marker[data-u="soon"],
440 .badge[data-u="soon"] {
441 color: var(--color-soon);
442 background: var(--color-soon-bg);
443 }
444 .marker[data-u="overdue"],
445 .badge[data-u="overdue"] {
446 color: var(--color-overdue);
447 background: var(--color-overdue-bg);
448 }
449 .marker[data-u="done"],
450 .badge[data-u="done"] {
451 color: var(--color-muted);
452 background: var(--color-done-bg);
453 }
454 .marker[data-u="done"] {
455 text-decoration: line-through;
456 }
457 .dot {
458 width: 0.6rem;
459 height: 0.6rem;
460 flex: none;
461 border-radius: var(--radius-pill);
462 background: currentColor;
463 }
464 .dot[data-u="later"] {
465 background: var(--color-accent);
466 }
467 .dot[data-u="soon"] {
468 background: var(--color-soon);
469 }
470 .dot[data-u="overdue"] {
471 background: var(--color-overdue);
472 }
473 .dot[data-u="done"] {
474 background: var(--color-done);
475 }
476 .legend {
477 display: flex;
478 flex-wrap: wrap;
479 gap: var(--space-2) var(--space-4);
480 list-style: none;
481 margin: 0;
482 padding: var(--space-3) var(--space-4);
483 border-top: 1px solid var(--color-line);
484 font-size: var(--text-sm);
485 color: var(--color-muted);
486 }
487 .legend li {
488 display: inline-flex;
489 align-items: center;
490 gap: var(--space-2);
491 }
492 .badge {
493 display: inline-block;
494 padding: 0.05rem 0.55rem;
495 font-size: var(--text-xs);
496 font-weight: 650;
497 border-radius: var(--radius-pill);
498 vertical-align: 0.1em;
499 }
500
501 /* A date, opened. */
502 .sheet {
503 width: min(32rem, 100vw - 2rem);
504 max-height: min(42rem, 100vh - 2rem);
505 overflow-y: auto;
506 padding: var(--space-4) var(--space-5) var(--space-5);
507 color: var(--color-fg);
508 background: var(--color-surface);
509 border: 1px solid var(--color-line);
510 border-radius: var(--radius-md);
511 box-shadow: 0 16px 48px var(--color-shadow);
512 }
513 .sheet::backdrop {
514 background: var(--color-shadow);
515 }
516 .sheet-head {
517 display: flex;
518 justify-content: space-between;
519 align-items: flex-start;
520 gap: var(--space-3);
521 }
522 .sheet-head h2 {
523 font-size: var(--text-xl);
524 margin: var(--space-1) 0 var(--space-2);
525 }
526 .eyebrow {
527 font-size: var(--text-sm);
528 }
529 .sheet section p + p {
530 margin-top: var(--space-1);
531 }
532 .sheet-actions {
533 display: grid;
534 gap: var(--space-3);
535 margin-top: var(--space-5);
536 padding-top: var(--space-4);
537 border-top: 1px solid var(--color-line);
538 }
539 .move {
540 display: grid;
541 gap: var(--space-2);
542 }
543 .move label,
544 .stack label {
545 display: grid;
546 gap: var(--space-1);
547 font-size: var(--text-sm);
548 font-weight: 600;
549 }
550 .moves {
551 margin: 0;
552 padding-left: var(--space-4);
553 font-size: var(--text-sm);
554 }
555
556 /* Reminder drafts. */
557 .drafts {
558 list-style: none;
559 margin: 0;
560 padding: 0;
561 }
562 .draft {
563 display: flex;
564 align-items: flex-start;
565 gap: var(--space-2);
566 border-top: 1px solid var(--color-line);
567 }
568 .draft:first-child {
569 border-top: 0;
570 }
571 .draft details {
572 flex: 1;
573 min-width: 0;
574 }
575 .draft summary {
576 display: flex;
577 flex-wrap: wrap;
578 justify-content: space-between;
579 align-items: center;
580 gap: var(--space-1) var(--space-3);
581 min-height: var(--size-tap);
582 padding: var(--space-1) 0;
583 cursor: pointer;
584 }
585 .draft form {
586 padding-top: var(--space-1);
587 }
588 .state {
589 font-size: var(--text-sm);
590 color: var(--color-muted);
591 white-space: nowrap;
592 }
593 .state[data-today] {
594 color: var(--color-soon);
595 font-weight: 650;
596 }
597 .state[data-late] {
598 color: var(--color-overdue);
599 font-weight: 650;
600 }
601 .state[data-sent]::before {
602 content: "✓ ";
603 }
604 .draft-text {
605 margin: 0 0 var(--space-3);
606 padding: var(--space-3);
607 background: var(--color-bg);
608 border-radius: var(--radius-sm);
609 font-size: var(--text-sm);
610 }
611 .draft-text p + p {
612 margin-top: var(--space-2);
613 }
614 .draft-body {
615 white-space: pre-line;
616 }
617 .button-small {
618 min-height: var(--size-tap);
619 padding: 0 var(--space-3);
620 font-size: var(--text-sm);
621 }
622
623 /* A deal's page. */
624 .dates,
625 .parties {
626 list-style: none;
627 margin: 0;
628 padding: 0;
629 }
630 .date-row {
631 display: flex;
632 justify-content: space-between;
633 align-items: center;
634 gap: var(--space-3);
635 padding: var(--space-3) 0;
636 border-top: 1px solid var(--color-line);
637 }
638 .date-row:first-child,
639 .parties li:first-child {
640 border-top: 0;
641 }
642 .date-row p + p {
643 margin-top: var(--space-1);
644 }
645 .parties li {
646 display: grid;
647 grid-template-columns: 8rem 1fr;
648 gap: 0 var(--space-3);
649 padding: var(--space-2) 0;
650 border-top: 1px solid var(--color-line);
651 }
652 .parties .mono {
653 grid-column: 2;
654 overflow-wrap: anywhere;
655 }
656 .stack {
657 display: grid;
658 gap: var(--space-3);
659 }
660 .stack .button {
661 justify-self: start;
662 }
663 .pair,
664 .lengths {
665 display: grid;
666 grid-template-columns: repeat(auto-fit, minmax(10rem, 1fr));
667 gap: var(--space-3);
668 }
669 fieldset {
670 margin: 0;
671 padding: var(--space-3) var(--space-4) var(--space-4);
672 border: 1px solid var(--color-line);
673 border-radius: var(--radius-md);
674 }
675 legend {
676 padding: 0 var(--space-1);
677 font-size: var(--text-sm);
678 color: var(--color-muted);
679 }
680 .check {
681 display: flex !important;
682 align-items: center;
683 gap: var(--space-2);
684 min-height: var(--size-tap);
685 margin-top: var(--space-2);
686 font-weight: 400 !important;
687 }
688 .check input {
689 width: 1.25rem;
690 height: 1.25rem;
691 accent-color: var(--color-accent);
692 }
693 select.input {
694 padding-right: var(--space-2);
695 }
696 .narrow {
697 max-width: 40rem;
698 }
699 .remove {
700 margin-top: var(--space-4);
701 }
702 @media (max-width: 40rem) {
703 .page {
704 padding-left: var(--space-3);
705 padding-right: var(--space-3);
706 }
707 .parties li {
708 grid-template-columns: 1fr;
709 }
710 .parties .mono {
711 grid-column: 1;
712 }
713 .sheet {
714 padding: var(--space-3) var(--space-4) var(--space-4);
715 }
716 }
717 .draft-who {
718 flex: 1;
719 display: flex;
720 flex-wrap: wrap;
721 justify-content: space-between;
722 align-items: center;
723 gap: var(--space-1) var(--space-3);
724 min-height: var(--size-tap);
725 padding: var(--space-1) 0;
726 }
727 .draft-preview summary {
728 display: flex;
729 align-items: center;
730 min-height: var(--size-tap);
731 color: var(--color-accent);
732 cursor: pointer;
733 }

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs