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

The agent puts their own name, brokerage, phone and email on the app from a Profile page, so the sales meeting shows their name without a redeploy #67

Merged opened this

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

Merged

mason/deal-clock:mason/63-the-agent-puts-their-own-name-brokerage → main 4 commits fork 2 threads · 2 unresolved

  • Merged. mason/63-the-agent-puts-their-own-name-brokerage was merged into main as 2276821.

Review

Sign in to review this change.
25 files changed +898 −76
README.md +7 −8
@@ -143,20 +143,19 @@ Signed out, `/` shows what deal-clock does, three short points, a still picture
143143
144144 ## Make it yours
145145
146 The app ships with a sample agent. To carry your own, set four settings
147 (Settings → App → Environment):
148
149 - `DEAL_CLOCK_AGENT`: your name.
150 - `DEAL_CLOCK_BROKERAGE`: your brokerage.
151 - `DEAL_CLOCK_PHONE`: your number (digits, spaces, `+ ( ) - .`).
152 - `DEAL_CLOCK_EMAIL`: your email address.
146 The app ships with a sample agent. To carry your own, open **Profile** in the
147 header and type your name, brokerage, phone (digits, spaces, `+ ( ) - .`) and
148 email once; **Use defaults** goes back to the sample. Only an admin can save it;
149 over the API it is `GET/PUT/DELETE /api/profile` (DELETE is Use defaults), over MCP
150 `get_profile` and `set_profile`. In the terminal press I, then e to edit (enter
151 keeps a field) or U for the defaults; a guest or a non-admin sees it read-only.
153152
154153 They show in the header (the phone and email are tap-to-call and
155154 tap-to-write), on the client timeline you hand to buyers and sellers, and in
156155 the terminal. Every new reminder draft ends with your name and brokerage, then
157156 your phone and email, so a party can call or write back straight from it.
158157 Reminders you already sent keep the words you approved. A phone or email that
159 does not look right is ignored in favour of the sample, with a line in the log.
158 does not look right is refused, and the form names the field.
160159
161160 Your contracts may use other standard contingency lengths. Set them once and
162161 every New deal form, its date preview, the API and the MCP tool start from them
contract.json +9
@@ -16,6 +16,15 @@
1616 "list": "user"
1717 }
1818 },
19 "profile": {
20 "can": {
21 "create": "nobody",
22 "read": "user",
23 "update": "admin",
24 "delete": "nobody",
25 "list": "nobody"
26 }
27 },
1928 "audit": {
2029 "api": "/api/audit",
2130 "can": {
contract/openapi.json +225
@@ -6,6 +6,231 @@
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 "/api/profile": {
10 "get": {
11 "summary": "The agent's name, brokerage, phone and email as the header and every reminder's sign-off carry them; saved is false while the environment's defaults stand.",
12 "operationId": "getApiProfile",
13 "responses": {
14 "200": {
15 "description": "The agent's name, brokerage, phone and email as the header and every reminder's sign-off carry them; saved is false while the environment's defaults stand.",
16 "content": {
17 "application/json": {
18 "schema": {
19 "type": "object",
20 "properties": {
21 "name": {
22 "type": "string",
23 "minLength": 1,
24 "maxLength": 80
25 },
26 "brokerage": {
27 "type": "string",
28 "minLength": 1,
29 "maxLength": 80
30 },
31 "phone": {
32 "type": "string",
33 "maxLength": 30
34 },
35 "email": {
36 "type": "string",
37 "maxLength": 254
38 },
39 "saved": {
40 "type": "boolean",
41 "description": "False while the environment's defaults stand."
42 }
43 },
44 "required": [
45 "name",
46 "brokerage",
47 "phone",
48 "email"
49 ]
50 }
51 }
52 }
53 },
54 "default": {
55 "description": "{ error, message }: why not",
56 "content": {
57 "application/json": {
58 "schema": {
59 "$ref": "#/components/schemas/Error"
60 }
61 }
62 }
63 }
64 },
65 "x-contract": {
66 "resource": "profile",
67 "verb": "read",
68 "least": "user"
69 }
70 },
71 "put": {
72 "summary": "Save the agent's four details, all or none; the same checks as the Profile page. Only an admin may.",
73 "operationId": "putApiProfile",
74 "requestBody": {
75 "required": true,
76 "content": {
77 "application/json": {
78 "schema": {
79 "type": "object",
80 "properties": {
81 "name": {
82 "type": "string",
83 "minLength": 1,
84 "maxLength": 80
85 },
86 "brokerage": {
87 "type": "string",
88 "minLength": 1,
89 "maxLength": 80
90 },
91 "phone": {
92 "type": "string",
93 "maxLength": 30
94 },
95 "email": {
96 "type": "string",
97 "maxLength": 254
98 },
99 "saved": {
100 "type": "boolean",
101 "description": "False while the environment's defaults stand."
102 }
103 },
104 "required": [
105 "name",
106 "brokerage",
107 "phone",
108 "email"
109 ]
110 }
111 }
112 }
113 },
114 "responses": {
115 "200": {
116 "description": "Save the agent's four details, all or none; the same checks as the Profile page. Only an admin may.",
117 "content": {
118 "application/json": {
119 "schema": {
120 "type": "object",
121 "properties": {
122 "name": {
123 "type": "string",
124 "minLength": 1,
125 "maxLength": 80
126 },
127 "brokerage": {
128 "type": "string",
129 "minLength": 1,
130 "maxLength": 80
131 },
132 "phone": {
133 "type": "string",
134 "maxLength": 30
135 },
136 "email": {
137 "type": "string",
138 "maxLength": 254
139 },
140 "saved": {
141 "type": "boolean",
142 "description": "False while the environment's defaults stand."
143 }
144 },
145 "required": [
146 "name",
147 "brokerage",
148 "phone",
149 "email"
150 ]
151 }
152 }
153 }
154 },
155 "default": {
156 "description": "{ error, message }: why not",
157 "content": {
158 "application/json": {
159 "schema": {
160 "$ref": "#/components/schemas/Error"
161 }
162 }
163 }
164 }
165 },
166 "x-contract": {
167 "resource": "profile",
168 "verb": "update",
169 "least": "admin"
170 }
171 },
172 "delete": {
173 "summary": "Forget the saved details: the environment's values are the agent again. Only an admin may.",
174 "operationId": "deleteApiProfile",
175 "responses": {
176 "200": {
177 "description": "Forget the saved details: the environment's values are the agent again. Only an admin may.",
178 "content": {
179 "application/json": {
180 "schema": {
181 "type": "object",
182 "properties": {
183 "name": {
184 "type": "string",
185 "minLength": 1,
186 "maxLength": 80
187 },
188 "brokerage": {
189 "type": "string",
190 "minLength": 1,
191 "maxLength": 80
192 },
193 "phone": {
194 "type": "string",
195 "maxLength": 30
196 },
197 "email": {
198 "type": "string",
199 "maxLength": 254
200 },
201 "saved": {
202 "type": "boolean",
203 "description": "False while the environment's defaults stand."
204 }
205 },
206 "required": [
207 "name",
208 "brokerage",
209 "phone",
210 "email"
211 ]
212 }
213 }
214 }
215 },
216 "default": {
217 "description": "{ error, message }: why not",
218 "content": {
219 "application/json": {
220 "schema": {
221 "$ref": "#/components/schemas/Error"
222 }
223 }
224 }
225 }
226 },
227 "x-contract": {
228 "resource": "profile",
229 "verb": "update",
230 "least": "admin"
231 }
232 }
233 },
9234 "/tick": {
10235 "post": {
11236 "summary": "The reminders that go out today and have not been sent: call it each morning. It sends nothing and changes nothing.",
docs/TECHNICAL.md +2 −1
@@ -7,7 +7,8 @@ everything technical, and `AGENTS.md` says how to add to it.
77 ## Settings
88
99 The agent in the header, the client timeline and every reminder's sign-off
10 comes from four settings (Settings → App → Environment): `DEAL_CLOCK_AGENT`,
10 is the saved Profile (one `profile` row in sqlite). Until one is saved, four
11 settings (Settings → App → Environment) are the defaults: `DEAL_CLOCK_AGENT`,
1112 `DEAL_CLOCK_BROKERAGE`, `DEAL_CLOCK_PHONE` (digits, spaces, `+ ( ) - .`, at
1213 most 30 characters) and `DEAL_CLOCK_EMAIL` (one `@`, at most 254). A bad phone
1314 or email falls back to the sample with one line in the log. Dates follow the server's time zone (`TZ`).
src/contract.test.ts +11
@@ -20,6 +20,7 @@ import {
2020 import { actingAs, identities, table, type Verb } from "./can.ts";
2121 import { contract, permit } from "./contract.ts";
2222 import { openDb } from "./db.ts";
23 import { getProfile, setProfile, useDefaults } from "./profile.ts";
2324 import type { Who } from "./who.ts";
2425
2526 const db = openDb(mkdtempSync(join(tmpdir(), "app-contract-")));
@@ -72,6 +73,16 @@ const doors: Record<
7273 updateDeal(db, who, { id: dealBy(authorId), address: "2 Test St" }).ok,
7374 delete: (who, authorId) => deleteDeal(db, who, { id: dealBy(authorId) }).ok,
7475 },
76 // One row, written through setProfile and useDefaults; nothing creates, lists or deletes it.

The profile row of the contract table is covered. Add the terminal door as well once it exists.

77 profile: {
78 read: (who) => getProfile(db, who).ok,
79 update: (who) =>
80 setProfile(db, who, { name: "A", brokerage: "B", phone: "555 0100", email: "[email protected]" }).ok &&
81 useDefaults(db, who).ok,
82 create: () => false,
83 list: () => false,
84 delete: () => false,
85 },
7586 // The trail is written by the app itself, never through a door: there
7687 // is no action that creates, changes or removes a row of it.
7788 audit: {
src/db.ts +10
@@ -310,6 +310,16 @@ export const migrations: string[] = [
310310 // number, so the parties get one "dates changed" notice for them; 0 is a
311311 // move made on its own.
312312 `ALTER TABLE deadline_move ADD COLUMN amendment INTEGER NOT NULL DEFAULT 0`,
313 // The agent's own name, brokerage, phone and email: at most one row, and
314 // with none the environment's values stand (src/profile.ts).
315 `CREATE TABLE IF NOT EXISTS profile (
316 id INTEGER PRIMARY KEY CHECK (id = 1),
317 name TEXT NOT NULL CHECK (length(name) BETWEEN 1 AND 80),
318 brokerage TEXT NOT NULL CHECK (length(brokerage) BETWEEN 1 AND 80),
319 phone TEXT NOT NULL,
320 email TEXT NOT NULL,
321 updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
322 )`,
313323 ];
314324
315325 export function openDb(dir = dataDir): Database {
src/deals.ts +4 −3
@@ -19,7 +19,8 @@ import {
1919 type Lengths,
2020 type PartyRole,
2121 } from "./deadlines.ts";
22 import { agent as defaultAgent, LENGTH_MAX, standard } from "./env.ts";
22 import { LENGTH_MAX, standard } from "./env.ts";
23 import { agentOf } from "./profile.ts";
2324 import { emit } from "./live.ts";
2425 import { outbox } from "./outbox.ts";
2526 import { conflictLine, conflicts, type Conflict } from "./order.ts";
@@ -851,7 +852,7 @@ export function sendReminder(
851852 const draft = draftsFor(
852853 seen,
853854 seen.deadlines.find((d) => d.id === deadline.id)!,
854 input.agent ?? defaultAgent,
855 input.agent ?? agentOf(db),
855856 ).find((r) => r.party_id === party.id && r.moment === input.moment);
856857 if (draft === undefined && input.moment === "moved")
857858 return within(db, who, dealId, fail("not_found", "No such reminder on this date."));
@@ -891,7 +892,7 @@ function draftOf(
891892 const draft =
892893 party === null
893894 ? undefined
894 : draftsFor(view(db, deal), seen, input.agent ?? defaultAgent).find(
895 : draftsFor(view(db, deal), seen, input.agent ?? agentOf(db)).find(
895896 (r) => r.party_id === party.id && r.moment === input.moment,
896897 );
897898 if (party === null || draft === undefined)
src/ics.ts +7 −4
@@ -7,6 +7,7 @@
77 import { addDays } from "./dates.ts";
88 import { PARTY_LABEL } from "./deadlines.ts";
99 import type { DealView } from "./deals.ts";
10 import { signOff, type Agent } from "./reminders.ts";
1011
1112 /** Text as a property value: backslash, semicolon, comma and newline escaped. */
1213 export const icsText = (s: string): string =>
@@ -73,7 +74,7 @@ function events(deal: DealView, host: string, now: string, openOnly: boolean): s
7374 return lines;
7475 }
7576
76 function wrap(name: string, body: string[]): string {
77 function wrap(name: string, body: string[], agent?: Agent): string {
7778 const lines = [
7879 "BEGIN:VCALENDAR",
7980 "VERSION:2.0",
@@ -81,21 +82,23 @@ function wrap(name: string, body: string[]): string {
8182 "CALSCALE:GREGORIAN",
8283 "METHOD:PUBLISH",
8384 `X-WR-CALNAME:${icsText(name)}`,
85 ...(agent === undefined ? [] : [`X-WR-CALDESC:${icsText(signOff(agent))}`]),
8486 ...body,
8587 "END:VCALENDAR",
8688 ];
8789 return `${lines.map(fold).join("\r\n")}\r\n`;
8890 }
8991
90 export function calendar(deal: DealView, host: string, stamp = new Date()): string {
91 return wrap(deal.address, events(deal, host, stampOf(stamp), false));
92 export function calendar(deal: DealView, host: string, stamp = new Date(), agent?: Agent): string {
93 return wrap(deal.address, events(deal, host, stampOf(stamp), false), agent);
9294 }
9395
9496 /** Every open date of every open deal in one file; done dates and closed deals are left out. */
95 export function book(deals: readonly DealView[], host: string, stamp = new Date()): string {
97 export function book(deals: readonly DealView[], host: string, stamp = new Date(), agent?: Agent): string {
9698 const now = stampOf(stamp);
9799 return wrap(
98100 "Deal clock",
99101 deals.filter((deal) => !deal.closed).flatMap((deal) => events(deal, host, now, true)),
102 agent,
100103 );
101104 }
src/mcp.ts +25 −3
@@ -30,10 +30,11 @@ import {
3030 declineReminder,
3131 undoDecline,
3232 } from "./deals.ts";
33 import { agent, LENGTH_MAX, standard, title } from "./env.ts";
33 import { LENGTH_MAX, standard, title } from "./env.ts";
3434 import { dueOn } from "./reminders.ts";
3535 import { FIND_REFUSAL, find, query } from "./find.ts";
3636 import { fields } from "./http.ts";
37 import { agentOf, getProfile, setProfile } from "./profile.ts";
3738 import { people } from "./people.ts";
3839 import { timelineRows } from "./timeline.ts";
3940 import { owner, thisWeek } from "./week.ts";
@@ -76,7 +77,7 @@ export const tools: readonly Tool[] = [
7677 const got = getDeal(db, who, { id: Number(args.id) });
7778 if (!got.ok) return got;
7879 const dates = timelineRows(got.value, today()).map(({ label, due, role, name, status }) => ({ label, due, owed_by: { role, name: name ?? null }, status }));
79 return { ok: true, value: { address: got.value.address, agent, dates } };
80 return { ok: true, value: { address: got.value.address, agent: agentOf(db), dates } };
8081 },
8182 },
8283 {
@@ -85,7 +86,7 @@ export const tools: readonly Tool[] = [
8586 inputSchema: { type: "object", properties: {} },
8687 run: (db, who) => {
8788 const deals = listDeals(db, who);
88 return deals.ok ? { ok: true, value: dueOn(deals.value, today(), agent) } : deals;
89 return deals.ok ? { ok: true, value: dueOn(deals.value, today(), agentOf(db)) } : deals;
8990 },
9091 },
9192 {
@@ -331,6 +332,27 @@ export const tools: readonly Tool[] = [
331332 inputSchema: { type: "object", properties: { deal_id: { type: "integer" } }, required: ["deal_id"] },
332333 run: (db, who, a) => deleteDeal(db, who, { id: Number(a.deal_id) }),
333334 },
335 {
336 name: "get_profile",
337 description: "The agent's name, brokerage, phone and email as the header and every reminder's sign-off carry them; saved is false while the environment's defaults stand.",
338 inputSchema: { type: "object", properties: {} },
339 run: (db, who) => getProfile(db, who),
340 },
341 {
342 name: "set_profile",
343 description: "Save the agent's name and brokerage (1 to 80 characters), phone and email; the same checks as the Profile page, all or none. Only an admin may.",
344 inputSchema: {
345 type: "object",
346 properties: {
347 name: { type: "string", maxLength: 80 },
348 brokerage: { type: "string", maxLength: 80 },
349 phone: { type: "string", maxLength: 30 },
350 email: { type: "string", maxLength: 254 },
351 },
352 required: ["name", "brokerage", "phone", "email"],
353 },
354 run: (db, who, a) => setProfile(db, who, a),
355 },
334356 {
335357 name: "restore_samples",
336358 description: "Put the four sample deals back as the README describes them, anchored to today; deals people made are untouched.",
src/pages/clock.ts +10 −7
@@ -8,9 +8,9 @@
88 import { addDays, daysBetween, isWeekend, relative, short, spoken, urgency } from "../dates.ts";
99 import type { DealView } from "../deals.ts";
1010 import { KIND } from "../deadlines.ts";
11 import { agent } from "../env.ts";
1211 import { escape } from "../http.ts";
13 import { drafts, pending, unsent } from "../reminders.ts";
12 import { agent as defaults } from "../env.ts";
13 import { drafts, pending, unsent, type Agent } from "../reminders.ts";
1414 import type { Who } from "../who.ts";
1515 import { thisWeek } from "../week.ts";
1616 import { layout } from "./layout.ts";
@@ -124,8 +124,8 @@ function weekCard(deals: readonly DealView[], on: string): string {
124124 const remembered = memoizer<{ count: number; toSend: number; html: string }>(400);
125125
126126 /** One deal's reminders that go out today, as list items: counted, and rendered once while the deal stands. */
127 function reminderRows(deal: DealView, on: string): { count: number; toSend: number; html: string } {
128 return remembered(`${on}|${print(deal)}`, () => {
127 function reminderRows(deal: DealView, on: string, agent: Agent): { count: number; toSend: number; html: string } {
128 return remembered(`${on}|${JSON.stringify(agent)}|${print(deal)}`, () => {
129129 const these = drafts(deal, agent).filter((r) => pending(r, on));
130130 return {
131131 count: these.length,
@@ -140,6 +140,7 @@ const pages = memoizer<string>(3);
140140 /** The clock, rendered once while nothing it shows has changed. */
141141 export function clock(input: {
142142 who: Who;
143 agent?: Agent | undefined;
143144 deals: readonly DealView[];
144145 on: string;
145146 notice?: string | undefined;
@@ -147,7 +148,7 @@ export function clock(input: {
147148 q?: string | undefined;
148149 }): string {
149150 const key = Bun.hash(
150 JSON.stringify([input.who, input.on, input.notice ?? null, input.open ?? null, input.q ?? "", agent]) +
151 JSON.stringify([input.who, input.on, input.notice ?? null, input.open ?? null, input.q ?? "", input.agent]) +
151152 input.deals.map(print).join(),
152153 );
153154 return pages(`${input.deals.length}:${key}`, () => render(input));
@@ -155,6 +156,7 @@ export function clock(input: {
155156
156157 function render(input: {
157158 who: Who;
159 agent?: Agent | undefined;
158160 deals: readonly DealView[];
159161 on: string;
160162 notice?: string | undefined;
@@ -162,6 +164,7 @@ function render(input: {
162164 q?: string | undefined;
163165 }): string {
164166 const { who, on, notice } = input;
167 const agent = input.agent ?? defaults;
165168 const opened =
166169 input.open === undefined ? undefined : input.deals.flatMap((d) => d.sent).find((m) => m.id === input.open);
167170 const q = input.q ?? "";
@@ -174,7 +177,7 @@ function render(input: {
174177 const overdue = open.filter((d) => urgency(d.due, on, false) === "overdue").length;
175178 const soon = open.filter((d) => urgency(d.due, on, false) === "soon").length;
176179 const { start, days } = span(deals, on);
177 const today = deals.map((deal) => reminderRows(deal, on));
180 const today = deals.map((deal) => reminderRows(deal, on, agent));
178181 const todayCount = today.reduce((n, t) => n + t.count, 0);
179182 const none = q !== "" && found.length === 0;
180183 const toSend = today.reduce((n, t) => n + t.toSend, 0);
@@ -245,5 +248,5 @@ function render(input: {
245248 }
246249 <p class="muted small">Each date reminds its parties three days before and the morning of, and the one who owes a date is asked for an update the morning after it slips. Send records your approval and opens your own Mail or Messages with the words.</p>
247250 </section>`}`;
248 return layout({ body, who, path: "/", notice, open: opened?.href });
251 return layout({ body, who, agent, path: "/", notice, open: opened?.href });
249252 }
src/pages/deal.ts +8 −6
@@ -9,7 +9,7 @@ import { canChange, canRemove, closedOn, type DealView, type Party, type Plan, t
99 import { standard } from "../env.ts";
1010 import { DEFAULT_LENGTHS, PARTY_LABEL, PARTY_ROLES } from "../deadlines.ts";
1111 import { escape } from "../http.ts";
12 import { MOMENT_LABEL } from "../reminders.ts";
12 import { MOMENT_LABEL, type Agent } from "../reminders.ts";
1313 import type { Who } from "../who.ts";
1414 import { amendForm, type AmendState } from "./amend.ts";
1515 import { confirmRemove } from "./confirm.ts";
@@ -62,6 +62,7 @@ function messages(deal: DealView, may: boolean): string {
6262
6363 export function dealPage(input: {
6464 who: Who;
65 agent?: Agent | undefined;
6566 deal: DealView;
6667 on: string;
6768 notice?: string | undefined;
@@ -72,7 +73,7 @@ export function dealPage(input: {
7273 /** An amendment that was refused: what was typed and what was wrong. */
7374 amend?: AmendState | undefined;
7475 }): string {
75 const { who, deal, on, notice, problem } = input;
76 const { who, agent, deal, on, notice, problem } = input;
7677 const opened = input.open === undefined ? undefined : deal.sent.find((m) => m.id === input.open);
7778 const path = `/deals/${deal.id}`;
7879 const may = canChange(who, deal);
@@ -155,7 +156,7 @@ export function dealPage(input: {
155156 <h2>Messages</h2>
156157 ${messages(deal, may)}
157158 </section>
158 ${deal.deadlines.map((d) => sheet(deal, d, who, on, path)).join("")}
159 ${deal.deadlines.map((d) => sheet(deal, d, who, on, path, agent)).join("")}
159160 </div>
160161 ${forms}
161162 ${
@@ -169,7 +170,7 @@ export function dealPage(input: {
169170 })
170171 : ""
171172 }`;
172 return layout({ body, who, path, heading: deal.address, notice, open: opened?.href });
173 return layout({ body, who, agent, path, heading: deal.address, notice, open: opened?.href });
173174 }
174175
175176 /** What the form was last sent with, what was wrong with it, and the dates it would make. */
@@ -195,11 +196,12 @@ const previewList = ({ plan, dates }: NonNullable<NewDealState["preview"]>): str
195196
196197 export function newDealPage(input: {
197198 who: Who;
199 agent?: Agent | undefined;
198200 on: string;
199201 notice?: string | undefined;
200202 state?: NewDealState | undefined;
201203 }): string {
202 const { who, on, notice, state } = input;
204 const { who, agent, on, notice, state } = input;
203205 const values = state?.values ?? {};
204206 const problem = state?.problem;
205207 const val = (name: string, fallback: string): string => escape(values[name] ?? fallback);
@@ -254,5 +256,5 @@ export function newDealPage(input: {
254256 <p class="muted small">Reading these from the contract PDF is phase two.</p>
255257 </section>
256258 ${state?.preview === undefined ? "" : previewList(state.preview)}`;
257 return layout({ body, who, path: "/deals/new", heading: "New deal", notice });
259 return layout({ body, who, agent, path: "/deals/new", heading: "New deal", notice });
258260 }
src/pages/layout.ts +6 −3
@@ -6,7 +6,7 @@
66 */
77
88 import {
9 agent,
9 agent as defaults,
1010 commit,
1111 description,
1212 env,
@@ -19,6 +19,7 @@ import { asset, escape } from "../http.ts";
1919 import { labelOf, NO_CONTACT } from "../outbox.ts";
2020 import { contactLinks } from "./contact.ts";
2121 import { token, tokensHref } from "../tokens.ts";
22 import type { Agent } from "../reminders.ts";
2223 import type { Who } from "../who.ts";
2324
2425 const iconHref = asset("icon.svg");
@@ -26,6 +27,8 @@ const iconHref = asset("icon.svg");
2627 export function layout(input: {
2728 body: string;
2829 who: Who;
30 /** Whose deals these are: the header names them. */
31 agent?: Agent | undefined;
2932 path: string;
3033 heading?: string;
3134 notice?: string | undefined;
@@ -38,7 +41,7 @@ export function layout(input: {
3841 /** A class on <body>, for styles that belong to one page only. */
3942 bodyClass?: string;
4043 }): string {
41 const { body, who, path, notice, open, plain = false, bodyClass } = input;
44 const { body, who, agent = defaults, path, notice, open, plain = false, bodyClass } = input;
4245 const pageTitle = input.heading === undefined ? title : `${input.heading} · ${title}`;
4346 const to = encodeURIComponent(path);
4447 const door =
@@ -81,7 +84,7 @@ ${plain || input.live === false ? "" : `<script type="module" src="${asset("live
8184 ? ""
8285 : `<nav class="row">
8386 ${env === "production" ? "" : `<span class="pill" data-env="${escape(env)}">${escape(where)}</span>`}
84 ${who.role === "anon" ? "" : `<a class="button button-quiet" href="/">Clock</a> <a class="button button-quiet" href="/people">People</a>`}
87 ${who.role === "anon" ? "" : `<a class="button button-quiet" href="/">Clock</a> <a class="button button-quiet" href="/people">People</a> <a class="button button-quiet" href="/profile">Profile</a>`}
8588 ${door}
8689 </nav>`
8790 }
src/pages/people.ts +3 −2
@@ -8,6 +8,7 @@ import { relative, spoken } from "../dates.ts";
88 import { escape } from "../http.ts";
99 import type { Person } from "../people.ts";
1010 import type { Who } from "../who.ts";
11 import type { Agent } from "../reminders.ts";
1112 import { layout } from "./layout.ts";
1213 import { URGENCY_LABEL } from "./sheet.ts";
1314
@@ -20,10 +21,10 @@ const person = (p: Person, on: string): string => `<section class="card person">
2021 ${p.owes.length === 0 ? `<p class="muted">Nothing open</p>` : `<ul class="week-list">${p.owes.map((o) => owedRow(o, on)).join("")}</ul>`}
2122 </section>`;
2223
23 export function peoplePage(input: { who: Who; people: readonly Person[]; on: string }): string {
24 export function peoplePage(input: { who: Who; agent?: Agent | undefined; people: readonly Person[]; on: string }): string {
2425 const { who, people, on } = input;
2526 const body = `<h1>People</h1>
2627 <p class="summary">Everyone on your deals, with every open date they owe, soonest first.</p>
2728 ${people.length === 0 ? `<p class="muted">No one yet: add a deal and its parties.</p>` : people.map((p) => person(p, on)).join("")}`;
28 return layout({ body, who, path: "/people", heading: "People", live: false });
29 return layout({ body, who, agent: input.agent, path: "/people", heading: "People", live: false });
2930 }
src/pages/profile.ts added +66
@@ -0,0 +1,66 @@
1 /**
2 * The agent's own details at `/profile`: four labelled fields, prefilled with
3 * what the header says now. A refused form keeps what was typed and names the
4 * field, as New deal does. Whoever may not change it sees the details only.
5 */
6
7 import { escape } from "../http.ts";
8 import type { Profile } from "../profile.ts";
9 import type { Agent } from "../reminders.ts";
10 import type { Who } from "../who.ts";
11 import { layout } from "./layout.ts";
12
13 export interface ProfileState {
14 readonly values: Readonly<Record<string, string>>;
15 readonly problem: { readonly message: string; readonly field?: string | undefined };
16 }
17
18 export function profilePage(input: {
19 who: Who;
20 profile: Profile;
21 /** Whether the table lets `who` save it. */
22 mayChange: boolean;
23 notice?: string | undefined;
24 state?: ProfileState | undefined;
25 }): string {
26 const { who, profile, mayChange, notice, state } = input;
27 const agent: Agent = profile;
28 const values = state?.values ?? {};
29 const problem = state?.problem;
30 const val = (name: keyof Agent): string => escape(values[name] ?? agent[name]);
31 const why = (name: string): string =>
32 problem?.field === name
33 ? `<span class="field-error" id="${name}-why" role="alert">${escape(problem.message)}</span>`
34 : "";
35 const bad = (name: string): string =>
36 problem?.field === name ? ` aria-invalid="true" aria-describedby="${name}-why"` : "";
37 const general =
38 problem !== undefined && problem.field === undefined
39 ? `<p class="field-error" role="alert">${escape(problem.message)}</p>`
40 : "";
41 const form = `<form class="stack" method="post" action="/profile">
42 ${general}
43 <label>Your name<input class="input" name="name" required maxlength="80" autocomplete="name" value="${val("name")}"${bad("name")}>${why("name")}</label>
44 <label>Brokerage<input class="input" name="brokerage" required maxlength="80" autocomplete="organization" value="${val("brokerage")}"${bad("brokerage")}>${why("brokerage")}</label>
45 <label>Phone<input class="input" type="tel" name="phone" required maxlength="30" autocomplete="tel" value="${val("phone")}"${bad("phone")}>${why("phone")}</label>
46 <label>Email<input class="input" type="email" name="email" required maxlength="254" autocomplete="email" value="${val("email")}"${bad("email")}>${why("email")}</label>
47 <div class="actions">
48 <button class="button">Save profile</button>
49 <button class="button button-quiet" formaction="/profile/defaults" formnovalidate>Use defaults</button>
50 </div>
51 </form>`;
52 const readOnly = `<dl class="stack">
53 <div><dt class="muted small">Your name</dt><dd>${escape(agent.name)}</dd></div>
54 <div><dt class="muted small">Brokerage</dt><dd>${escape(agent.brokerage)}</dd></div>
55 <div><dt class="muted small">Phone</dt><dd>${escape(agent.phone)}</dd></div>
56 <div><dt class="muted small">Email</dt><dd>${escape(agent.email)}</dd></div>
57 </dl>
58 <p class="muted small">Only an admin can change these.</p>`;
59 const body = `<p class="crumb"><a href="/">← The clock</a></p>
60 <section class="card narrow">
61 <h1>Profile</h1>
62 <p class="muted">${profile.saved ? "Saved by you." : "These are the defaults the app was started with."} The header, the client timeline and the sign-off of every unsent reminder carry them. Reminders already sent keep the words that went out.</p>
63 ${mayChange ? form : readOnly}
64 </section>`;
65 return layout({ body, who, agent, path: "/profile", heading: "Profile", notice, live: false });
66 }
src/pages/refused.ts +4 −2
@@ -6,20 +6,22 @@
66
77 import type { Failure } from "../result.ts";
88 import { escape } from "../http.ts";
9 import type { Agent } from "../reminders.ts";
910 import type { Who } from "../who.ts";
1011 import { layout } from "./layout.ts";
1112
1213 export function refusedPage(input: {
1314 who: Who;
15 agent?: Agent | undefined;
1416 path: string;
1517 heading: string;
1618 error: Failure;
1719 message: string;
1820 }): string {
19 const { who, path, heading, error, message } = input;
21 const { who, agent, path, heading, error, message } = input;
2022 const body =
2123 error === "signin_required"
2224 ? `<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>`
2325 : `<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 });
26 return layout({ body, who, agent, path, heading });
2527 }
src/pages/sheet.ts +5 −5
@@ -8,13 +8,13 @@
88 import { BODY_MAX, canChange, REASON_MAX, SUBJECT_MAX, type DealView, type DeadlineView } from "../deals.ts";
99 import { relative, short, spoken, urgency, type Urgency } from "../dates.ts";
1010 import { PARTY_LABEL } from "../deadlines.ts";
11 import { agent } from "../env.ts";
1211 import { escape } from "../http.ts";
1312 import { confirmRemove } from "./confirm.ts";
1413 import { memoizer, print } from "../memo.ts";
1514 import { labelOf, NO_CONTACT, outbox } from "../outbox.ts";
1615 import { conflictLine } from "../order.ts";
17 import { draftsFor, MOMENT_LABEL, MOMENTS, type Draft } from "../reminders.ts";
16 import { agent as defaults } from "../env.ts";
17 import { draftsFor, MOMENT_LABEL, MOMENTS, type Agent, type Draft } from "../reminders.ts";
1818 import type { Who } from "../who.ts";
1919 import { owner } from "../week.ts";
2020
@@ -138,7 +138,7 @@ export function draftItem(draft: Draft, on: string, may: boolean, to: string): s
138138 export const draftLink = (draft: Draft, on: string): string =>
139139 `<li class="draft"><a class="draft-open" href="/deals/${draft.deal_id}#sheet-${draft.deadline_id}" data-sheet="sheet-${draft.deadline_id}" data-sheets="/deals/${draft.deal_id}/sheets">${draftLine(draft, on, true)}</a></li>`;
140140
141 export function sheet(deal: DealView, d: DeadlineView, who: Who, on: string, to: string): string {
141 export function sheet(deal: DealView, d: DeadlineView, who: Who, on: string, to: string, agent: Agent = defaults): string {
142142 const id = sheetId(d);
143143 const may = canChange(who, deal);
144144 const drafts = d.done_at === null ? draftsFor(deal, d, agent) : [];
@@ -211,7 +211,7 @@ const remembered = memoizer<string>(300);
211211 * deal, whether `who` may change it, the day and where its forms return to,
212212 * so that is the key: a deal nobody touched is not rendered again.
213213 */
214 export const dealSheets = (deal: DealView, who: Who, on: string, to: string): string =>
214 export const dealSheets = (deal: DealView, who: Who, on: string, to: string, agent: Agent = defaults): string =>
215215 remembered(`${canChange(who, deal)}|${on}|${to}|${JSON.stringify(agent)}|${print(deal)}`, () =>
216 deal.deadlines.map((d) => sheet(deal, d, who, on, to)).join(""),
216 deal.deadlines.map((d) => sheet(deal, d, who, on, to, agent)).join(""),
217217 );
src/pages/timeline.ts +5 −3
@@ -6,15 +6,17 @@
66 */
77
88 import type { DealView } from "../deals.ts";
9 import { agent } from "../env.ts";
9 import type { Agent } from "../reminders.ts";
10 import { agent as defaults } from "../env.ts";
1011 import { escape } from "../http.ts";
1112 import { timelineRows } from "../timeline.ts";
1213 import type { Who } from "../who.ts";
1314 import { contactLinks } from "./contact.ts";
1415 import { layout } from "./layout.ts";
1516
16 export function timelinePage(input: { who: Who; deal: DealView; on: string }): string {
17 export function timelinePage(input: { who: Who; agent?: Agent | undefined; deal: DealView; on: string }): string {
1718 const { who, deal, on } = input;
19 const agent = input.agent ?? defaults;
1820 const path = `/deals/${deal.id}/timeline`;
1921 const rows = timelineRows(deal, on)
2022 .map(
@@ -33,5 +35,5 @@ export function timelinePage(input: { who: Who; deal: DealView; on: string }): s
3335 <p class="summary">${contactLinks(agent)}</p>
3436 <ol class="timeline-list">${rows}</ol>
3537 </section>`;
36 return layout({ body, who, path, heading: `Timeline · ${deal.address}`, plain: true, bodyClass: "timeline-page" });
38 return layout({ body, who, agent, path, heading: `Timeline · ${deal.address}`, plain: true, bodyClass: "timeline-page" });
3739 }
src/pages/welcome.ts +3 −2
@@ -8,6 +8,7 @@
88 import { addDays, short, urgency } from "../dates.ts";
99 import { KIND, schedule } from "../deadlines.ts";
1010 import { escape } from "../http.ts";
11 import type { Agent } from "../reminders.ts";
1112 import type { Who } from "../who.ts";
1213 import { axis } from "./clock.ts";
1314 import { layout } from "./layout.ts";
@@ -50,7 +51,7 @@ function picture(on: string): string {
5051 </div>`;
5152 }
5253
53 export function welcomePage(input: { who: Who; on: string }): string {
54 export function welcomePage(input: { who: Who; agent?: Agent | undefined; on: string }): string {
5455 const body = `<section class="welcome">
5556 <h1>Every deadline of every deal on one timeline, with reminders each party gets before anything slips.</h1>
5657 <ul class="points">
@@ -62,5 +63,5 @@ export function welcomePage(input: { who: Who; on: string }): string {
6263 ${picture(input.on)}
6364 </section>
6465 </section>`;
65 return layout({ body, who: input.who, path: "/", live: false });
66 return layout({ body, who: input.who, agent: input.agent, path: "/", live: false });
6667 }
src/profile.test.ts added +191
@@ -0,0 +1,191 @@
1 /** The agent's profile: saved once, read by the header, drafts, timeline, files and terminal. */
2 import { afterAll, beforeEach, expect, test } from "bun:test";
3 import { mkdtempSync } from "node:fs";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { getDeal, insertDeal, plan, sendReminder, type NewDeal } from "./deals.ts";
7 import { openDb } from "./db.ts";
8 import { agent as defaults } from "./env.ts";
9 import { book } from "./ics.ts";
10 import { agentOf, getProfile, setProfile, useDefaults } from "./profile.ts";
11 import { draftsFor } from "./reminders.ts";
12 import { forgetRationing } from "./security.ts";
13 import { serve } from "./server.ts";
14 import { terminal } from "./terminal.ts";
15 import { sign, type Who } from "./who.ts";
16
17 const KEY = "a-key-only-the-forge-holds";
18 const dir = mkdtempSync(join(tmpdir(), "app-profile-"));
19 const server = serve({ port: 0, dataDir: dir, identityKey: KEY });
20 const base = `http://${server.hostname}:${server.port}`;
21 afterAll(() => server.stop(true));
22 beforeEach(forgetRationing);
23
24 const as = (id: string, name: string, role: "user" | "admin"): Record<string, string> => {
25 const identity = `${id}|${name}|${role}|${Date.now() + 60_000}`;
26 return { "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) };
27 };
28 const root = as("u0", "root", "admin");
29 const rita = as("u-rita", "rita", "user");
30 const lee = { name: "Lee Park", brokerage: "Bay Homes", phone: "+1 555 0199", email: "[email protected]" };
31 const put = (body: unknown, who: Record<string, string> = root) =>
32 fetch(`${base}/api/profile`, { method: "PUT", headers: { "content-type": "application/json", ...who }, body: JSON.stringify(body) });
33 const page = async (path: string, who: Record<string, string> = root) => (await fetch(base + path, { headers: who })).text();
34 const form = (path: string, fields: Record<string, string>, who: Record<string, string> = root) =>
35 fetch(base + path, { method: "POST", redirect: "manual", headers: { "content-type": "application/x-www-form-urlencoded", ...who }, body: new URLSearchParams(fields) });
36 const notice = (r: Response) => decodeURIComponent(r.headers.get("set-cookie") ?? "");
37
38 /** A deal written without announcing it: the event stream's own test counts what is announced. */
39 const open = (db: ReturnType<typeof openDb>, who: Who, input: NewDeal): { id: number } => {
40 const planned = plan(input);
41 if (!planned.ok) throw new Error(planned.message);
42 return insertDeal(db, { id: "id" in who ? who.id : "", name: "name" in who ? who.name : "" }, planned.value);
43 };
44
45 const admin: Who = { role: "admin", id: "u0", name: "root" };
46 const user: Who = { role: "user", id: "u1", name: "alice" };
47
48 test("the defaults stand until saved, then the saved row; Use defaults restores them", () => {
49 const db = openDb(mkdtempSync(join(tmpdir(), "app-profile-unit-")));
50 expect(agentOf(db)).toEqual(defaults);
51 expect(getProfile(db, user)).toEqual({ ok: true, value: { ...defaults, id: 1, saved: false } });
52 expect(setProfile(db, admin, lee).ok).toBe(true);
53 expect(agentOf(db)).toEqual(lee);
54 const got = getProfile(db, user);
55 expect(got.ok && got.value.saved).toBe(true);
56 expect(useDefaults(db, admin).ok).toBe(true);
57 expect(agentOf(db)).toEqual(defaults);
58 expect(db.query("SELECT count(*) AS n FROM profile").get()).toEqual({ n: 0 });
59 });
60
61 test("each field is checked with env.ts's rules and the first bad one is named", () => {
62 const db = openDb(mkdtempSync(join(tmpdir(), "app-profile-bad-")));
63 const bad = (change: Record<string, unknown>) => setProfile(db, admin, { ...lee, ...change });
64 for (const [field, value] of [["name", ""], ["name", "x".repeat(81)], ["brokerage", " "], ["phone", "call me"], ["email", "nope"], ["email", 5]] as const) {
65 const r = bad({ [field]: value });
66 expect([field, r.ok]).toEqual([field, false]);
67 expect(!r.ok && r.field).toBe(field);
68 }
69 expect(bad({ name: "x".repeat(80) }).ok).toBe(true);
70 expect(agentOf(db).name).toBe("x".repeat(80));
71 });
72
73 test("a role below the required one is refused, and the attempt is audited", () => {
74 const db = openDb(mkdtempSync(join(tmpdir(), "app-profile-role-")));
75 const refused = setProfile(db, user, lee);
76 expect(!refused.ok && refused.error).toBe("forbidden");
77 expect(useDefaults(db, user).ok).toBe(false);
78 expect(setProfile(db, { role: "anon" }, lee)).toMatchObject({ ok: false, error: "signin_required" });
79 expect(getProfile(db, { role: "anon" })).toMatchObject({ ok: false, error: "signin_required" });
80 expect(agentOf(db)).toEqual(defaults);
81 setProfile(db, admin, lee);
82 const rows = db.query<{ outcome: string; allowed: number; resource: string }, []>("SELECT resource, outcome, allowed FROM audit WHERE resource = 'profile' ORDER BY id").all();
83 expect(rows.map((r) => r.outcome)).toEqual(["forbidden", "forbidden", "signin_required", "ok"]);
84 });
85
86 test("a fresh draft signs off with the saved profile; a sent message keeps the words that went out", () => {
87 const db = openDb(mkdtempSync(join(tmpdir(), "app-profile-draft-")));
88 const made = { value: open(db, user, { address: "1 Oak", buyer: "Ann Buyer", seller: "Sam Seller", contractDate: "2026-10-01", closingDate: "2026-11-20" }) };
89 const view = () => {
90 const got = getDeal(db, user, { id: made.value.id });
91 if (!got.ok) throw new Error(got.message);
92 return got.value;
93 };
94 const deadline = view().deadlines[0]!;
95 const first = draftsFor(view(), deadline, agentOf(db))[0]!;
96 expect(first.body).toContain(defaults.name);
97 const ask = { deadlineId: deadline.id, partyId: first.party_id, moment: first.moment };
98 expect(sendReminder(db, user, ask).ok).toBe(true);
99 setProfile(db, admin, lee);
100 const after = draftsFor(view(), view().deadlines[0]!, agentOf(db));
101 expect(after.find((d) => d.party_id === first.party_id && d.moment === first.moment)!.body).toContain(defaults.name);
102 const fresh = after.find((d) => d.sent_at === null)!;
103 expect(fresh.body.endsWith("Lee Park, Bay Homes\n+1 555 0199 · [email protected]")).toBe(true);
104 expect(fresh.body).not.toContain(defaults.name);
105 expect(book([view()], "x.example", new Date(), agentOf(db))).toContain("X-WR-CALDESC:Lee Park\\, Bay Homes");
106 // The terminal reads it too, when drawn.
107 const term = terminal(db, admin, { title: "t", where: "local" });
108 expect(term.screen().join("\n")).toContain("Lee Park, Bay Homes");
109 useDefaults(db, admin);
110 expect(term.screen().join("\n")).toContain(defaults.name);
111 });
112
113 test("the Profile page is prefilled, linked from the header, and saving changes the header and the timeline", async () => {
114 const before = await page("/profile");
115 expect(before).toContain(`value="${defaults.name}"`);
116 expect(before).toContain('href="/profile"');
117 expect(await page("/profile", rita)).not.toContain('action="/profile"');
118 const saved = await form("/profile", lee);
119 expect(saved.status).toBe(303);
120 expect(notice(saved)).toContain("Profile saved");
121 const header = await page("/profile");
122 expect(header).toContain("<b>Lee Park</b><small>Bay Homes</small>");
123 expect(header).toContain('value="[email protected]"');
124 expect(await page("/")).toContain("<b>Lee Park</b>");
125 expect(await (await fetch(base + "/")).text()).toContain("<b>Lee Park</b>");
126 const deals = (await (await fetch(`${base}/api/deals`, { headers: root })).json()) as { id: number }[];
127 expect(await page(`/deals/${deals[0]!.id}/timeline`)).toContain("prepared by Lee Park, Bay Homes");
128 expect(await page(`/deals/${deals[0]!.id}`)).toContain("Lee Park, Bay Homes");
129 const cleared = await form("/profile/defaults", {});
130 expect(notice(cleared)).toContain("defaults stand");
131 expect(await page("/profile")).toContain(`value="${defaults.name}"`);
132 });
133
134 test("a refused form keeps what was typed and names the field; nothing is saved", async () => {
135 const res = await form("/profile", { ...lee, email: "<b>nope" });
136 expect(res.status).toBe(422);
137 const html = await res.text();
138 expect(html).toContain('aria-describedby="email-why"');
139 expect(html).toContain("That is not an email address.");
140 expect(html).toContain('value="Lee Park"');
141 expect(html).toContain('value="&lt;b&gt;nope"');
142 expect(await page("/profile")).toContain(`value="${defaults.name}"`);
143 });
144
145 test("saving is same-origin checked, an admin's only, and refused for anyone else", async () => {
146 const cross = await fetch(`${base}/profile`, { method: "POST", redirect: "manual", headers: { "content-type": "application/x-www-form-urlencoded", "sec-fetch-site": "cross-site", ...root }, body: new URLSearchParams(lee) });
147 expect(cross.status).toBe(403);
148 expect(notice(await form("/profile", lee, rita))).toContain("Only an admin");
149 expect(notice(await form("/profile/defaults", {}, rita))).toContain("Only an admin");
150 expect((await put(lee, rita)).status).toBe(403);
151 expect((await put(lee, {})).status).toBe(401);
152 expect(await page("/profile")).toContain(`value="${defaults.name}"`);
153 });
154
155 test("GET and PUT /api/profile, and the MCP tools, apply the same rules", async () => {
156 const bad = await put({ ...lee, email: "nope" });
157 expect(bad.status).toBe(422);
158 expect(await bad.json()).toMatchObject({ error: "invalid" });
159 expect((await put({ ...lee, phone: "abc" })).status).toBe(422);
160 const ok = await put(lee);
161 expect(ok.status).toBe(200);
162 const got = await (await fetch(`${base}/api/profile`, { headers: rita })).json();
163 expect(got).toEqual({ ...lee, id: 1, saved: true });
164 expect((await fetch(`${base}/api/profile`)).status).toBe(401);
165 const call = (name: string, args: unknown, who: Record<string, string>) =>
166 fetch(`${base}/mcp`, { method: "POST", headers: { "content-type": "application/json", ...who }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }) }).then((r) => r.json() as Promise<any>);
167 const read = await call("get_profile", {}, rita);
168 expect(JSON.parse(read.result.content[0].text)).toMatchObject({ name: "Lee Park" });
169 expect((await call("set_profile", { ...lee, name: "Zed" }, rita)).result.isError).toBe(true);
170 expect((await call("set_profile", { ...lee, email: "x" }, root)).result.isError).toBe(true);
171 expect((await call("set_profile", { ...lee, name: "Zed" }, root)).result.isError).toBeUndefined();
172 expect((await (await fetch(`${base}/api/profile`, { headers: rita })).json()).name).toBe("Zed");
173 expect((await fetch(`${base}/api/profile`, { method: "DELETE", headers: root })).status).toBe(200);
174 expect((await (await fetch(`${base}/api/profile`, { headers: rita })).json()).name).toBe(defaults.name);
175 });
176
177 test("the profile is one read per request, not one per draft", async () => {
178 const db = openDb(mkdtempSync(join(tmpdir(), "app-profile-once-")));
179 let reads = 0;
180 const query = db.query.bind(db);
181 (db as any).query = (sql: string) => {
182 if (sql.includes("FROM profile")) reads++;
183 return query(sql);
184 };
185 const { routes } = await import("./routes.ts");
186 for (let i = 0; i < 5; i++) open(db, user, { address: `${i} Oak`, buyer: "A", seller: "B", contractDate: "2026-10-01", closingDate: "2026-11-20" });
187 reads = 0;
188 const route = routes.find((r) => r.method === "GET" && r.path === "/")!;
189 await route.handle({ request: new Request("http://x/"), url: new URL("http://x/"), db, who: admin, params: {} });
190 expect(reads).toBe(1);
191 });
src/profile.ts added +88
@@ -0,0 +1,88 @@
1 /**
2 * The agent's own details: name, brokerage, phone and email, typed once on
3 * the Profile page and read by every header, timeline, draft and calendar
4 * file. One row in `profile` holds them; with no row, the environment's
5 * values (`env.ts`) are the defaults. A draft already sent keeps its words:
6 * only what is still a draft reads the profile again.
7 */
8
9 import type { Database } from "bun:sqlite";
10 import { agent as defaults, validEmail, validPhone } from "./env.ts";
11 import type { Agent } from "./reminders.ts";
12 import { audited, fail, ok, refuse, type Result } from "./result.ts";
13 import { permit } from "./contract.ts";
14 import type { Who } from "./who.ts";
15

Un-export NAME_MAX unless another module imports it.

16 const NAME_MAX = 80;
17
18 /** The agent as it stands, and whether the agent has saved it (false: the defaults). */
19 export type Profile = Agent & { readonly id: 1; readonly saved: boolean };
20
21 const FIELDS = ["name", "brokerage", "phone", "email"] as const;
22
23 /** The agent the page, the drafts and the files name: the saved row, else the defaults. */
24 export function agentOf(db: Database): Agent {
25 const row = db
26 .query<Agent, []>("SELECT name, brokerage, phone, email FROM profile WHERE id = 1")
27 .get();
28 return row ?? defaults;
29 }
30
31 /** Four fields as the agent typed them, or the first one that fails and why. */
32 export function checkProfile(input: Record<string, unknown>): Result<Agent> {
33 const text = (name: string): string => (typeof input[name] === "string" ? (input[name] as string).trim() : "");
34 const [name, brokerage, phone, email] = FIELDS.map(text) as [string, string, string, string];
35 if (name.length < 1 || name.length > NAME_MAX)
36 return fail("invalid", `Your name is 1 to ${NAME_MAX} characters.`, "name");
37 if (brokerage.length < 1 || brokerage.length > NAME_MAX)
38 return fail("invalid", `The brokerage is 1 to ${NAME_MAX} characters.`, "brokerage");
39 if (!validPhone(phone))
40 return fail("invalid", "A phone number is digits with + ( ) . - or spaces, up to 30 characters.", "phone");
41 if (!validEmail(email)) return fail("invalid", "That is not an email address.", "email");
42 return ok({ name, brokerage, phone, email });
43 }
44
45 const may = (who: Who): Result<null> =>
46 permit(who, "profile", "update") === "yes"
47 ? ok(null)
48 : refuse(who, "Sign in to change the profile.", "Only an admin may change the profile.");
49
50 /** The profile, for whoever the table lets read it. */
51 export function getProfile(db: Database, who: Who): Result<Profile> {
52 if (permit(who, "profile", "read") !== "yes")
53 return refuse(who, "Sign in to see the profile.", "You may not see the profile.");
54 const saved = db.query<{ id: number }, []>("SELECT id FROM profile WHERE id = 1").get() !== null;
55 return ok({ ...agentOf(db), id: 1, saved });
56 }
57
58 /** Save the four fields, all or none; audited either way. */
59 export function setProfile(db: Database, who: Who, input: Record<string, unknown>): Result<Profile> {
60 const allowed = may(who);
61 let out: Result<Profile>;
62 if (!allowed.ok) out = allowed;
63 else {
64 const checked = checkProfile(input);
65 if (!checked.ok) out = checked;
66 else {
67 const a = checked.value;
68 db.query(
69 `INSERT INTO profile (id, name, brokerage, phone, email) VALUES (1, ?1, ?2, ?3, ?4)
70 ON CONFLICT (id) DO UPDATE SET name = excluded.name, brokerage = excluded.brokerage, phone = excluded.phone, email = excluded.email, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now')`,
71 ).run(a.name, a.brokerage, a.phone, a.email);
72 out = ok({ ...a, id: 1, saved: true });
73 }
74 }
75 return audited(db, who, "profile", "update", 1, out);
76 }
77
78 /** Forget the saved row: the environment's values are the agent again. */
79 export function useDefaults(db: Database, who: Who): Result<Profile> {
80 const allowed = may(who);
81 let out: Result<Profile>;
82 if (!allowed.ok) out = allowed;
83 else {
84 db.query("DELETE FROM profile WHERE id = 1").run();
85 out = ok({ ...defaults, id: 1, saved: false });
86 }
87 return audited(db, who, "profile", "update", 1, out);
88 }
src/routes.ts +104 −18
@@ -21,7 +21,7 @@ import {
2121 type Result,
2222 } from "./actions.ts";
2323 import { DEFAULT_LENGTHS } from "./deadlines.ts";
24 import { agent, commit, description, env, standard, forgeUrl, publicOrigin, startedAt, title, version } from "./env.ts";
24 import { commit, description, env, standard, forgeUrl, publicOrigin, startedAt, title, version } from "./env.ts";
2525 import {
2626 asset,
2727 back,
@@ -65,6 +65,9 @@ import {
6565 type NewDeal,
6666 } from "./deals.ts";
6767 import { book, calendar } from "./ics.ts";
68 import { agentOf, getProfile, setProfile, useDefaults, type Profile } from "./profile.ts";
69 import { profilePage } from "./pages/profile.ts";
70 import { permit } from "./contract.ts";
6871 import { rpc } from "./mcp.ts";
6972 import { FIND_REFUSAL, find, query } from "./find.ts";
7073 import { clock } from "./pages/clock.ts";
@@ -105,7 +108,7 @@ export interface Api {
105108 }
106109
107110 export interface Route {
108 readonly method: "GET" | "POST" | "PATCH" | "DELETE";
111 readonly method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
109112 readonly path: string;
110113 readonly handle: (ctx: Context) => Response | Promise<Response>;
111114 readonly api?: Api;
@@ -290,6 +293,17 @@ export const DRAFT: Schema = {
290293 },
291294 required: ["deal_id", "deadline_id", "party_id", "moment", "on", "subject", "body"],
292295 };
296 export const PROFILE: Schema = {
297 type: "object",
298 properties: {
299 name: { type: "string", minLength: 1, maxLength: 80 },
300 brokerage: { type: "string", minLength: 1, maxLength: 80 },
301 phone: { type: "string", maxLength: 30 },
302 email: { type: "string", maxLength: 254 },
303 saved: { type: "boolean", description: "False while the environment's defaults stand." },
304 },
305 required: ["name", "brokerage", "phone", "email"],
306 };
293307 const list = (items: Schema): Schema => ({ type: "array", items });
294308 export const ERROR: Schema = {
295309 type: "object",
@@ -387,11 +401,11 @@ export const routes: readonly Route[] = [
387401 path: "/",
388402 handle: (c) => {
389403 const { notice, open, clear } = readNotice(c.request);
390 if (c.who.role === "anon") return html(welcomePage({ who: c.who, on: today() }), 200, clear);
404 if (c.who.role === "anon") return html(welcomePage({ who: c.who, agent: agentOf(c.db), on: today() }), 200, clear);
391405 const deals = listDeals(c.db, c.who);
392406 if (!deals.ok)
393407 return html(
394 refusedPage({ who: c.who, path: "/", heading: "The clock", error: deals.error, message: deals.message }),
408 refusedPage({ who: c.who, agent: agentOf(c.db), path: "/", heading: "The clock", error: deals.error, message: deals.message }),
395409 200,
396410 clear,
397411 );
@@ -400,6 +414,7 @@ export const routes: readonly Route[] = [
400414 return html(
401415 refusedPage({
402416 who: c.who,
417 agent: agentOf(c.db),
403418 path: "/",
404419 heading: "The clock",
405420 error: "invalid",
@@ -408,7 +423,7 @@ export const routes: readonly Route[] = [
408423 400,
409424 clear,
410425 );
411 return html(clock({ who: c.who, deals: deals.value, on: today(), notice, open, q }), 200, clear);
426 return html(clock({ who: c.who, agent: agentOf(c.db), deals: deals.value, on: today(), notice, open, q }), 200, clear);
412427 },
413428 },
414429 {
@@ -418,10 +433,10 @@ export const routes: readonly Route[] = [
418433 const deals = listDeals(c.db, c.who);
419434 if (!deals.ok)
420435 return html(
421 refusedPage({ who: c.who, path: "/people", heading: "People", error: deals.error, message: deals.message }),
436 refusedPage({ who: c.who, agent: agentOf(c.db), path: "/people", heading: "People", error: deals.error, message: deals.message }),
422437 STATUS[deals.error],
423438 );
424 return html(peoplePage({ who: c.who, people: people(deals.value, today()), on: today() }));
439 return html(peoplePage({ who: c.who, agent: agentOf(c.db), people: people(deals.value, today()), on: today() }));
425440 },
426441 },
427442 {
@@ -430,7 +445,7 @@ export const routes: readonly Route[] = [
430445 handle: (c) => {
431446 const deals = listDeals(c.db, c.who);
432447 if (!deals.ok) return text(deals.message, STATUS[deals.error]);
433 return new Response(book(deals.value, new URL(publicOrigin).hostname), {
448 return new Response(book(deals.value, new URL(publicOrigin).hostname, new Date(), agentOf(c.db)), {
434449 headers: {
435450 "content-type": "text/calendar; charset=utf-8",
436451 "content-disposition": 'attachment; filename="deal-clock.ics"',
@@ -445,7 +460,7 @@ export const routes: readonly Route[] = [
445460 path: "/deals/new",
446461 handle: (c) => {
447462 const { notice, clear } = readNotice(c.request);
448 return html(newDealPage({ who: c.who, on: today(), notice }), 200, clear);
463 return html(newDealPage({ who: c.who, agent: agentOf(c.db), on: today(), notice }), 200, clear);
449464 },
450465 },
451466 {
@@ -457,6 +472,7 @@ export const routes: readonly Route[] = [
457472 return html(
458473 refusedPage({
459474 who: c.who,
475 agent: agentOf(c.db),
460476 path: c.url.pathname,
461477 heading: found.error === "not_found" || found.error === "invalid" ? "No such deal" : "A deal",
462478 error: found.error,
@@ -465,7 +481,7 @@ export const routes: readonly Route[] = [
465481 STATUS[found.error],
466482 );
467483 const { notice, open, clear } = readNotice(c.request);
468 return html(dealPage({ who: c.who, deal: found.value, on: today(), notice, open }), 200, clear);
484 return html(dealPage({ who: c.who, agent: agentOf(c.db), deal: found.value, on: today(), notice, open }), 200, clear);
469485 },
470486 },
471487 {
@@ -475,7 +491,7 @@ export const routes: readonly Route[] = [
475491 handle: (c) => {
476492 const found = getDeal(c.db, c.who, { id: Number(c.params.id) });
477493 if (!found.ok) return text(found.message, STATUS[found.error]);
478 return html(dealSheets(found.value, c.who, today(), "/"));
494 return html(dealSheets(found.value, c.who, today(), "/", agentOf(c.db)));
479495 },
480496 },
481497 {
@@ -487,6 +503,7 @@ export const routes: readonly Route[] = [
487503 return html(
488504 refusedPage({
489505 who: c.who,
506 agent: agentOf(c.db),
490507 path: c.url.pathname,
491508 heading: found.error === "not_found" || found.error === "invalid" ? "No such deal" : "A deal",
492509 error: found.error,
@@ -494,7 +511,7 @@ export const routes: readonly Route[] = [
494511 }),
495512 STATUS[found.error],
496513 );
497 return html(timelinePage({ who: c.who, deal: found.value, on: today() }));
514 return html(timelinePage({ who: c.who, agent: agentOf(c.db), deal: found.value, on: today() }));
498515 },
499516 },
500517 {
@@ -504,7 +521,7 @@ export const routes: readonly Route[] = [
504521 const found = getDeal(c.db, c.who, { id: Number(c.params.id) });
505522 if (!found.ok) return text(found.message, STATUS[found.error]);
506523 const name = found.value.address.replace(/[^A-Za-z0-9]+/g, "-").replace(/^-|-$/g, "").toLowerCase() || "deal";
507 return new Response(calendar(found.value, new URL(publicOrigin).hostname), {
524 return new Response(calendar(found.value, new URL(publicOrigin).hostname, new Date(), agentOf(c.db)), {
508525 headers: {
509526 "content-type": "text/calendar; charset=utf-8",
510527 "content-disposition": `attachment; filename="${name}.ics"`,
@@ -523,7 +540,7 @@ export const routes: readonly Route[] = [
523540 const made = createDeal(c.db, c.who, newDeal(fromForm(f)));
524541 if (made.ok) return back("Deal opened. Every date is on the clock.", `/deals/${made.value.id}`);
525542 if (made.error !== "invalid") return back(made.message, "/deals/new");
526 return html(newDealPage({ who: c.who, on: today(), state: { values: f, problem: made } }), 422);
543 return html(newDealPage({ who: c.who, agent: agentOf(c.db), on: today(), state: { values: f, problem: made } }), 422);
527544 },
528545 },
529546 {
@@ -537,9 +554,9 @@ export const routes: readonly Route[] = [
537554 if (!may.ok) return back(may.message, "/deals/new");
538555 const planned = plan(newDeal(fromForm(f)));
539556 if (!planned.ok)
540 return html(newDealPage({ who: c.who, on: today(), state: { values: f, problem: planned } }), 422);
557 return html(newDealPage({ who: c.who, agent: agentOf(c.db), on: today(), state: { values: f, problem: planned } }), 422);
541558 const preview = { plan: planned.value, dates: plannedDates(planned.value) };
542 return html(newDealPage({ who: c.who, on: today(), state: { values: f, preview } }));
559 return html(newDealPage({ who: c.who, agent: agentOf(c.db), on: today(), state: { values: f, preview } }));
543560 },
544561 },
545562 {
@@ -568,6 +585,75 @@ export const routes: readonly Route[] = [
568585 path: "/samples/restore",
569586 handle: (c) => done(restoreSamples(c.db, c.who), "/", "Sample deals restored."),
570587 },
588 {
589 method: "GET",
590 path: "/profile",
591 handle: (c) => {
592 const { notice, clear } = readNotice(c.request);
593 const got = getProfile(c.db, c.who);
594 if (!got.ok)
595 return html(
596 refusedPage({ who: c.who, agent: agentOf(c.db), path: "/profile", heading: "Profile", error: got.error, message: got.message }),
597 STATUS[got.error],
598 clear,
599 );
600 return html(profilePage({ who: c.who, profile: got.value, mayChange: permit(c.who, "profile", "update") === "yes", notice }), 200, clear);
601 },
602 },
603 {
604 method: "POST",
605 path: "/profile",
606 handle: async (c) => {
607 const f = await form(c);
608 if (f instanceof Response) return f;
609 const saved = setProfile(c.db, c.who, f);
610 if (saved.ok) return back("Profile saved. The header and every unsent reminder carry it.", "/profile");
611 if (saved.error !== "invalid") return back(saved.message, "/profile");
612 const profile = getProfile(c.db, c.who);
613 if (!profile.ok) return back(saved.message, "/profile");
614 return html(profilePage({ who: c.who, profile: profile.value, mayChange: true, state: { values: f, problem: saved } }), 422);
615 },
616 },
617 {
618 method: "POST",
619 path: "/profile/defaults",
620 handle: (c) => done(useDefaults(c.db, c.who), "/profile", "Profile cleared; the defaults stand."),
621 },
622 {
623 method: "GET",
624 path: "/api/profile",
625 handle: (c) => answer(getProfile(c.db, c.who)),
626 api: {
627 summary: "The agent's name, brokerage, phone and email as the header and every reminder's sign-off carry them; saved is false while the environment's defaults stand.",
628 answer: PROFILE,
629 cell: { resource: "profile", verb: "read" },
630 },
631 },
632 {
633 method: "PUT",
634 path: "/api/profile",
635 handle: async (c) => {
636 const body = await readJson(c.request);
637 if (body === undefined) return json({ error: "too_large" }, 413);
638 return answer(setProfile(c.db, c.who, fields(body)));
639 },
640 api: {
641 summary: "Save the agent's four details, all or none; the same checks as the Profile page. Only an admin may.",
642 body: PROFILE,
643 answer: PROFILE,
644 cell: { resource: "profile", verb: "update" },
645 },
646 },
647 {
648 method: "DELETE",
649 path: "/api/profile",
650 handle: (c) => answer(useDefaults(c.db, c.who)),
651 api: {
652 summary: "Forget the saved details: the environment's values are the agent again. Only an admin may.",
653 answer: PROFILE,
654 cell: { resource: "profile", verb: "update" },
655 },
656 },
571657 {
572658 method: "POST",
573659 path: "/deals/:id/address",
@@ -580,7 +666,7 @@ export const routes: readonly Route[] = [
580666 if (saved.error !== "invalid" || f.address === undefined) return back(saved.message, `/deals/${id}`);
581667 const found = getDeal(c.db, c.who, { id });
582668 if (!found.ok) return back(found.message, `/deals/${id}`);
583 return html(dealPage({ who: c.who, deal: found.value, on: today(), problem: { value: f.address, message: saved.message } }), STATUS.invalid);
669 return html(dealPage({ who: c.who, agent: agentOf(c.db), deal: found.value, on: today(), problem: { value: f.address, message: saved.message } }), STATUS.invalid);
584670 },
585671 },
586672 {
@@ -712,7 +798,7 @@ export const routes: readonly Route[] = [
712798 const deals = listDeals(c.db, c.who);
713799 if (!deals.ok) return answer(deals);
714800 const on = today();
715 return json({ on, reminders: dueOn(deals.value, on, agent) });
801 return json({ on, reminders: dueOn(deals.value, on, agentOf(c.db)) });
716802 },
717803 api: {
718804 summary:
src/server.test.ts +2
@@ -188,6 +188,8 @@ test("the MCP server lists the tools and calls them as the caller", async () =>
188188 "remove_party",
189189 "remove_date",
190190 "remove_deal",
191 "get_profile",
192 "set_profile",
191193 "restore_samples",
192194 ]);
193195 const call = (name: string, args: unknown, who = {}) =>
src/terminal.test.ts +29
@@ -563,6 +563,35 @@ test("n declines a Date changed notice with a reason and u undoes it", () => {
563563 expect(n()).toBe(0);
564564 });
565565
566 test("I shows the profile; an admin edits it and goes back to the defaults, and the header follows", () => {
567 const root: Who = { role: "admin", id: "u0", name: "root" };
568 const t = terminal(db, root, { title: "deal-clock", where: "test" });
569 press(t, "I");
570 expect(lines(t).join("\n")).toContain("Not saved");
571 press(t, "e", "Riley Agent\r", "\r", "555 0199\r", "\r");
572 const saved = lines(t).join("\n");
573 expect(saved).toContain("Profile saved.");
574 expect(saved).toContain("Name Riley Agent");
575 expect(saved).toContain("Phone 555 0199");
576 expect(lines(t)[0]).toContain("Riley Agent");
577 press(t, "U", "yes\r");
578 expect(lines(t).join("\n")).toContain("Using the defaults.");
579 expect(lines(t).join("\n")).toContain("Not saved");
580 });
581
582 test("the profile is read-only to a user and shows nothing to a guest", () => {
583 const user = terminal(db, alice, context);
584 press(user, "I", "e");
585 expect(lines(user).join("\n")).toContain("Only an admin may change the profile.");
586 press(user, "U");
587 expect(lines(user).join("\n")).toContain("Only an admin may change the profile.");
588 const guest = terminal(db, { role: "anon" } as Who, context);
589 press(guest, "I", "e");
590 const screen = lines(guest).join("\n");
591 expect(screen).toContain("Sign in to see the profile.");
592 expect(screen).toContain("Sign in to change the profile.");
593 });
594
566595 test("Send in the terminal names the exact address to send from the phone, or says there is none", () => {
567596 /** Open the first reminder still to send on 12 Elm St; answer who it is for. */
568597 const firstPending = () => {
src/terminal.ts +72 −7
@@ -8,6 +8,7 @@
88 * reminders what goes out today; enter reads a draft, e edits its words, s sends it
99 * people each person on the deals with every open date they owe (P)
1010 * timeline a deal's dates as a client would get them (t on a deal)
11 * profile your name, brokerage, phone and email (I); e edits them, U goes back to the defaults
1112 * deal one deal's dates and parties; a adds a date, p a party, A corrects the address, M amends the contract, D removes it
1213 *
1314 * On a date (dates or deal view): x marks it done, u reopens it, m moves it
@@ -53,6 +54,8 @@ import { find, FIND_MAX, query } from "./find.ts";
5354 import { mayRestore, restoreSamples } from "./actions.ts";
5455 import { conflictLine } from "./order.ts";
5556 import { PARTY_LABEL, PARTY_ROLES, type PartyRole } from "./deadlines.ts";
57 import { agentOf, getProfile, setProfile, useDefaults } from "./profile.ts";
58 import { permit } from "./contract.ts";
5659 import { drafts, MOMENT_LABEL, pending, unsent, type Agent, type Draft } from "./reminders.ts";
5760 import type { Result } from "./result.ts";
5861 import type { Who } from "./who.ts";
@@ -65,7 +68,7 @@ const bold = (s: string): string => `${esc}1m${s}${esc}0m`;
6568 const COLOUR: Readonly<Record<Urgency, string>> = { overdue: "31", soon: "33", later: "36", done: "2" };
6669 const tint = (u: Urgency, s: string): string => `${esc}${COLOUR[u]}m${s}${esc}0m`;
6770
68 type View = "dates" | "week" | "people" | "reminders" | "deal" | "messages" | "timeline";
71 type View = "dates" | "week" | "people" | "reminders" | "deal" | "messages" | "timeline" | "profile";
6972 interface Row {
7073 readonly deal: DealView;
7174 readonly date: DeadlineView;
@@ -90,9 +93,11 @@ export interface Terminal {
9093 export function terminal(
9194 db: Database,
9295 me: Who,
93 context: { title: string; where: string; ssh?: string | undefined; agent: Agent; on?: () => string },
96 context: { title: string; where: string; ssh?: string | undefined; agent?: Agent; on?: () => string },
9497 ): Terminal {
9598 const on = context.on ?? today;
99 /** The saved profile unless a caller fixed one: read when drawn, so a save elsewhere shows at once. */
100 const agentNow = (): Agent => context.agent ?? agentOf(db);
96101 let view: View = "dates";
97102 let cursor = 0;
98103 let dealId: number | undefined;
@@ -131,7 +136,7 @@ export function terminal(
131136 const reminderRows = (): { deal: DealView; draft: Draft }[] => {
132137 const day = on();
133138 return deals().flatMap((deal) =>
134 drafts(deal, context.agent)
139 drafts(deal, agentNow())
135140 .filter((r) => pending(r, day))
136141 .map((draft) => ({ deal, draft })),
137142 );
@@ -309,6 +314,43 @@ export function terminal(
309314 return true;
310315 }
311316
317 function onProfile(key: string): void {
318 if (key !== "e" && key !== "U") return;
319 if (permit(me, "profile", "update") !== "yes") {
320 said = me.role === "anon" ? "Sign in to change the profile." : "Only an admin may change the profile.";
321 return;
322 }
323 const now = agentNow();
324 if (key === "e")
325 prompt = {
326 steps: [
327 `Your name (enter keeps ${now.name})`,
328 `Brokerage (enter keeps ${now.brokerage})`,
329 `Phone (enter keeps ${now.phone})`,
330 `Email (enter keeps ${now.email})`,
331 ],
332 answers: [],
333 text: "",
334 finish: ([name, brokerage, phone, email]) =>
335 report(
336 setProfile(db, me, {
337 name: name || now.name,
338 brokerage: brokerage || now.brokerage,
339 phone: phone || now.phone,
340 email: email || now.email,
341 }),
342 "Profile saved.",
343 ),
344 };
345 else
346 prompt = {
347 steps: ["Type yes to use the defaults from the environment"],
348 answers: [],
349 text: "",
350 finish: ([yes]) => (yes === "yes" ? report(useDefaults(db, me), "Using the defaults.") : "Kept."),
351 };
352 }
353
312354 function typing(chunk: string): void {
313355 const p = prompt!;
314356 if (chunk === "\x1b" || chunk === "\x03") {
@@ -384,6 +426,9 @@ export function terminal(
384426 } else if (key === "P") {
385427 view = "people";
386428 cursor = 0;
429 } else if (key === "I") {
430 view = "profile";
431 cursor = 0;
387432 } else if (key === "r") {
388433 view = "reminders";
389434 cursor = 0;
@@ -440,6 +485,7 @@ export function terminal(
440485 showDone = !showDone;
441486 cursor = 0;
442487 } else if (view === "reminders") onReminder(key);
488 else if (view === "profile") onProfile(key);
443489 else if (view === "messages" || view === "timeline") return;
444490 else if (!(view === "deal" && onDeal(key))) onDate(key);
445491 cursor = Math.min(cursor, Math.max(0, rowCount() - 1));
@@ -460,7 +506,7 @@ export function terminal(
460506 const day = on();
461507 const all = deals();
462508 const lines = [
463 `${bold(context.title)} ${context.agent.name}, ${context.agent.brokerage} ${dim(`${context.agent.phone} · ${context.agent.email}`)} ${dim(context.where)} ${dim(me.role === "anon" ? "guest" : `${me.name}${me.role === "admin" ? " (admin)" : ""}`)}`,
509 `${bold(context.title)} ${agentNow().name}, ${agentNow().brokerage} ${dim(`${agentNow().phone} · ${agentNow().email}`)} ${dim(context.where)} ${dim(me.role === "anon" ? "guest" : `${me.name}${me.role === "admin" ? " (admin)" : ""}`)}`,
464510 context.ssh === undefined ? dim("The terminal is off.") : dim(`connect: ${context.ssh}`),
465511 `${spoken(day)} · ${all.length} deals · ${view === "dates" ? bold("[d] dates") : "[d] dates"} · ${view === "week" ? bold("[w] this week") : "[w] this week"} · ${view === "reminders" ? bold("[r] reminders today") : "[r] reminders today"} · ${view === "people" ? bold("[P] people") : "[P] people"}`,
466512 "",
@@ -506,6 +552,21 @@ export function terminal(
506552 lines.push(` ${tint(o.urgency, `${spoken(o.due).padEnd(12)} ${relative(o.due, day).padEnd(12)}`)} ${o.label} — ${o.address}`);
507553 }
508554 }
555 } else if (view === "profile") {
556 const got = getProfile(db, me);
557 if (!got.ok) lines.push(got.message);
558 else {
559 const a = got.value;
560 lines.push(
561 bold("Profile"),
562 dim(a.saved ? "Saved here; every header, draft and calendar file reads it." : "Not saved: the environment's defaults are in use."),
563 "",
564 ` Name ${a.name}`,
565 ` Brokerage ${a.brokerage}`,
566 ` Phone ${a.phone}`,
567 ` Email ${a.email}`,
568 );
569 }
509570 } else if (view === "messages") {
510571 const deal = openDeal();
511572 if (deal === undefined) lines.push(dim("That deal is gone."));
@@ -527,7 +588,7 @@ export function terminal(
527588 const deal = openDeal();
528589 if (deal === undefined) lines.push(dim("That deal is gone."));
529590 else {
530 lines.push(bold(`Client timeline — ${deal.address}`), dim(`${context.agent.name}, ${context.agent.brokerage}`), dim(`${context.agent.phone} · ${context.agent.email}`), "");
591 lines.push(bold(`Client timeline — ${deal.address}`), dim(`${agentNow().name}, ${agentNow().brokerage}`), dim(`${agentNow().phone} · ${agentNow().email}`), "");
531592 timelineRows(deal, day).forEach((r) =>
532593 lines.push(` ${tint(r.urgency, `${r.spoken.padEnd(16)} ${r.status.padEnd(9)}`)} ${r.label} · ${r.name === undefined ? r.role : `${r.role}: ${r.name}`}`),
533594 );
@@ -564,7 +625,11 @@ export function terminal(
564625 else {
565626 if (said !== "") lines.push(...said.split("\n"));
566627 const keys =
567 view === "people"
628 view === "profile"
629 ? permit(me, "profile", "update") === "yes"
630 ? "e edit · U use defaults · d dates · q quit"
631 : "d dates · q quit (only an admin changes the profile)"
632 : view === "people"
568633 ? "P people · d dates · w this week · r reminders · q quit"
569634 : view === "reminders"
570635 ? "j/k move · enter read · e edit · s send · n don't send · u undo · / find · d dates · q quit"
@@ -574,7 +639,7 @@ export function terminal(
574639 ? "b back to the deal · d dates · q quit"
575640 : view === "deal"
576641 ? "j/k move · t client timeline · s messages · x done · u reopen · m move · a add date · p add party · e edit party · A edit address · M amend the contract · X remove date/party · D remove deal · b back · q quit"
577 : `j/k move · x done · u reopen · m move · o open deal · n new deal · c check dates · / find · R restore samples · h ${showDone ? "hide" : "show"} done · w this week · r reminders · P people · q quit`;
642 : `j/k move · x done · u reopen · m move · o open deal · n new deal · c check dates · / find · R restore samples · h ${showDone ? "hide" : "show"} done · w this week · r reminders · P people · I profile · q quit`;
578643 lines.push(dim(me.role === "anon" ? `${keys} · sign in with a key the forge knows to change anything` : keys));
579644 }
580645 return lines;
src/tty.ts +2 −2
@@ -6,12 +6,12 @@
66 */
77
88 import { openDb } from "./db.ts";
9 import { agent, ssh, title, where } from "./env.ts";
9 import { ssh, title, where } from "./env.ts";
1010 import { terminal } from "./terminal.ts";
1111 import { whoAtTty } from "./who.ts";
1212
1313 const esc = "\x1b[";
14 const term = terminal(openDb(), whoAtTty(), { title, where, ssh, agent });
14 const term = terminal(openDb(), whoAtTty(), { title, where, ssh });
1515 const draw = (): void => {
1616 process.stdout.write(`${esc}2J${esc}H${term.screen().join("\r\n")}`);
1717 };

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs