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

The response record says whether the agent is getting faster: this 30 days against the 30 days before #92

Merged opened this

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

Merged

mason/speed-to-lead:mason/85-the-response-record-says-whether-the-age → main 1 commit fork 1 thread · 1 unresolved

  • Merged. mason/85-the-response-record-says-whether-the-age was merged into main as 70cd19b.

Review

Sign in to review this change.
15 files changed +197 −21
README.md +11
@@ -221,6 +221,17 @@ those 30 days says how many leads it sent, the median first reply and how
221221 many were answered under 5 minutes, measured the same way; sources with no
222222 leads are left out.
223223
224 Under the record, one plain line answers "am I getting faster?" by setting
225 the last 30 days beside the 30 days before them, counted by the same rules:
226 "2 min faster than the month before · 71% within 5 minutes, up from 54%".
227 It reads "slower" when you slowed down and "Same pace as the month before"
228 when the middle time is the same; if no lead arrived in the month before,
229 there is no line at all. A lead still waiting counts with its time so far,
230 so a red clock pulls the recent month down. The sample leads include a
231 slower earlier month, so a fresh desk shows an improving line. The figures
232 are `record.earlier` in `GET /leads` and the `list_leads` tool, and the line
233 is on the terminal desk too.
234
224235 Admins can read the **Activity** page (`/activity`): every change and refused attempt in plain sentences, newest first, 50 to a page, with a "Messages sent only" filter. In the terminal an admin presses `a` on the desk (`o` older, `n` newer, `m` messages sent only).
225236
226237 Once you've replied, the clock stops and shows how long it took.
contract/openapi.json +28 −1
@@ -2701,6 +2701,32 @@
27012701 "under_five"
27022702 ]
27032703 }
2704 },
2705 "earlier": {
2706 "type": [
2707 "object",
2708 "null"
2709 ],
2710 "description": "The 30 days before that window, by the same rules (waiting leads count their time so far); null when no lead arrived then. The desk's trend line compares the two.",
2711 "properties": {
2712 "leads": {
2713 "type": "integer",
2714 "description": "Leads that arrived in the earlier window."
2715 },
2716 "median_ms": {
2717 "type": "integer",
2718 "description": "Median time to first reply then, in milliseconds."
2719 },
2720 "within_5_min_pct": {
2721 "type": "integer",
2722 "description": "Whole percent answered (or waiting) under five minutes then."
2723 }
2724 },
2725 "required": [
2726 "leads",
2727 "median_ms",
2728 "within_5_min_pct"
2729 ]
27042730 }
27052731 },
27062732 "required": [
@@ -2709,7 +2735,8 @@
27092735 "replied",
27102736 "median_ms",
27112737 "within_5_min_pct",
2712 "by_source"
2738 "by_source",
2739 "earlier"
27132740 ]
27142741 },
27152742 "show": {
src/actions.test.ts +2 −2
@@ -226,10 +226,10 @@ test("qualified or lost leaves the cadence", () => {
226226 if (!gone.ok) expect(gone.error).toBe("not_found");
227227 });
228228
229 test("the sample desk: sixteen leads, some red, some mid-cadence; only an admin restarts it", () => {
229 test("the sample desk: twenty leads, some red, some mid-cadence; only an admin restarts it", () => {
230230 const sampleDb = openDb(mkdtempSync(join(tmpdir(), "app-sample-")));
231231 expect(resetSample(sampleDb, alice).ok).toBe(false);
232 expect(must(resetSample(sampleDb, root, T0)).leads).toBe(16);
232 expect(must(resetSample(sampleDb, root, T0)).leads).toBe(20);
233233 const listed = must(listLeads(sampleDb, alice, { now: T0.getTime() }));
234234 // A believable first record: 14 leads in 30 days, 57% answered or waiting under 5 minutes.
235235 expect(listed.record).toMatchObject({ leads: 14, replied: 7, within_5_min_pct: 57 });
src/clock.ts +26
@@ -55,6 +55,32 @@ export function recordLine(record: {
5555 return `Median first reply: ${span(record.median_ms)} · ${record.within_5_min_pct}% answered within 5 minutes`;
5656 }
5757
58 /**
59 * The record against the month before, in one line; null when there is
60 * nothing to compare (no earlier leads, or none in this window).
61 * "2 min faster than the month before · 71% within 5 minutes, up from 54%".
62 */
63 export function trendLine(record: {
64 median_ms: number | null;
65 within_5_min_pct: number | null;
66 earlier?: { median_ms: number; within_5_min_pct: number } | null;
67 }): string | null {
68 const { earlier, median_ms: now, within_5_min_pct: pct } = record;
69 if (earlier === undefined || earlier === null || now === null || pct === null)
70 return null;
71 const pace =
72 span(now) === span(earlier.median_ms)
73 ? "Same pace as the month before"
74 : now < earlier.median_ms
75 ? `${span(earlier.median_ms - now)} faster than the month before`
76 : `${span(now - earlier.median_ms)} slower than the month before`;
77 const share =
78 pct === earlier.within_5_min_pct
79 ? `${pct}% within 5 minutes, same as before`
80 : `${pct}% within 5 minutes, ${pct > earlier.within_5_min_pct ? "up" : "down"} from ${earlier.within_5_min_pct}%`;
81 return `${pace} · ${share}`;
82 }
83
5884 /** m:ss, so 48 seconds reads 0:48 and 2 h 5 min reads 125:00. */
5985 function minSec(ms: number): string {
6086 const total = Math.round(ms / 1000);
src/export.test.ts +1 −1
@@ -56,7 +56,7 @@ test("the download has the header, one row per lead, and the file headers", asyn
5656 expect(rows[0]).toEqual([...COLUMNS]);
5757 const all = await (await get("/leads")).json();
5858 expect(rows.length).toBe(1 + all.leads.length);
59 expect(all.leads.length).toBe(16);
59 expect(all.leads.length).toBe(20);
6060 expect(rows[1]!.length).toBe(COLUMNS.length);
6161 expect(["yes", "no"]).toContain(rows[1]![9]!);
6262 expect(["open", "qualified", "lost"]).toContain(rows[1]![4]!);
src/leads.test.ts +36 −1
@@ -12,7 +12,7 @@ import { agent } from "./env.ts";
1212 import { findLead, findMatch, insertLead, readyFor, responseRecord, send } from "./leads.ts";
1313 import { addLead, listAudit, listLeads, setState } from "./actions.ts";
1414 import type { Who } from "./who.ts";
15 import { recordLine, sourceLine } from "./clock.ts";
15 import { recordLine, sourceLine, trendLine } from "./clock.ts";
1616
1717 const NOW = Date.parse("2026-10-30T12:00:00.000Z");
1818 const M = 60_000;
@@ -205,3 +205,38 @@ test("by source: counts, medians, under five, waiting leads by time so far, old
205205 expect(sourceLine(rows[1]!)).toBe("Referral · 1 lead · median 1:00 · 1 answered under 5 min");
206206 expect(responseRecord(fresh(), NOW).by_source).toEqual([]);
207207 });
208
209 test("the month before: same rules, boundary at 30 days, nothing said without earlier leads", () => {
210 const db = fresh();
211 lead(db, 2 * D, 1 * M); // current
212 expect(responseRecord(db, NOW).earlier).toBeNull();
213 expect(trendLine(responseRecord(db, NOW))).toBeNull();
214 lead(db, 30 * D - M, 1 * M); // just inside the current window
215 lead(db, 30 * D + M, 20 * M); // just before it
216 lead(db, 60 * D + M, 1 * M); // too old for either
217 lead(db, 45 * D); // earlier and still waiting: its time so far counts
218 const record = responseRecord(db, NOW);
219 expect(record.leads).toBe(2);
220 expect(record.earlier).toMatchObject({ leads: 2, median_ms: Math.round((20 * M + 45 * D) / 2), within_5_min_pct: 0 });
221 });
222
223 test("the trend sentence: faster, slower, same, and the share", () => {
224 const e = (median_ms: number, within_5_min_pct: number) => ({ median_ms, within_5_min_pct });
225 const line = (median_ms: number, pct: number, earlier: ReturnType<typeof e> | null) =>
226 trendLine({ median_ms, within_5_min_pct: pct, earlier });
227 expect(line(3 * M, 71, e(5 * M, 54))).toBe("2 min faster than the month before · 71% within 5 minutes, up from 54%");
228 expect(line(6 * M, 40, e(5 * M, 54))).toBe("1 min slower than the month before · 40% within 5 minutes, down from 54%");
229 expect(line(3 * M, 54, e(3 * M, 54))).toBe("Same pace as the month before · 54% within 5 minutes, same as before");
230 expect(line(3 * M, 54, null)).toBeNull();
231 expect(trendLine({ median_ms: null, within_5_min_pct: null, earlier: e(M, 1) })).toBeNull();
232 });
233
234 test("a red clock now pulls the current window down against the month before", () => {
235 const db = fresh();
236 lead(db, 40 * D, 10 * M);
237 lead(db, 2 * D, 1 * M);
238 expect(trendLine(responseRecord(db, NOW))).toContain("faster");
239 lead(db, 3 * D); // waiting three days
240 lead(db, 4 * D);
241 expect(trendLine(responseRecord(db, NOW))).toContain("slower");
242 });
src/leads.ts +29 −8
@@ -461,6 +461,15 @@ export interface ResponseRecord {
461461 readonly within_5_min_pct: number | null;
462462 /** The same, one entry per source that had leads in the window, most leads first. */
463463 readonly by_source: readonly SourceRecord[];
464 /** The 30 days before those, by the same rules; null when no lead arrived then. */
465 readonly earlier: EarlierRecord | null;
466 }
467
468 /** The window before the current one: what the trend line compares against. */
469 export interface EarlierRecord {
470 readonly leads: number;
471 readonly median_ms: number;
472 readonly within_5_min_pct: number;
464473 }
465474
466475 /** How fast one lead source was answered over the same window. */
@@ -486,14 +495,18 @@ export const RECORD_DAYS = 30;
486495 * its time so far, so the numbers cannot improve by ignoring red clocks.
487496 */
488497 export function responseRecord(db: Database, now: number): ResponseRecord {
489 const since = new Date(now - RECORD_DAYS * DAY_MS).toISOString();
490 const all = db
498 const cut = now - RECORD_DAYS * DAY_MS;
499 const since = new Date(cut - RECORD_DAYS * DAY_MS).toISOString();
500 const cutIso = new Date(cut).toISOString();
501 // One pass: the earlier window is read with the same rules as the current one.
502 const rows = db
491503 .query<{ source: Source; created_at: string; replied_at: string | null }, [string]>(
492504 "SELECT source, created_at, replied_at FROM lead WHERE created_at >= ?1",
493505 )
494506 .all(since)
495507 .map((row) => ({
496508 source: row.source,
509 current: row.created_at >= cutIso,
497510 ms: Math.max(
498511 0,
499512 (row.replied_at === null ? now : Date.parse(row.replied_at)) -
@@ -502,6 +515,8 @@ export function responseRecord(db: Database, now: number): ResponseRecord {
502515 replied: row.replied_at !== null,
503516 }))
504517 .sort((a, b) => a.ms - b.ms);
518 const all = rows.filter((w) => w.current);
519 const before = rows.filter((w) => !w.current);
505520 const n = all.length;
506521 const groups = new Map<Source, number[]>();
507522 for (const w of all) {
@@ -522,16 +537,22 @@ export function responseRecord(db: Database, now: number): ResponseRecord {
522537 leads: n,
523538 replied: all.filter((w) => w.replied).length,
524539 median_ms: n === 0 ? null : medianOf(all.map((w) => w.ms)),
525 within_5_min_pct:
526 n === 0
527 ? null
528 : Math.round(
529 (100 * all.filter((w) => w.ms < FIVE_MIN_MS).length) / n,
530 ),
540 within_5_min_pct: n === 0 ? null : pctUnderFive(all),
531541 by_source,
542 earlier:
543 before.length === 0
544 ? null
545 : {
546 leads: before.length,
547 median_ms: medianOf(before.map((w) => w.ms)),
548 within_5_min_pct: pctUnderFive(before),
549 },
532550 };
533551 }
534552
553 const pctUnderFive = (w: readonly { ms: number }[]): number =>
554 Math.round((100 * w.filter((x) => x.ms < FIVE_MIN_MS).length) / w.length);
555
535556 /** A lead arrives at `at`, with its first reply drafted. Returns its id. */
536557 export function insertLead(
537558 db: Database,
src/mcp.ts +1 −1
@@ -79,7 +79,7 @@ export const tools: readonly Tool[] = [
7979 {
8080 name: "list_leads",
8181 description:
82 "The desk: your response record (median first reply, share answered within 5 minutes, last 30 days, and the same per lead source as record.by_source) and the leads (optionally only those that need you, are in follow-up, or are closed), newest first, with what is ready to approve.",
82 "The desk: your response record (median first reply, share answered within 5 minutes, last 30 days, and the same per lead source as record.by_source, and how the 30 days before compare as record.earlier) and the leads (optionally only those that need you, are in follow-up, or are closed), newest first, with what is ready to approve.",
8383 inputSchema: {
8484 type: "object",
8585 properties: {
src/pages/desk.ts +7 −2
@@ -6,7 +6,7 @@
66 import { day, clock, consent, source, starForm, STATE_LABEL } from "./parts.ts";
77 import { deskTitle, layout } from "./layout.ts";
88 import { escape } from "../http.ts";
9 import { recordLine, sourceLine } from "../clock.ts";
9 import { recordLine, sourceLine, trendLine } from "../clock.ts";
1010 import { isAfterShowing, isBeforeShowing, isAnswer, isCheckIn } from "../drafts.ts";
1111 import { FINISHED_ACTION, FINISHED_LABEL } from "../finished.ts";
1212 import { dateName } from "../putaway.ts";
@@ -19,6 +19,11 @@ import type { SignInPreview } from "../actions.ts";
1919 import { MAX_SIGNIN_TEXT } from "../signins.ts";
2020 import type { Who } from "../who.ts";
2121
22 const trendHtml = (record: ResponseRecord): string => {
23 const line = trendLine(record);
24 return line === null ? "" : `<p class="record-trend muted">${escape(line)}</p>`;
25 };
26
2227 export function deskPage(input: {
2328 who: Who;
2429 agent: Agent;
@@ -65,7 +70,7 @@ export function deskPage(input: {
6570 const answers = leads.filter((l) => l.ready !== null && isAnswer(l.ready.day)).length;
6671 const due = leads.filter((l) => l.ready !== null && l.ready.day > 0 && !isAnswer(l.ready.day)).length;
6772 const summary = `<p class="summary" aria-live="polite"><b>${waiting}</b> waiting for a first reply <span aria-hidden="true">·</span> <b>${due}</b> follow-up${due === 1 ? "" : "s"} due today${answers === 0 ? "" : ` <span aria-hidden="true">·</span> <b>${answers}</b> wrote back`}</p>`;
68 const record = input.record === undefined ? "" : `<p class="record">${escape(recordLine(input.record))}</p>${input.record.by_source.map((r) => `<p class="record-source muted">${escape(sourceLine(r))}</p>`).join("")}<p class="muted">${RECORD_NOTE}</p>`;
73 const record = input.record === undefined ? "" : `<p class="record">${escape(recordLine(input.record))}</p>${trendHtml(input.record)}${input.record.by_source.map((r) => `<p class="record-source muted">${escape(sourceLine(r))}</p>`).join("")}<p class="muted">${RECORD_NOTE}</p>`;
6974 const q = input.q ?? "";
7075 const views =
7176 counts === undefined
src/routes.ts +12 −1
@@ -334,8 +334,19 @@ export const DESK: Schema = {
334334 required: ["source", "count", "median_ms", "under_five"],
335335 },
336336 },
337 earlier: {
338 type: ["object", "null"],
339 description:
340 "The 30 days before that window, by the same rules (waiting leads count their time so far); null when no lead arrived then. The desk's trend line compares the two.",
341 properties: {
342 leads: { type: "integer", description: "Leads that arrived in the earlier window." },
343 median_ms: { type: "integer", description: "Median time to first reply then, in milliseconds." },
344 within_5_min_pct: { type: "integer", description: "Whole percent answered (or waiting) under five minutes then." },
345 },
346 required: ["leads", "median_ms", "within_5_min_pct"],
347 },
337348 },
338 required: ["days", "leads", "replied", "median_ms", "within_5_min_pct", "by_source"],
349 required: ["days", "leads", "replied", "median_ms", "within_5_min_pct", "by_source", "earlier"],
339350 },
340351 show: { enum: [...VIEWS], description: "The view listed." },
341352 q: { type: "string", description: "The search that narrowed the desk; empty when none." },
src/sample.test.ts +34
@@ -8,12 +8,18 @@ import { lostCounts } from "./lost.ts";
88 import { activityPage } from "./pages/activity.ts";
99 import { currentAgent } from "./profile.ts";
1010 import { INQUIRIES, SAMPLES, seed } from "./sample.ts";
11 import { deskPage } from "./pages/desk.ts";
12 import { trendLine } from "./clock.ts";
1113 import { terminal, plain } from "./terminal.ts";
1214 import type { Who } from "./who.ts";
1315
1416 const alice: Who = { role: "user", id: "u1", name: "alice" };
1517 const root: Who = { role: "admin", id: "u0", name: "root" };
1618 const anon: Who = { role: "anon" } as Who;
19 const must = <T>(r: { ok: boolean; value?: T }): T => {
20 if (!r.ok) throw new Error("refused");
21 return r.value as T;
22 };
1723 const fresh = () => openDb(mkdtempSync(join(tmpdir(), "app-inq-")));
1824 const names = (db: ReturnType<typeof fresh>): string[] => {
1925 const r = listLeads(db, alice);
@@ -102,3 +108,31 @@ test("the sample desk's lost leads carry real, varied reasons, and the Activity
102108 expect(html).toContain("bought with another agent");
103109 expect(html).not.toContain("no reason given");
104110 });
111
112 test("a fresh desk shows an improving line, and restarting the samples keeps it", () => {
113 const db = fresh();
114 const T = Date.parse("2026-11-08T12:00:00.000Z");
115 seed(db, new Date(T));
116 const line = trendLine(must(listLeads(db, alice, { now: T })).record);
117 expect(line).toMatch(/faster than the month before · \d+% within 5 minutes, up from \d+%/);
118 must(resetSample(db, root, new Date(T + 86_400_000)));
119 expect(trendLine(must(listLeads(db, alice, { now: T + 86_400_000 })).record)).toContain("faster");
120 });
121
122 test("the desk page and the terminal print the line, escaped", () => {
123 const record = {
124 days: 30, leads: 2, replied: 2, median_ms: 60_000, within_5_min_pct: 100, by_source: [],
125 earlier: { leads: 1, median_ms: 300_000, within_5_min_pct: 0 },
126 };
127 const page = deskPage({ who: alice, agent: currentAgent(fresh()), leads: [], mayAdd: false, mayStar: false, mayReset: false, record });
128 expect(page).toContain('<p class="record-trend muted">4 min faster than the month before · 100% within 5 minutes, up from 0%</p>');
129 const none = deskPage({ who: alice, agent: currentAgent(fresh()), leads: [], mayAdd: false, mayStar: false, mayReset: false, record: { ...record, earlier: null } });
130 expect(none).not.toContain("record-trend");
131 expect(trendLine({ ...record, earlier: { median_ms: 5, within_5_min_pct: 1 } })).not.toContain("<");
132 });
133
134 test("the terminal desk header carries the line", () => {
135 const db = fresh();
136 seed(db, new Date());
137 expect(terminal(db, alice).screen(100).map(plain).join("\n")).toMatch(/faster than the month before/);
138 });
src/sample.ts +5
@@ -86,6 +86,11 @@ export const SAMPLES: readonly Sample[] = [
8686 person("Owen Hart", "zillow", false, "Is 55 Cedar Ln still on the market? We'd like a second showing.", { ago: 9 * D, answeredIn: 2 * M + 40 * S, touched: [1, 3], closed: { state: "lost", reason: "bought_elsewhere" } }),
8787 person("Nadia Petrov", "website", true, "We might sell, but not before our kids finish school in two years. What should we do now?", { ago: 12 * D, answeredIn: 3 * M + 5 * S, touched: [1, 3], closed: { state: "lost", reason: "not_ready" } }),
8888 person("Carl Dunn", "referral", false, "A friend gave me your name. Call me about listing the duplex.", { ago: 20 * D, answeredIn: 5 * M, touched: [1, 3, 7], closed: { state: "lost", reason: "never_answered" } }),
89 // The month before: slower, so a fresh desk shows the agent improving.
90 person("Fiona Walsh", "zillow", false, "Is the Birch St listing still open? Would like to see it Saturday.", { ago: 38 * D, answeredIn: 14 * M, touched: [1, 3], closed: { state: "lost", reason: "not_ready" } }),
91 person("Gus Moreno", "website", false, "What are closing costs for a $450k purchase here?", { ago: 42 * D, answeredIn: 22 * M, touched: [1, 3], closed: { state: "lost", reason: "bought_elsewhere" } }),
92 person("Imani Reed", "referral", false, "Referred by a coworker. Looking to buy within the year.", { ago: 47 * D, answeredIn: 7 * M, touched: [1, 3], closed: { state: "lost", reason: "not_ready" } }),
93 person("Pavel Sokol", "open_house", false, "Signed in at the Cedar Ct open house; send details please.", { ago: 52 * D, answeredIn: 11 * M, touched: [1, 3], closed: { state: "lost", reason: "not_ready" } }),
8994 person("Ruth Okafor", "website", false, "Looking at starter homes under $400k. Can you send a few options?", { ago: 34 * D, answeredIn: 2 * M + 10 * S, touched: [1, 3, 7, 14, 30] }),
9095 ];
9196
src/search.test.ts +2 −2
@@ -37,8 +37,8 @@ test("a name, an email or a phone finds the lead, in any case", () => {
3737 });
3838
3939 test("no search is the whole desk", () => {
40 expect(names({}).length).toBe(16);
41 expect(names({ q: "" }).length).toBe(16);
40 expect(names({}).length).toBe(20);
41 expect(names({ q: "" }).length).toBe(20);
4242 });
4343
4444 test("a search combines with the view", () => {
src/terminal.test.ts +1 −1
@@ -412,7 +412,7 @@ test("x on the desk shows the leads as CSV, for those who may list; esc goes bac
412412 const t = terminal(db, alice);
413413 t.key("x");
414414 const screen = read(t);
415 expect(screen).toContain("16 leads as CSV");
415 expect(screen).toContain("20 leads as CSV");
416416 expect(screen).toContain("name,email,phone,source,status");
417417 expect(screen).toContain("Maria Gonzalez");
418418 t.key("\x1b");
src/terminal.ts +2 −1
@@ -65,7 +65,7 @@ import { MAX_SIGNIN_LINES } from "./signins.ts";
6565 import { dateName, MAX_AWAY_DAYS } from "./putaway.ts";
6666 import { showingLine, showingWhen } from "./showings.ts";
6767 import { answers, callLine, OUTCOME_LABEL, OUTCOMES, type Outcome } from "./calls.ts";
68 import { between, elapsed, recordLine, sourceLine, tone } from "./clock.ts";
68 import { between, elapsed, recordLine, sourceLine, tone, trendLine } from "./clock.ts";
6969 import { permit } from "./contract.ts";
7070 import { goesLabel, isQuiet, nextOpening, RECORD_NOTE } from "./quiet.ts";
7171 import { said as saidOf } from "./sentences.ts";
@@ -275,6 +275,7 @@ export function terminal(
275275 const zone = currentAgent(db).timeZone;
276276 const lines: string[] = [
277277 dim(recordLine(listed.value.record)),
278 ...(trendLine(listed.value.record) === null ? [] : [dim(trendLine(listed.value.record)!)]),

Nit: compute trendLine once into a const instead of calling it twice with !.

278279 ...listed.value.record.by_source.map((r) => dim(sourceLine(r))),
279280 dim(RECORD_NOTE),
280281 VIEWS.map((v) => {

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs