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

The agent adds one line of their own on the Profile page, like "Text me anytime, I answer within the hour", and every new reminder draft carries it above the sign-off #138

Merged opened this

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

Merged

mason/deal-clock:mason/135-the-agent-adds-one-line-of-their-own-on → main 2 commits fork 2 threads · 2 unresolved

  • Merged. mason/135-the-agent-adds-one-line-of-their-own-on was merged into main as 601f210.

Review

Sign in to review this change.
11 files changed +209 −16
README.md +5 −2
@@ -223,10 +223,13 @@ for a compliance file.
223223
224224 The app ships with a sample agent. To carry your own, open **Profile** in the
225225 header and type your name, brokerage, phone (digits, spaces, `+ ( ) - .`) and
226 email once; **Use defaults** goes back to the sample. Only an admin can save it;
226 email once. Below them, **A line of your own at the end of every message** is
227 optional: one line, up to 200 characters, like "Text me anytime, I answer within
228 the hour". Every new draft carries it above the sign-off; sent and held drafts
229 keep their words. **Use defaults** goes back to the sample. Only an admin can save it;
227230 over the API it is `GET/PUT/DELETE /api/profile` (DELETE is Use defaults), over MCP
228231 `get_profile` and `set_profile`. In the terminal press I, then e to edit (enter
229 keeps a field) or U for the defaults; a guest or a non-admin sees it read-only.
232 keeps a field, including the line, which `-` clears) or U for the defaults; a guest or a non-admin sees it read-only.
230233
231234 They show in the header (the phone and email are tap-to-call and
232235 tap-to-write), on the client timeline you hand to buyers and sellers, and in
contract/openapi.json +20
@@ -36,6 +36,11 @@
3636 "type": "string",
3737 "maxLength": 254
3838 },
39 "line": {
40 "type": "string",
41 "maxLength": 200,
42 "description": "One line of the agent's own, no line breaks or control characters, above the sign-off of every new draft; empty for none. On a save, leaving it out keeps the saved line; only an empty string clears it."
43 },
3944 "saved": {
4045 "type": "boolean",
4146 "description": "False while the environment's defaults stand."
@@ -96,6 +101,11 @@
96101 "type": "string",
97102 "maxLength": 254
98103 },
104 "line": {
105 "type": "string",
106 "maxLength": 200,
107 "description": "One line of the agent's own, no line breaks or control characters, above the sign-off of every new draft; empty for none. On a save, leaving it out keeps the saved line; only an empty string clears it."
108 },
99109 "saved": {
100110 "type": "boolean",
101111 "description": "False while the environment's defaults stand."
@@ -137,6 +147,11 @@
137147 "type": "string",
138148 "maxLength": 254
139149 },
150 "line": {
151 "type": "string",
152 "maxLength": 200,
153 "description": "One line of the agent's own, no line breaks or control characters, above the sign-off of every new draft; empty for none. On a save, leaving it out keeps the saved line; only an empty string clears it."
154 },
140155 "saved": {
141156 "type": "boolean",
142157 "description": "False while the environment's defaults stand."
@@ -198,6 +213,11 @@
198213 "type": "string",
199214 "maxLength": 254
200215 },
216 "line": {
217 "type": "string",
218 "maxLength": 200,
219 "description": "One line of the agent's own, no line breaks or control characters, above the sign-off of every new draft; empty for none. On a save, leaving it out keeps the saved line; only an empty string clears it."
220 },
201221 "saved": {
202222 "type": "boolean",
203223 "description": "False while the environment's defaults stand."
src/db.ts +3
@@ -323,6 +323,9 @@ export const migrations: string[] = [
323323 email TEXT NOT NULL,
324324 updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
325325 )`,
326 // A line of the agent's own above the sign-off of every new draft; rows
327 // saved before it have none.
328 `ALTER TABLE profile ADD COLUMN line TEXT NOT NULL DEFAULT '' CHECK (length(line) <= 200)`,
326329 // Which change inside a row an audit row was ("reminder.send"), for the Activity page.
327330 `ALTER TABLE audit ADD COLUMN what TEXT`,
328331 // A status update on the whole deal is a fifth moment, `status`, hung on the
src/line.test.ts added +143
@@ -0,0 +1,143 @@
1 /** The agent's own line: saved on the Profile page, above the sign-off of every new draft. */
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 { addDays, today } from "./dates.ts";
7 import { createDeal, getDeal, holdReminder, moveDeadline, sendReminder } from "./deals.ts";
8 import { openDb } from "./db.ts";
9 import { agentOf, setProfile } from "./profile.ts";
10 import { draftsFor, signOff, statusDrafts } from "./reminders.ts";
11 import { forgetRationing } from "./security.ts";
12 import { serve } from "./server.ts";
13 import { sign, type Who } from "./who.ts";
14
15 const KEY = "a-key-only-the-forge-holds";
16 const dir = mkdtempSync(join(tmpdir(), "app-line-"));
17 const server = serve({ port: 0, dataDir: dir, identityKey: KEY });
18 const base = `http://${server.hostname}:${server.port}`;
19 afterAll(() => server.stop(true));
20 beforeEach(forgetRationing);
21 const identity = `u0|root|admin|${Date.now() + 600_000}`;
22 const root = { "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) };
23 const put = (body: unknown) =>
24 fetch(`${base}/api/profile`, { method: "PUT", headers: { "content-type": "application/json", ...root }, body: JSON.stringify(body) });
25 const dana = { name: "Dana", brokerage: "HP", phone: "(555) 010-0142", email: "[email protected]" };
26 const LINE = "Text me anytime, I answer within the hour";
27
28 const db = openDb(mkdtempSync(join(tmpdir(), "app-line-db-")));
29 const admin: Who = { role: "admin", id: "u0", name: "root" };
30 const made = createDeal(db, admin, { openAnyway: true, address: "1 Oak", buyer: "Ann Buyer", seller: "Sam Seller", contractDate: today(), closingDate: addDays(today(), 40) });
31 if (!made.ok) throw new Error(made.message);
32 for (const p of made.value.parties) db.query("UPDATE party SET contact = ?1 WHERE id = ?2").run(`${p.name.split(" ")[0]!.toLowerCase()}@example.com`, p.id);
33 const view = () => {
34 const got = getDeal(db, admin, { id: made.value.id });
35 if (!got.ok) throw new Error(got.message);
36 return got.value;
37 };
38
39 test("a saved line sits on its own line above the sign-off of a reminder and a status update", () => {
40 expect(setProfile(db, admin, { ...dana, line: ` ${LINE} ` }).ok).toBe(true);
41 const agent = agentOf(db);
42 expect(agent.line).toBe(LINE);
43 const deal = view();
44 const reminder = draftsFor(deal, deal.deadlines[0]!, agent)[0]!;
45 expect(reminder.body.endsWith(`\n\n${LINE}\n${signOff({ ...dana })}`)).toBe(true);
46 const closing = view();
47 const status = statusDrafts(closing, agent)[0]!;
48 expect(status.body.endsWith(`\n\n${LINE}\nDana, HP\n(555) 010-0142 · [email protected]`)).toBe(true);
49 });
50
51 test("an empty line changes nothing", () => {
52 const deal = view();
53 const plain = draftsFor(deal, deal.deadlines[0]!, dana)[0]!;
54 const empty = draftsFor(deal, deal.deadlines[0]!, { ...dana, line: "" })[0]!;
55 expect(empty.body).toBe(plain.body);
56 expect(signOff({ ...dana, line: "" })).toBe("Dana, HP\n(555) 010-0142 · [email protected]");
57 });
58
59 test("201 characters or a line break is refused, and the field keeps what was typed", async () => {
60 expect(setProfile(db, admin, { ...dana, line: "x".repeat(200) }).ok).toBe(true);
61 const long = setProfile(db, admin, { ...dana, line: "x".repeat(201) });
62 expect(long.ok).toBe(false);
63 for (const line of ["one\ntwo", "one\r\ntwo"]) {
64 const r = setProfile(db, admin, { ...dana, line });
65 expect(r.ok).toBe(false);
66 }
67 expect((await put({ ...dana, line: "a\nb" })).status).toBe(422);
68 const form = await fetch(`${base}/profile`, {
69 method: "POST",
70 redirect: "manual",
71 headers: { "content-type": "application/x-www-form-urlencoded", ...root },
72 body: new URLSearchParams({ ...dana, line: "y".repeat(201) }),
73 });
74 expect(form.status).toBe(422);
75 expect(await form.text()).toContain("y".repeat(201));
76 });
77
78 test("over the API the line is read and saved; HTML in it is escaped on the pages", async () => {
79 const hostile = `<script>alert(1)</script> "hi"`;
80 expect((await put({ ...dana, line: hostile })).status).toBe(200);
81 const got = await (await fetch(`${base}/api/profile`, { headers: root })).json();
82 expect(got.line).toBe(hostile);
83 const profile = await (await fetch(`${base}/profile`, { headers: root })).text();
84 expect(profile).not.toContain("<script>alert(1)");
85 expect(profile).toContain("&lt;script&gt;");
86 const spec = await (await fetch(`${base}/openapi.json`, { headers: root })).text();
87 expect(spec).toContain("One line of the agent's own");
88 });
89
90 test("a saved line is in every kind of draft: reminder, day of, late follow-up and date-changed notice", () => {
91 const deal = view();
92 const insp = deal.deadlines.find((d) => d.kind === "inspection")!;
93 const moved = moveDeadline(db, admin, { id: insp.id, due: addDays(insp.due, 5), reason: "x" });
94 expect(moved.ok).toBe(true);
95 const after = view();
96 const agent = { ...dana, line: LINE };
97 const mine = draftsFor(after, after.deadlines.find((d) => d.id === insp.id)!, agent);
98 for (const moment of ["before", "day_of", "late", "moved"])
99 for (const d of mine.filter((x) => x.moment === moment)) {
100 expect(d.body.endsWith(`\n\n${LINE}\n${signOff(dana)}`)).toBe(true);
101 }
102 expect(new Set(mine.map((d) => d.moment))).toEqual(new Set(["before", "day_of", "late", "moved"]));
103 });
104
105 test("a draft sent, or edited and held, keeps its words when the line changes", () => {
106 const deal = view();
107 const withBefore = deal.deadlines.filter((d) => draftsFor(deal, d, dana).some((x) => x.moment === "before"));
108 const [sendOn, holdOn] = [withBefore[0]!, withBefore[1]!];
109 const first = (on: typeof sendOn) => draftsFor(deal, on, dana).find((d) => d.moment === "before")!;
110 const [toSend, toHold] = [first(sendOn), first(holdOn)];
111 const ask = (on: typeof sendOn, d: typeof toSend) => ({ deadlineId: on.id, dealId: deal.id, partyId: d.party_id, moment: d.moment, agent: dana });
112 expect(sendReminder(db, admin, ask(sendOn, toSend)).ok).toBe(true);
113 expect(holdReminder(db, admin, { ...ask(holdOn, toHold), on: toHold.on, body: "My own edited words" }).ok).toBe(true);
114 const agent = { ...dana, line: "A brand new line" };
115 const now = view();
116 const again = (on: typeof sendOn) => draftsFor(now, now.deadlines.find((d) => d.id === on.id)!, agent);
117 const sent = again(sendOn).find((d) => d.moment === "before" && d.party_id === toSend.party_id)!;
118 const held = again(holdOn).find((d) => d.moment === "before" && d.party_id === toHold.party_id)!;
119 expect(sent.sent_at).not.toBeNull();
120 expect(sent.body).toBe(toSend.body);
121 expect(sent.body).not.toContain("A brand new line");
122 expect(held.body).toBe("My own edited words");
123 const fresh = again(sendOn).find((d) => d.moment === "day_of")!;
124 expect(fresh.body).toContain("A brand new line");
125 });
126
127 test("control characters are refused; a save that leaves the line out keeps it, an empty string clears it", () => {
128 for (const line of ["a\tb", "a\vb", "a\fb", "a\u0085b", "a\0b", "a\u2028b"])
129 expect(setProfile(db, admin, { ...dana, line }).ok).toBe(false);
130 expect(setProfile(db, admin, { ...dana, line: LINE }).ok).toBe(true);
131 expect(setProfile(db, admin, { ...dana, name: "Dana W" }).ok).toBe(true);
132 expect(agentOf(db).line).toBe(LINE);
133 expect(setProfile(db, admin, { ...dana, line: "" }).ok).toBe(true);
134 expect(agentOf(db).line).toBeUndefined();
135 });
136
137 test("HTML in the line is escaped on the review page", async () => {
138 const hostile = `<script>alert(7)</script>`;
139 expect((await put({ ...dana, line: hostile })).status).toBe(200);
140 const page = await (await fetch(`${base}/reminders/today`, { headers: root })).text();
141 expect(page).toContain("&lt;script&gt;alert(7)");
142 expect(page).not.toContain("<script>alert(7)");
143 });
src/mcp.ts +1
@@ -512,6 +512,7 @@ export const tools: readonly Tool[] = [
512512 brokerage: { type: "string", maxLength: 80 },
513513 phone: { type: "string", maxLength: 30 },
514514 email: { type: "string", maxLength: 254 },
515 line: { type: "string", maxLength: 200, description: "One line of your own above the sign-off; no line breaks. Leave it out to keep the saved line; an empty string clears it." },
515516 },
516517 required: ["name", "brokerage", "phone", "email"],
517518 },
src/pages/profile.ts +3 −1
@@ -29,7 +29,7 @@ export function profilePage(input: {
2929 const agent: Agent = profile;
3030 const values = state?.values ?? {};
3131 const problem = state?.problem;
32 const val = (name: keyof Agent): string => escape(values[name] ?? agent[name]);
32 const val = (name: keyof Agent): string => escape(values[name] ?? agent[name] ?? "");
3333 const why = (name: string): string =>
3434 problem?.field === name
3535 ? `<span class="field-error" id="${name}-why" role="alert">${escape(problem.message)}</span>`
@@ -46,6 +46,7 @@ export function profilePage(input: {
4646 <label>Brokerage<input class="input" name="brokerage" required maxlength="80" autocomplete="organization" value="${val("brokerage")}"${bad("brokerage")}>${why("brokerage")}</label>
4747 <label>Phone<input class="input" type="tel" name="phone" required maxlength="30" autocomplete="tel" value="${val("phone")}"${bad("phone")}>${why("phone")}</label>
4848 <label>Email<input class="input" type="email" name="email" required maxlength="254" autocomplete="email" value="${val("email")}"${bad("email")}>${why("email")}</label>
49 <label>A line of your own at the end of every message<input class="input" name="line" maxlength="200" value="${val("line")}"${bad("line")}>${why("line")}</label>
4950 <div class="actions">
5051 <button class="button">Save profile</button>
5152 <button class="button button-quiet" formaction="/profile/defaults" formnovalidate>Use defaults</button>
@@ -56,6 +57,7 @@ export function profilePage(input: {
5657 <div><dt class="muted small">Brokerage</dt><dd>${escape(agent.brokerage)}</dd></div>
5758 <div><dt class="muted small">Phone</dt><dd>${escape(agent.phone)}</dd></div>
5859 <div><dt class="muted small">Email</dt><dd>${escape(agent.email)}</dd></div>
60 <div><dt class="muted small">A line of your own</dt><dd>${escape(agent.line ?? "") || "None"}</dd></div>
5961 </dl>
6062 <p class="muted small">Only an admin can change these.</p>`;
6163 const body = `<p class="crumb"><a href="/">← The clock</a></p>
src/profile.ts +18 −8
@@ -14,6 +14,7 @@ import { permit } from "./contract.ts";
1414 import type { Who } from "./who.ts";
1515
1616 const NAME_MAX = 80;
17 const LINE_MAX = 200;
1718
1819 /** The agent as it stands, and whether the agent has saved it (false: the defaults). */
1920 export type Profile = Agent & { readonly id: 1; readonly saved: boolean };
@@ -23,12 +24,14 @@ const FIELDS = ["name", "brokerage", "phone", "email"] as const;
2324 /** The agent the page, the drafts and the files name: the saved row, else the defaults. */
2425 export function agentOf(db: Database): Agent {
2526 const row = db
26 .query<Agent, []>("SELECT name, brokerage, phone, email FROM profile WHERE id = 1")
27 .query<Agent, []>("SELECT name, brokerage, phone, email, line FROM profile WHERE id = 1")
2728 .get();
28 return row ?? defaults;
29 if (row === null) return defaults;
30 const { line, ...rest } = row;
31 return line ? row : rest;
2932 }
3033
31 /** Four fields as the agent typed them, or the first one that fails and why. */
34 /** Five fields as the agent typed them, or the first one that fails and why. */
3235 export function checkProfile(input: Record<string, unknown>): Result<Agent> {
3336 const text = (name: string): string => (typeof input[name] === "string" ? (input[name] as string).trim() : "");
3437 const [name, brokerage, phone, email] = FIELDS.map(text) as [string, string, string, string];
@@ -39,7 +42,11 @@ export function checkProfile(input: Record<string, unknown>): Result<Agent> {
3942 if (!validPhone(phone))
4043 return fail("invalid", "A phone number is digits with + ( ) . - or spaces, up to 30 characters.", "phone");
4144 if (!validEmail(email)) return fail("invalid", "That is not an email address.", "email");
42 return ok({ name, brokerage, phone, email });
45 const line = typeof input.line === "string" ? input.line.trim() : "";
46 if (line.length > LINE_MAX) return fail("invalid", `Your own line is at most ${LINE_MAX} characters.`, "line");
47 if (/[\p{Cc}\u2028\u2029]/u.test(line))
outdated

Refuse every control character, not just CR/LF/U+2028/9, so no stray \v, \f, NUL or U+0085 reaches a draft.

48 return fail("invalid", "Your own line is one line of plain text: no line breaks, tabs or other control characters.", "line");
49 return ok(line ? { name, brokerage, phone, email, line } : { name, brokerage, phone, email });
4350 }
4451
4552 const may = (who: Who): Result<null> =>
@@ -61,14 +68,17 @@ export function setProfile(db: Database, who: Who, input: Record<string, unknown
6168 let out: Result<Profile>;
6269 if (!allowed.ok) out = allowed;
6370 else {
64 const checked = checkProfile(input);
71 // A client that predates the line does not send it, and must not wipe it:
72 // only an explicit empty string clears.
73 const given = typeof input.line === "string" ? input : { ...input, line: agentOf(db).line ?? "" };
74 const checked = checkProfile(given);
6575 if (!checked.ok) out = checked;
6676 else {
6777 const a = checked.value;
6878 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);
79 `INSERT INTO profile (id, name, brokerage, phone, email, line) VALUES (1, ?1, ?2, ?3, ?4, ?5)
80 ON CONFLICT (id) DO UPDATE SET name = excluded.name, brokerage = excluded.brokerage, phone = excluded.phone, email = excluded.email, line = excluded.line, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now')`,
81 ).run(a.name, a.brokerage, a.phone, a.email, a.line ?? "");
7282 out = ok({ ...a, id: 1, saved: true });
7383 }
7484 }
src/reminders.ts +4 −2
@@ -20,11 +20,13 @@ export interface Agent {
2020 readonly brokerage: string;
2121 readonly phone: string;
2222 readonly email: string;
23 /** One line of the agent's own, above the sign-off; empty or absent for none. */
24 readonly line?: string | undefined;
2325 }
2426
25 /** How every draft ends: who to call or write back. */
27 /** How every draft ends: the agent's own line if set, then who to call or write back. */
2628 export const signOff = (agent: Agent): string =>
27 `${agent.name}, ${agent.brokerage}\n${agent.phone} · ${agent.email}`;
29 `${agent.line ? `${agent.line}\n` : ""}${agent.name}, ${agent.brokerage}\n${agent.phone} · ${agent.email}`;
2830
2931 export interface Draft {
3032 readonly deal_id: number;
src/routes.ts +1
@@ -418,6 +418,7 @@ export const PROFILE: Schema = {
418418 brokerage: { type: "string", minLength: 1, maxLength: 80 },
419419 phone: { type: "string", maxLength: 30 },
420420 email: { type: "string", maxLength: 254 },
421 line: { type: "string", maxLength: 200, description: "One line of the agent's own, no line breaks or control characters, above the sign-off of every new draft; empty for none. On a save, leaving it out keeps the saved line; only an empty string clears it." },
421422 saved: { type: "boolean", description: "False while the environment's defaults stand." },
422423 },
423424 required: ["name", "brokerage", "phone", "email"],
src/terminal.test.ts +6 −1
@@ -617,11 +617,16 @@ test("I shows the profile; an admin edits it and goes back to the defaults, and
617617 const t = terminal(db, root, { title: "deal-clock", where: "test" });
618618 press(t, "I");
619619 expect(lines(t).join("\n")).toContain("Not saved");
620 press(t, "e", "Riley Agent\r", "\r", "555 0199\r", "\r");
620 press(t, "e", "Riley Agent\r", "\r", "555 0199\r", "\r", "Text me anytime\r");
621621 const saved = lines(t).join("\n");
622622 expect(saved).toContain("Profile saved.");
623623 expect(saved).toContain("Name Riley Agent");
624624 expect(saved).toContain("Phone 555 0199");
625 expect(saved).toContain("Own line Text me anytime");
626 press(t, "e", "\r", "\r", "\r", "\r", "\r");
627 expect(lines(t).join("\n")).toContain("Own line Text me anytime");
628 press(t, "e", "\r", "\r", "\r", "\r", "-\r");
629 expect(lines(t).join("\n")).toContain("Own line none");
625630 expect(lines(t)[0]).toContain("Riley Agent");
626631 press(t, "U", "yes\r");
627632 expect(lines(t).join("\n")).toContain("Using the defaults.");
src/terminal.ts +5 −2
@@ -9,7 +9,7 @@
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)
1111 * activity who approved, declined or changed what, newest first (L, admins); m only messages, o older, y newer
12 * profile your name, brokerage, phone and email (I); e edits them, U goes back to the defaults
12 * profile your name, brokerage, phone, email and own line (I); e edits them, U goes back to the defaults
1313 * deal one deal's dates and parties; a adds a date, p a party, A corrects the address, C sets the closing time and place, M amends the contract, S drafts a status update for the party under the cursor, D removes it, F marks it fell through (or brings it back), Y changes the side (buyer, listing or both)
1414 *
1515 * On a date (dates or deal view): x marks it done, W waives it (the buyer gave it up), u reopens it or un-waives it, m moves it
@@ -483,16 +483,18 @@ export function terminal(
483483 `Brokerage (enter keeps ${now.brokerage})`,
484484 `Phone (enter keeps ${now.phone})`,
485485 `Email (enter keeps ${now.email})`,
486 `A line of your own above the sign-off (enter keeps ${now.line ? `"${now.line}"` : "none"}, - clears it)`,
486487 ],
487488 answers: [],
488489 text: "",
489 finish: ([name, brokerage, phone, email]) =>
490 finish: ([name, brokerage, phone, email, line]) =>
490491 report(
491492 setProfile(db, me, {
492493 name: name || now.name,
493494 brokerage: brokerage || now.brokerage,
494495 phone: phone || now.phone,
495496 email: email || now.email,
outdated

The line is only preserved, never editable here. Add a prompt so the terminal does what the page does, plus a test.

497 line: line === "-" ? "" : line || (now.line ?? ""),
496498 }),
497499 "Profile saved.",
498500 ),
@@ -774,6 +776,7 @@ export function terminal(
774776 ` Brokerage ${a.brokerage}`,
775777 ` Phone ${a.phone}`,
776778 ` Email ${a.email}`,
779 ` Own line ${a.line ?? dim("none")}`,
777780 );
778781 }
779782 } else if (view === "messages") {

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs