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

New deal starts from the agent's own standard contingency lengths, set once, so a market with a 7-day inspection does not retype it every deal #55

Merged opened this

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

Merged

mason/deal-clock:mason/52-new-deal-starts-from-the-agent-s-own-sta → main 2 commits fork 2 threads · 2 unresolved

  • Merged. mason/52-new-deal-starts-from-the-agent-s-own-sta was merged into main as fda7b3a.

Review

Sign in to review this change.
9 files changed +182 −32
README.md +14
@@ -139,6 +139,20 @@ your phone and email, so a party can call or write back straight from it.
139139 Reminders you already sent keep the words you approved. A phone or email that
140140 does not look right is ignored in favour of the sample, with a line in the log.
141141
142 Your contracts may use other standard contingency lengths. Set them once and
143 every New deal form, its date preview, the API and the MCP tool start from them
144 (you can still change any length for one deal):
145
146 - `DEAL_CLOCK_INSPECTION_DAYS` (brief: 10), `DEAL_CLOCK_APPRAISAL_DAYS` (21),
147 `DEAL_CLOCK_FINANCING_DAYS` (30), `DEAL_CLOCK_TITLE_DAYS` (14): days after the
148 contract date.
149 - `DEAL_CLOCK_WALKTHROUGH_DAYS` (1): days before closing.
150 - `DEAL_CLOCK_BUSINESS_DAYS`: `1` to count business days by default; otherwise
151 calendar days.
152
153 A length that is missing, not a whole number, or outside 0 to 180 is the
154 brief's, with a line in the log. The sample deals always use the brief's.
155
142156 ## What is real, and what is not yet
143157
144158 - **Real:** the dates and their math, mark done, moves with their reasons,
src/deadlines.ts +2 −8
@@ -6,6 +6,7 @@
66 */
77
88 import { addBusinessDays, addDays, daysBetween } from "./dates.ts";
9 import { standard } from "./env.ts";
910
1011 export const PARTY_ROLES = [
1112 "buyer",
@@ -113,14 +114,7 @@ export interface Lengths {
113114 /** Days before closing. */
114115 readonly walkthrough: number;
115116 }
116 export const DEFAULT_LENGTHS: Lengths = {
117 inspection: 10,
118 appraisal: 21,
119 financing: 30,
120 title: 14,
121 walkthrough: 1,
122 };
123 export const LENGTH_MAX = 180;
117 export const DEFAULT_LENGTHS: Lengths = standard.lengths;
124118
outdated

Re-exporting LENGTH_MAX only to keep old imports working; point importers at env.ts instead.

125119 export interface Planned {
126120 readonly kind: Kind;
src/deals.ts +4 −3
@@ -14,13 +14,12 @@ import {
1414 isClosed,
1515 isPartyRole,
1616 KIND,
17 LENGTH_MAX,
1817 schedule,
1918 type Kind,
2019 type Lengths,
2120 type PartyRole,
2221 } from "./deadlines.ts";
23 import { agent as defaultAgent } from "./env.ts";
22 import { agent as defaultAgent, LENGTH_MAX, standard } from "./env.ts";
2423 import { emit } from "./live.ts";
2524 import { draftsFor, type Agent, type Draft } from "./reminders.ts";
2625 import { audited, fail, ok, refuse, type Result } from "./result.ts";
@@ -400,7 +399,9 @@ export function plan(input: NewDeal): Result<Plan> {
400399 lengths[key] = n;
401400 }
402401 const businessDays =
403 input.businessDays === true || input.businessDays === "on" || input.businessDays === "1";
402 input.businessDays === undefined
403 ? standard.businessDays
404 : input.businessDays === true || input.businessDays === "on" || input.businessDays === "1";
404405 return ok({ address, buyer, seller, contractDate, closingDate, lengths, businessDays });
405406 }
406407
src/env.ts +37
@@ -52,3 +52,40 @@ export const agent = {
5252 phone: setting("DEAL_CLOCK_PHONE", "(555) 010-0142", validPhone),
5353 email: setting("DEAL_CLOCK_EMAIL", "[email protected]", validEmail),
5454 } as const;
55
56 /** The brief's contingency lengths, in days: what a new deal starts from unless the agent says otherwise. */
57 export const BRIEF_LENGTHS = {
58 inspection: 10,
59 appraisal: 21,
60 financing: 30,
61 title: 14,
62 walkthrough: 1,
63 } as const;
64 export const LENGTH_MAX = 180;
65
66 /**
67 * The agent's standard lengths from `DEAL_CLOCK_<NAME>_DAYS` and whether they
68 * count business days. A missing, non-integer or out-of-range value is the
69 * brief's, with one line in the log; it never stops the boot.
70 */
71 export function resolveLengths(source: Record<string, string | undefined>): {
72 lengths: { -readonly [K in keyof typeof BRIEF_LENGTHS]: number };
73 businessDays: boolean;
74 } {
75 const lengths = { ...BRIEF_LENGTHS } as { -readonly [K in keyof typeof BRIEF_LENGTHS]: number };
76 for (const key of Object.keys(BRIEF_LENGTHS) as (keyof typeof BRIEF_LENGTHS)[]) {
77 const name = `DEAL_CLOCK_${key.toUpperCase()}_DAYS`;
78 const v = (source[name] ?? "").trim();
79 if (v === "") continue;
80 const n = Number(v);
81 if (/^\d{1,3}$/.test(v) && n <= LENGTH_MAX) lengths[key] = n;
82 else console.warn(`${name} is not a whole number of days, 0 to ${LENGTH_MAX}; using ${BRIEF_LENGTHS[key]}`);
83 }
84 const raw = (source.DEAL_CLOCK_BUSINESS_DAYS ?? "").trim().toLowerCase();
85 if (raw !== "" && !["1", "0", "true", "false"].includes(raw))
86 console.warn("DEAL_CLOCK_BUSINESS_DAYS is not valid; counting calendar days");
87 return { lengths, businessDays: raw === "1" || raw === "true" };
88 }
89
90 /** What a new deal starts from: the form, its preview, the API and the MCP tool all read this one set. */
91 export const standard = resolveLengths(process.env);
src/lengths.test.ts added +94
@@ -0,0 +1,94 @@
1 /** The agent's standard contingency lengths: set once, read by the form, preview, API and MCP. */
2 import { expect, test } from "bun:test";
3 import { BRIEF_LENGTHS, resolveLengths } from "./env.ts";
4
5 test("nothing set: the brief's lengths, calendar days", () => {
6 const r = resolveLengths({});
7 expect(r.lengths).toEqual({ inspection: 10, appraisal: 21, financing: 30, title: 14, walkthrough: 1 });
8 expect(r.businessDays).toBe(false);
9 expect(BRIEF_LENGTHS.inspection).toBe(10);
10 });
11
12 test("set values replace the brief's; bad ones fall back without throwing", () => {
13 const r = resolveLengths({
14 DEAL_CLOCK_INSPECTION_DAYS: "7",
15 DEAL_CLOCK_APPRAISAL_DAYS: "abc",
16 DEAL_CLOCK_FINANCING_DAYS: "181",
17 DEAL_CLOCK_TITLE_DAYS: "-3",
18 DEAL_CLOCK_WALKTHROUGH_DAYS: "0",
19 DEAL_CLOCK_BUSINESS_DAYS: "1",
20 });
21 expect(r.lengths).toEqual({ inspection: 7, appraisal: 21, financing: 30, title: 14, walkthrough: 0 });
22 expect(r.businessDays).toBe(true);
23 expect(resolveLengths({ DEAL_CLOCK_TITLE_DAYS: "2.5" }).lengths.title).toBe(14);
24 });
25
26 test("a set value changes the form's number, the computed dates and the API default", async () => {
27 const script = `
28 const { plan } = await import("./src/deals.ts");
29 const { newDealPage } = await import("./src/pages/deal.ts");
30 const p = plan({ address: "1 Oak", buyer: "A", seller: "B", contractDate: "2026-10-01", closingDate: "2026-12-01" });
31 const html = newDealPage({ who: { role: "user", id: "u", name: "u" }, on: "2026-10-01" });
32 console.log(JSON.stringify({ i: p.value.lengths.inspection, biz: p.value.businessDays,
33 field: /name="inspection"[^>]*value="(\\d+)"/.exec(html)?.[1], note: html.includes("standard") }));`;
34 const run = async (env: Record<string, string>) => {
35 const proc = Bun.spawn([process.execPath, "-e", script], { env: { ...process.env, ...env }, stdout: "pipe", stderr: "ignore" });
36 return JSON.parse(await new Response(proc.stdout).text());
37 };
38 expect(await run({ DEAL_CLOCK_INSPECTION_DAYS: "7" })).toEqual({ i: 7, biz: false, field: "7", note: true });
39 expect(await run({ DEAL_CLOCK_INSPECTION_DAYS: "x" })).toEqual({ i: 10, biz: false, field: "10", note: true });
40 });
41
42 test("with business days as the agent's standard, a form's unticked box still means calendar days", async () => {
43 const script = `
44 const { mkdtempSync } = await import("node:fs");
45 const { tmpdir } = await import("node:os");
46 const { join } = await import("node:path");
47 const { serve } = await import("./src/server.ts");
48 const { sign } = await import("./src/who.ts");
49 const KEY = "k";
50 const server = serve({ port: 0, dataDir: mkdtempSync(join(tmpdir(), "app-len-")), identityKey: KEY });
51 const base = "http://" + server.hostname + ":" + server.port;
52 const identity = "u1|alice|user|" + (Date.now() + 60000);
53 const who = { "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) };
54 const fields = { address: "1 Oak", buyer: "A", seller: "B", contract_date: "2026-10-02", closing_date: "2026-12-01" };
55 const form = () => { const f = new FormData(); for (const [k, v] of Object.entries(fields)) f.set(k, v); return f; };
56 const first = await (await fetch(base + "/deals/new", { headers: who })).text();
57 const check = await (await fetch(base + "/deals/check", { method: "POST", body: form(), headers: who })).text();
58 const posted = await fetch(base + "/deals", { method: "POST", body: form(), headers: who, redirect: "manual" });
59 const formPage = await (await fetch(base + posted.headers.get("location"), { headers: who })).text();
60 const api = await fetch(base + "/api/deals", { method: "POST", headers: { ...who, "content-type": "application/json" }, body: JSON.stringify(fields) });
61 const apiBody = await api.json();
62 const apiPage = await (await fetch(base + "/deals/" + apiBody.id, { headers: who })).text();
63 const mcp = await (await fetch(base + "/mcp", { method: "POST", headers: { ...who, "content-type": "application/json" },
64 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "open_deal", arguments: fields } }) })).json();
65 const mcpId = JSON.parse(mcp.result.content[0].text).id;
66 const mcpPage = await (await fetch(base + "/deals/" + mcpId, { headers: who })).text();
67 const list = await (await fetch(base + "/mcp", { method: "POST", headers: { ...who, "content-type": "application/json" },
68 body: JSON.stringify({ jsonrpc: "2.0", id: 2, method: "tools/list" }) })).json();
69 const schema = list.result.tools.find((t) => t.name === "open_deal").inputSchema.properties;
70 console.log(JSON.stringify({
71 firstTicked: first.includes('name="business_days" checked'),
72 checkTicked: check.includes('name="business_days" checked'),
73 formBiz: formPage.includes("business days"),
74 apiBiz: apiPage.includes("business days"),
75 mcpBiz: mcpPage.includes("business days"),
76 mcpInspection: schema.inspection.default, mcpBizDefault: schema.business_days.default,
77 }));
78 server.stop(true);`;
79 const proc = Bun.spawn([process.execPath, "-e", script], {
80 env: { ...process.env, DEAL_CLOCK_BUSINESS_DAYS: "1", DEAL_CLOCK_INSPECTION_DAYS: "7" },
81 stdout: "pipe",
82 stderr: "pipe",
83 });
84 const out = await new Response(proc.stdout).text();
85 expect(JSON.parse(out)).toEqual({
86 firstTicked: true,
87 checkTicked: false,
88 formBiz: false,
89 apiBiz: true,
90 mcpBiz: true,
91 mcpInspection: 7,
92 mcpBizDefault: true,
93 });
94 });
src/mcp.ts +8 −8
@@ -9,7 +9,7 @@
99 import type { Database } from "bun:sqlite";
1010 import { restoreSamples, type Result } from "./actions.ts";
1111 import { today } from "./dates.ts";
12 import { PARTY_ROLES } from "./deadlines.ts";
12 import { DEFAULT_LENGTHS, PARTY_ROLES } from "./deadlines.ts";
1313 import {
1414 addDeadline,
1515 addParty,
@@ -27,7 +27,7 @@ import {
2727 declineReminder,
2828 undoDecline,
2929 } from "./deals.ts";
30 import { agent, title } from "./env.ts";
30 import { agent, LENGTH_MAX, standard, title } from "./env.ts";
3131 import { dueOn } from "./reminders.ts";
3232 import { FIND_REFUSAL, find, query } from "./find.ts";
3333 import { fields } from "./http.ts";
@@ -194,12 +194,12 @@ export const tools: readonly Tool[] = [
194194 seller: { type: "string", maxLength: 100 },
195195 contract_date: { type: "string", format: "date" },
196196 closing_date: { type: "string", format: "date" },
197 inspection: { type: "integer", minimum: 0 },
198 appraisal: { type: "integer", minimum: 0 },
199 financing: { type: "integer", minimum: 0 },
200 title: { type: "integer", minimum: 0 },
201 walkthrough: { type: "integer", minimum: 0 },
202 business_days: { type: "boolean" },
197 inspection: { type: "integer", minimum: 0, maximum: LENGTH_MAX, default: DEFAULT_LENGTHS.inspection },
198 appraisal: { type: "integer", minimum: 0, maximum: LENGTH_MAX, default: DEFAULT_LENGTHS.appraisal },
199 financing: { type: "integer", minimum: 0, maximum: LENGTH_MAX, default: DEFAULT_LENGTHS.financing },
200 title: { type: "integer", minimum: 0, maximum: LENGTH_MAX, default: DEFAULT_LENGTHS.title },
201 walkthrough: { type: "integer", minimum: 0, maximum: LENGTH_MAX, default: DEFAULT_LENGTHS.walkthrough },
202 business_days: { type: "boolean", default: standard.businessDays },
203203 },
204204 required: ["address", "buyer", "seller", "contract_date", "closing_date"],
205205 },
src/pages/deal.ts +3 −1
@@ -6,6 +6,7 @@
66
77 import { addDays, relative, short, spoken } from "../dates.ts";
88 import { canChange, canRemove, closedOn, type DealView, type Party, type Plan, type PlannedDate, type Sent } from "../deals.ts";
9 import { standard } from "../env.ts";
910 import { DEFAULT_LENGTHS, PARTY_LABEL, PARTY_ROLES } from "../deadlines.ts";
1011 import { escape } from "../http.ts";
1112 import { MOMENT_LABEL } from "../reminders.ts";
@@ -191,7 +192,7 @@ export function newDealPage(input: {
191192 : "";
192193 const length = (name: keyof typeof DEFAULT_LENGTHS, label: string) =>
193194 `<label>${label}<input class="input" type="number" inputmode="numeric" name="${name}" min="0" max="180" value="${val(name, String(DEFAULT_LENGTHS[name]))}" required${bad(name)}>${why(name)}</label>`;
194 const ticked = values.business_days !== undefined;
195 const ticked = state === undefined ? standard.businessDays : values.business_days !== undefined;
195196 const body =
196197 who.role === "anon"
197198 ? `<p class="crumb"><a href="/">← The clock</a></p><section class="card"><h1>New deal</h1><p><a href="/__forge/signin?to=/deals/new">Sign in</a> to open a deal.</p></section>`
@@ -199,6 +200,7 @@ export function newDealPage(input: {
199200 <section class="card narrow">
200201 <h1>New deal</h1>
201202 <p class="muted">The contract and closing dates, and the contingency lengths, set every date. You can move any of them after.</p>
203 <p class="muted small">The lengths start from your standard ones; change any for this deal.</p>
202204 <form class="stack" method="post" action="/deals">
203205 ${general}
204206 <label>Property address<input class="input" name="address" required minlength="3" maxlength="200" autocomplete="off" placeholder="1418 Alder Lane" value="${val("address", "")}"${bad("address")}>${why("address")}</label>
src/routes.ts +16 −9
@@ -20,7 +20,8 @@ import {
2020 type Failure,
2121 type Result,
2222 } from "./actions.ts";
23 import { agent, commit, description, env, forgeUrl, publicOrigin, startedAt, title, version } from "./env.ts";
23 import { DEFAULT_LENGTHS } from "./deadlines.ts";
24 import { agent, commit, description, env, standard, forgeUrl, publicOrigin, startedAt, title, version } from "./env.ts";
2425 import {
2526 asset,
2627 back,
@@ -231,12 +232,12 @@ const NEW_DEAL: Schema = {
231232 seller: { type: "string", minLength: 1, maxLength: 100 },
232233 contract_date: DATE,
233234 closing_date: DATE,
234 inspection: { type: "integer", minimum: 0, maximum: 180, default: 10 },
235 appraisal: { type: "integer", minimum: 0, maximum: 180, default: 21 },
236 financing: { type: "integer", minimum: 0, maximum: 180, default: 30 },
237 title: { type: "integer", minimum: 0, maximum: 180, default: 14 },
238 walkthrough: { type: "integer", minimum: 0, maximum: 180, default: 1 },
239 business_days: { type: "boolean", default: false },
235 inspection: { type: "integer", minimum: 0, maximum: 180, default: DEFAULT_LENGTHS.inspection },
236 appraisal: { type: "integer", minimum: 0, maximum: 180, default: DEFAULT_LENGTHS.appraisal },
237 financing: { type: "integer", minimum: 0, maximum: 180, default: DEFAULT_LENGTHS.financing },
238 title: { type: "integer", minimum: 0, maximum: 180, default: DEFAULT_LENGTHS.title },
239 walkthrough: { type: "integer", minimum: 0, maximum: 180, default: DEFAULT_LENGTHS.walkthrough },
240 business_days: { type: "boolean", default: standard.businessDays },
240241 },
241242 required: ["address", "buyer", "seller", "contract_date", "closing_date"],
242243 };
@@ -317,6 +318,12 @@ async function form(c: Context): Promise<Record<string, string> | Response> {
317318 return out;
318319 }
319320
321 /** An unticked box is absent from a form: that says no, not "the agent's default". */
322 const fromForm = (f: Record<string, unknown>): Record<string, unknown> => ({

This override is untested; add a test that fails without it (see body).

323 ...f,
324 business_days: f.business_days ?? "0",
325 });
326
320327 /** A new deal from a form or a JSON body: the same names either way. */
321328 const newDeal = (f: Record<string, unknown>): NewDeal => ({
322329 address: f.address,
@@ -456,7 +463,7 @@ export const routes: readonly Route[] = [
456463 handle: async (c) => {
457464 const f = await form(c);
458465 if (f instanceof Response) return f;
459 const made = createDeal(c.db, c.who, newDeal(f));
466 const made = createDeal(c.db, c.who, newDeal(fromForm(f)));
460467 if (made.ok) return back("Deal opened. Every date is on the clock.", `/deals/${made.value.id}`);
461468 if (made.error !== "invalid") return back(made.message, "/deals/new");
462469 return html(newDealPage({ who: c.who, on: today(), state: { values: f, problem: made } }), 422);
@@ -471,7 +478,7 @@ export const routes: readonly Route[] = [
471478 if (f instanceof Response) return f;
472479 const may = mayOpen(c.who);
473480 if (!may.ok) return back(may.message, "/deals/new");
474 const planned = plan(newDeal(f));
481 const planned = plan(newDeal(fromForm(f)));
475482 if (!planned.ok)
476483 return html(newDealPage({ who: c.who, on: today(), state: { values: f, problem: planned } }), 422);
477484 const preview = { plan: planned.value, dates: plannedDates(planned.value) };
src/sample.ts +4 −3
@@ -7,7 +7,8 @@
77
88 import type { Database } from "bun:sqlite";
99 import { addDays, daysBetween, today } from "./dates.ts";
10 import { DEFAULT_LENGTHS, type PartyRole } from "./deadlines.ts";
10 import { type PartyRole } from "./deadlines.ts";
11 import { BRIEF_LENGTHS } from "./env.ts";
1112 import { insertDeal } from "./deals.ts";
1213
1314 export const SAMPLE = { id: "sample", name: "Sample data" };
@@ -19,7 +20,7 @@ interface Sample {
1920 /** Days from today. */
2021 readonly contract: number;
2122 readonly closing: number;
22 readonly lengths?: Partial<typeof DEFAULT_LENGTHS>;
23 readonly lengths?: Partial<typeof BRIEF_LENGTHS>;
2324 readonly parties: readonly [PartyRole, string, string][];
2425 readonly done?: readonly string[];
2526 readonly custom?: readonly [string, number, PartyRole, string][];
@@ -213,7 +214,7 @@ function writeSamples(db: Database, on: string): void {
213214 seller: s.seller,
214215 contractDate: addDays(on, s.contract),
215216 closingDate: addDays(on, s.closing),
216 lengths: { ...DEFAULT_LENGTHS, ...s.lengths },
217 lengths: { ...BRIEF_LENGTHS, ...s.lengths },
217218 businessDays: false,
218219 });
219220 db.query("INSERT INTO sample_deal (deal_id, sample) VALUES (?1, ?2)").run(deal.id, s.address);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs