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

The agent changes who owes a date after it is added, and its reminders from then on go to the new party #104

Merged opened this

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

Merged

mason/deal-clock:mason/102-the-agent-changes-who-owes-a-date-after → main 1 commit fork

  • Merged. mason/102-the-agent-changes-who-owes-a-date-after was merged into main as 539cfeb.

Review

Sign in to review this change.
9 files changed +241 −13
README.md +3
@@ -101,6 +101,9 @@ Signed out, `/` shows what deal-clock does, three short points, a still picture
101101 after closing. For an addendum that moves several dates, use *Amend the
102102 contract* on the deal page instead: one reason, and each party gets one
103103 notice listing every change.
104 If a date was entered against the wrong party, or the contract hands it
105 over (a repair, say), open its sheet and change *Owed by*: its reminders
106 from then on go to the new party, and the sent ones stay as they were.
104107 6. **See a date that was moved.** On 9 Orchard Row, open the appraisal
105108 marker. The sheet shows where it moved from and to, with the reason
106109 the appraiser gave.
contract/openapi.json +23 −7
@@ -1687,7 +1687,7 @@
16871687 },
16881688 "/api/deals/{id}/deadlines/{deadline}": {
16891689 "patch": {
1690 "summary": "Set how many days before it is due a date's first reminder goes out (a whole number, 1 to 30; 400 with field lead_days otherwise). An unsent draft is drafted again for the new day; a sent one keeps its words.",
1690 "summary": "Change a date: lead_days sets how many days before it is due its first reminder goes out (a whole number, 1 to 30; 400 with field lead_days otherwise; an unsent draft is drafted again for the new day, a sent one keeps its words), and owes changes which party owes it (one of the party roles; 422 otherwise, 409 for a date already done or waived). Today's and later reminders are drafted to the new party; ones already sent stay as they were. Send either or both.",
16911691 "operationId": "patchApiDealsIdDeadlinesDeadline",
16921692 "parameters": [
16931693 {
@@ -1718,18 +1718,24 @@
17181718 "type": "integer",
17191719 "minimum": 1,
17201720 "maximum": 30
1721 },
1722 "owes": {
1723 "enum": [
1724 "buyer",
1725 "seller",
1726 "lender",
1727 "title",
1728 "other_agent"
1729 ]
17211730 }
1722 },
1723 "required": [
1724 "lead_days"
1725 ]
1731 }
17261732 }
17271733 }
17281734 }
17291735 },
17301736 "responses": {
17311737 "200": {
1732 "description": "Set how many days before it is due a date's first reminder goes out (a whole number, 1 to 30; 400 with field lead_days otherwise). An unsent draft is drafted again for the new day; a sent one keeps its words.",
1738 "description": "Change a date: lead_days sets how many days before it is due its first reminder goes out (a whole number, 1 to 30; 400 with field lead_days otherwise; an unsent draft is drafted again for the new day, a sent one keeps its words), and owes changes which party owes it (one of the party roles; 422 otherwise, 409 for a date already done or waived). Today's and later reminders are drafted to the new party; ones already sent stay as they were. Send either or both.",
17331739 "content": {
17341740 "application/json": {
17351741 "schema": {
@@ -1740,11 +1746,21 @@
17401746 },
17411747 "lead_days": {
17421748 "type": "integer"
1749 },
1750 "owes": {
1751 "enum": [
1752 "buyer",
1753 "seller",
1754 "lender",
1755 "title",
1756 "other_agent"
1757 ]
17431758 }
17441759 },
17451760 "required": [
17461761 "id",
1747 "lead_days"
1762 "lead_days",
1763 "owes"
17481764 ]
17491765 }
17501766 }
src/activity.ts +9
@@ -6,6 +6,7 @@
66
77 import type { Database } from "bun:sqlite";
88 import { HOLD_WHAT, type AuditRow } from "./audit.ts";
9 import { isPartyRole, PARTY_LABEL } from "./deadlines.ts";
910 import { isDate, spoken } from "./dates.ts";
1011
1112 /** Rows to a page; a door asks for one more to know whether there is an older page. */
@@ -20,6 +21,7 @@ const WORDS: Readonly<Record<string, string>> = {
2021 "date.move": "moved a date",
2122 "date.done": "marked a date done",
2223 "date.waive": "waived a date",
24 "date.owes": "changed who owes a date",
2325 "date.lead": "changed when a date's reminder goes out",
2426 "date.add": "added a date",
2527 "date.remove": "removed a date",
@@ -58,8 +60,15 @@ const heldWords = (what: string | null): string | undefined => {
5860 return isDate(until) ? `held a reminder until ${spoken(until)}` : undefined;
5961 };
6062
63 /** "changed Owed by from Buyer to Seller": a hand-over's audit name carries both roles. */
64 const owesWords = (what: string | null): string | undefined => {
65 const [, from, to] = what?.match(/^date\.owes:([a-z_]+)>([a-z_]+)$/) ?? [];
66 return isPartyRole(from) && isPartyRole(to) ? `changed Owed by from ${PARTY_LABEL[from]} to ${PARTY_LABEL[to]}` : undefined;
67 };
68
6169 export const wording = (row: Pick<AuditRow, "resource" | "verb" | "what">): string =>
6270 heldWords(row.what) ||
71 owesWords(row.what) ||
6372 (row.what !== null && WORDS[row.what]) || WORDS[`${row.resource} ${row.verb}`] || `${row.resource} ${row.verb}`;
6473
6574 /** "Fri, Oct 16, 3:04 PM UTC" from the stored ISO time; the text itself if it does not read. */
src/deals.ts +36
@@ -19,6 +19,7 @@ import {
1919 LEAD_MAX,
2020 LEAD_MIN,
2121 leadOf,
22 PARTY_LABEL,
2223 schedule,
2324 type Kind,
2425 type Lengths,
@@ -704,6 +705,41 @@ export function waiveDate(
704705 return within(db, who, "date.waive", dealId, ok(reread(db, input.id)));
705706 }
706707
708 /** What the audit trail calls a change of who owes a date: `date.owes:<from>><to>`. */
709 export const OWES_WHAT = "date.owes";
710
711 /**
712 * Change who owes an open date. Today's and later reminders are drafted to
713 * the new party; reminders already sent or declined stay as they were, and
714 * a hold on a party the date no longer tells goes with the change. A done or
715 * waived date is settled and cannot be handed to anyone.
716 */
717 export function setOwes(
718 db: Database,
719 who: Who,
720 input: { id: number; dealId?: number; owes: unknown },
721 ): Result<Deadline> {
722 const { dealId, found } = deadlineFor(db, who, input.id, input.dealId);
723 if (!found.ok) return within(db, who, OWES_WHAT, dealId, found);
724 const { deadline } = found.value;
725 if (!isPartyRole(input.owes))
726 return within(db, who, OWES_WHAT, dealId, fail("invalid", "Say which party owes it.", "owes"));
727 if (!isOpen(deadline))
728 return within(db, who, OWES_WHAT, dealId, fail("conflict", `This date is ${deadline.waived_at !== null ? "waived" : "done"}; reopen it before changing who owes it.`));
729 if (input.owes === deadline.owes)
730 return within(db, who, OWES_WHAT, dealId, fail("invalid", `${PARTY_LABEL[input.owes]} already owes it.`, "owes"));
731 const told = [input.owes, ...KIND[deadline.kind].notify];
732 db.transaction(() => {
733 db.query("UPDATE deadline SET owes = ?1 WHERE id = ?2").run(input.owes as string, deadline.id);
734 for (const h of db.query<{ id: number; moment: string; role: string }, [number]>(
735 "SELECT h.id, h.moment, p.role FROM reminder_hold h JOIN party p ON p.id = h.party_id WHERE h.deadline_id = ?1",
736 ).all(deadline.id))
737 if (!told.includes(h.role as PartyRole) || (h.moment === "late" && h.role !== input.owes))
738 db.query("DELETE FROM reminder_hold WHERE id = ?1").run(h.id);
739 })();
740 return within(db, who, `${OWES_WHAT}:${deadline.owes}>${input.owes}`, dealId, ok(reread(db, deadline.id)));
741 }
742
707743 /** Whether `value` is a lead time: a whole number of days, 1 to 30. */
708744 const isLead = (value: unknown): value is number =>
709745 typeof value === "number" && Number.isInteger(value) && value >= LEAD_MIN && value <= LEAD_MAX;
src/mcp.ts +12
@@ -31,6 +31,7 @@ import {
3131 sendStatusUpdate,
3232 statusUpdates,
3333 setReminderLead,
34 setOwes,
3435 declineReminder,
3536 holdReminder,
3637 undoDecline,
@@ -132,6 +133,17 @@ export const tools: readonly Tool[] = [
132133 },
133134 run: (db, who, args) => markDone(db, who, { id: Number(args.id), done: args.done !== false }),
134135 },
136 {
137 name: "set_owes",
138 description:
139 "Change which party owes an open date (not one already done or waived). Today's and later reminders are drafted to the new party; ones already sent stay as they were.",
140 inputSchema: {
141 type: "object",
142 properties: { id: { type: "integer" }, owes: { enum: [...PARTY_ROLES] } },
143 required: ["id", "owes"],
144 },
145 run: (db, who, args) => setOwes(db, who, { id: Number(args.id), owes: args.owes }),
146 },
135147 {
136148 name: "waive_date",
137149 description: "Waive a date the buyer gave up on purpose (not Closing): it stays on the deal, settled, with no more reminders. Un-waive it with waived: false.",
src/owes.test.ts added +119
@@ -0,0 +1,119 @@
1 /** The agent changes who owes a date: its reminders follow, the record keeps the past, and every door agrees. */
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 { openDb } from "./db.ts";
8 import { createDeal, getDeal, markDone, setOwes, waiveDate, type DealView } from "./deals.ts";
9 import { agent } from "./env.ts";
10 import { people } from "./people.ts";
11 import { drafts } from "./reminders.ts";
12 import { wording } from "./activity.ts";
13 import { forgetRationing } from "./security.ts";
14 import { serve } from "./server.ts";
15 import { sign } from "./who.ts";
16 import type { Who } from "./who.ts";
17
18 const db = openDb(mkdtempSync(join(tmpdir(), "app-owes-")));
19 const alice: Who = { role: "user", id: "u1", name: "alice" };
20 const anon: Who = { role: "anon" };
21 const made = createDeal(db, alice, {
22 openAnyway: true,
23 address: "5 Hand Over Hill",
24 buyer: "Ann Buyer",
25 seller: "Sam Seller",
26 contractDate: addDays(today(), -10),
27 closingDate: addDays(today(), 30),
28 });
29 if (!made.ok) throw new Error(made.message);
30 const deal = (): DealView => {
31 const got = getDeal(db, alice, { id: made.value.id });
32 if (!got.ok) throw new Error(got.message);
33 return got.value;
34 };
35 const date = (kind: string) => deal().deadlines.find((d) => d.kind === kind)!;
36 db.query("UPDATE party SET contact = '[email protected]' WHERE deal_id = ?1 AND role = 'buyer'").run(made.value.id);
37 db.query("UPDATE party SET contact = '[email protected]' WHERE deal_id = ?1 AND role = 'seller'").run(made.value.id);
38 db.query("UPDATE deadline SET due = ?1 WHERE id = ?2").run(today(), date("earnest").id);
39 const roleOf = (kind: string, moment: string) => drafts(deal(), agent).filter((r) => r.deadline_id === date(kind).id && r.moment === moment).map((r) => r.party_role);
40
41 test("a change moves today's draft to the new party and the People page follows", () => {
42 expect(roleOf("earnest", "day_of")).not.toContain("seller");
43 const handed = setOwes(db, alice, { id: date("earnest").id, owes: "seller" });
44 expect(handed).toMatchObject({ ok: true, value: { owes: "seller" } });
45 expect(roleOf("earnest", "day_of")).toContain("seller");
46 const list = people([deal()], today());
47 const sam = list.find((p) => p.name === "Sam Seller")!;
48 const ann = list.find((p) => p.name === "Ann Buyer")!;
49 expect(sam.owes.map((o) => o.deadline_id)).toContain(date("earnest").id);
50 expect(ann.owes.map((o) => o.deadline_id)).not.toContain(date("earnest").id);
51 const row = db.query<{ what: string }, []>("SELECT what FROM audit WHERE what LIKE 'date.owes:%' ORDER BY id DESC LIMIT 1").get()!;
52 expect(wording({ resource: "deal", verb: "update", what: row.what })).toBe("changed Owed by from Buyer to Seller");
53 });
54
55 test("a bad role is invalid, the same party is refused, and a settled date is a conflict", () => {
56 expect(setOwes(db, alice, { id: date("appraisal").id, owes: "nobody" })).toMatchObject({ ok: false, error: "invalid", field: "owes" });
57 expect(setOwes(db, alice, { id: date("earnest").id, owes: "seller" })).toMatchObject({ ok: false, error: "invalid" });
58 markDone(db, alice, { id: date("title").id, done: true });
59 expect(setOwes(db, alice, { id: date("title").id, owes: "buyer" })).toMatchObject({ ok: false, error: "conflict" });
60 waiveDate(db, alice, { id: date("financing").id, waived: true });
61 expect(setOwes(db, alice, { id: date("financing").id, owes: "seller" })).toMatchObject({ ok: false, error: "conflict" });
62 });
63
64 test("an anonymous visitor is refused and nothing changes", () => {
65 const before = date("appraisal").owes;
66 expect(setOwes(db, anon, { id: date("appraisal").id, owes: "seller" })).toMatchObject({ ok: false, error: "signin_required" });
67 expect(date("appraisal").owes).toBe(before);
68 });
69
70 test("a hold on the old party's reminder is dropped with the change", () => {
71 const id = date("walkthrough").id;
72 const buyer = deal().parties.find((p) => p.role === "buyer")!;
73 db.query("INSERT INTO reminder_hold (deal_id, deadline_id, party_id, moment, due, move_id, until, held_on, by_name) VALUES (?1, ?2, ?3, 'late', ?4, 0, ?5, ?4, 'alice')").run(made.value.id, id, buyer.id, date("walkthrough").due, addDays(today(), 1));
74 setOwes(db, alice, { id, owes: "seller" });
75 expect(db.query("SELECT count(*) AS n FROM reminder_hold WHERE deadline_id = ?1").get(id)).toEqual({ n: 0 });
76 });
77
78 const KEY = "a-key-only-the-forge-holds";
79 const server = serve({ port: 0, dataDir: mkdtempSync(join(tmpdir(), "app-owes-http-")), identityKey: KEY });
80 const base = `http://${server.hostname}:${server.port}`;
81 afterAll(() => server.stop(true));
82 beforeEach(forgetRationing);
83 const identity = `u9|nora|user|${Date.now() + 600_000}`;
84 const me = { "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) };
85
86 test("the form, the API and the sheet agree, and another origin is refused", async () => {
87 const created = await fetch(base + "/api/deals", {
88 method: "POST",
89 headers: { ...me, "content-type": "application/json" },
90 body: JSON.stringify({ address: "9 Door Dr", open_anyway: true, buyer: "A", seller: "B", contract_date: "2026-10-01", closing_date: "2026-12-01" }),
91 });
92 const d = (await created.json()) as DealView;
93 const inspection = d.deadlines.find((x) => x.kind === "earnest")!;
94 const formHeaders = { ...me, "content-type": "application/x-www-form-urlencoded" };
95 const post = (owes: string, headers: Record<string, string> = formHeaders) =>
96 fetch(`${base}/deadlines/${inspection.id}/owes`, { method: "POST", body: new URLSearchParams({ owes, to: `/deals/${d.id}` }), headers, redirect: "manual" });
97 expect((await post("nobody")).status).toBe(422);
98 expect((await post("seller", { ...formHeaders, origin: "https://elsewhere.example" })).status).toBeGreaterThanOrEqual(400);
99 expect((await post("seller")).status).toBe(303);
100 const page = await (await fetch(`${base}/deals/${d.id}`, { headers: me })).text();
101 expect(page).toContain(`action="/deadlines/${inspection.id}/owes"`);
102 expect(page).toMatch(/<option value="seller" selected>/);
103 const patch = await fetch(`${base}/api/deals/${d.id}/deadlines/${inspection.id}`, { method: "PATCH", headers: { ...me, "content-type": "application/json" }, body: JSON.stringify({ owes: "lender" }) });
104 expect(patch.status).toBe(200);
105 expect(await patch.json()).toMatchObject({ owes: "lender" });
106 const bad = await fetch(`${base}/api/deals/${d.id}/deadlines/${inspection.id}`, { method: "PATCH", headers: { ...me, "content-type": "application/json" }, body: JSON.stringify({ owes: "ghost" }) });
107 expect(bad.status).toBe(422);
108 const rpc = await fetch(base + "/mcp", {
109 method: "POST",
110 headers: { ...me, "content-type": "application/json" },
111 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "set_owes", arguments: { id: inspection.id, owes: "buyer" } } }),
112 });
113 expect(JSON.stringify(await rpc.json())).toContain("buyer");
114 const anonymous = await fetch(`${base}/deadlines/${inspection.id}/owes`, { method: "POST", body: new URLSearchParams({ owes: "seller" }), headers: { "content-type": "application/x-www-form-urlencoded", origin: base }, redirect: "manual" });
115 expect(anonymous.status).toBeGreaterThanOrEqual(401);
116 const root = `u1|root|admin|${Date.now() + 600_000}`;
117 const activity = await (await fetch(`${base}/activity`, { headers: { "x-forge-identity": root, "x-forge-signature": sign(root, KEY) } })).text();
118 expect(activity).toContain("changed Owed by from Buyer to Seller");
119 });
src/pages/sheet.ts +9 −1
@@ -7,7 +7,7 @@
77
88 import { BODY_MAX, canChange, ROLL_REASON, REASON_MAX, SUBJECT_MAX, type DealView, type DeadlineView } from "../deals.ts";
99 import { relative, short, spoken, urgencyOf, type Urgency } from "../dates.ts";
10 import { isOpen, isWaivable, LEAD_MAX, LEAD_MIN, PARTY_LABEL } from "../deadlines.ts";
10 import { isOpen, isWaivable, LEAD_MAX, LEAD_MIN, PARTY_LABEL, PARTY_ROLES } from "../deadlines.ts";
1111 import { escape } from "../http.ts";
1212 import { confirmRemove } from "./confirm.ts";
1313 import { memoizer, print } from "../memo.ts";
@@ -222,6 +222,14 @@ export function sheet(deal: DealView, d: DeadlineView, who: Who, on: string, to:
222222 <button class="button button-quiet">Move this date</button>
223223 </form>
224224 <p class="muted small">Moving a date moves nothing else; the reason is kept.</p>
225 ${
226 isOpen(d)
227 ? `<form class="move" method="post" action="/deadlines/${d.id}/owes">${hidden({ to })}
228 <label>Owed by<select class="input" name="owes">${PARTY_ROLES.map((r) => `<option value="${r}"${r === d.owes ? " selected" : ""}>${escape(PARTY_LABEL[r])}</option>`).join("")}</select></label>
229 <button class="button button-quiet">Change who owes it</button>
230 </form>`
231 : ""
232 }
225233 <form class="move" method="post" action="/deadlines/${d.id}/lead">${hidden({ to })}
226234 <label>Remind me this many days before<input class="input" type="number" name="lead_days" min="${LEAD_MIN}" max="${LEAD_MAX}" step="1" value="${d.lead_days}" required></label>
227235 <button class="button button-quiet">Set reminder</button>
src/routes.ts +29 −5
@@ -20,7 +20,7 @@ import {
2020 type Failure,
2121 type Result,
2222 } from "./actions.ts";
23 import { DEFAULT_LENGTHS } from "./deadlines.ts";
23 import { DEFAULT_LENGTHS, PARTY_LABEL } from "./deadlines.ts";
2424 import { commit, description, env, standard, forgeUrl, publicOrigin, startedAt, title, version } from "./env.ts";
2525 import {
2626 asset,
@@ -66,6 +66,7 @@ import {
6666 sendStatusUpdate,
6767 statusUpdates,
6868 setReminderLead,
69 setOwes,
6970 declineReminder,
7071 holdReminder,
7172 undoDecline,
@@ -919,6 +920,23 @@ export const routes: readonly Route[] = [
919920 return done(moved, backTo(f.to), moved.ok ? withConflicts(c.db, c.who, moved.value.deal_id, "Date moved; nothing else did.") : undefined);
920921 },
921922 },
923 {
924 method: "POST",
925 path: "/deadlines/:id/owes",
926 handle: async (c) => {
927 const f = await form(c);
928 if (f instanceof Response) return f;
929 const id = Number(c.params.id);
930 const set = setOwes(c.db, c.who, { id, owes: f.owes });
931 if (set.ok) return done(set, backTo(f.to), `${PARTY_LABEL[set.value.owes]} now owes ${set.value.label}.`);
932 const deal = c.db.query<{ deal_id: number }, [number]>("SELECT deal_id FROM deadline WHERE id = ?1").get(id)?.deal_id;
933 const found = deal === undefined ? undefined : getDeal(c.db, c.who, { id: deal });
934 // A refusal on a real date comes back as that deal's page, saying why; anything else as before.
935 if (found?.ok && (set.error === "invalid" || set.error === "conflict"))
936 return html(dealPage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), deal: found.value, on: today(), notice: set.message }), STATUS[set.error]);
937 return done(set, backTo(f.to));
938 },
939 },
922940 {
923941 method: "POST",
924942 path: "/deadlines/:id/lead",
@@ -1311,7 +1329,13 @@ export const routes: readonly Route[] = [
13111329 handle: async (c) => {
13121330 const body = await readJson(c.request);
13131331 if (body === undefined) return json({ error: "too_large" }, 413);
1314 const lead = fields(body).lead_days;
1332 const sent = fields(body);
1333 const lead = sent.lead_days;
1334 const target = { id: Number(c.params.deadline), dealId: Number(c.params.id) };
1335 if ("owes" in sent) {
1336 const handed = setOwes(c.db, c.who, { ...target, owes: sent.owes });
1337 if (!handed.ok || !("lead_days" in sent)) return answer(handed);
1338 }
13151339 const set = setReminderLead(c.db, c.who, { id: Number(c.params.deadline), dealId: Number(c.params.id), leadDays: typeof lead === "number" ? lead : Number.NaN });
13161340 // A lead outside 1–30 is a bad field: 400, naming it.
13171341 if (!set.ok && set.field !== undefined) return json({ error: set.error, message: set.message, field: set.field }, 400);
@@ -1319,9 +1343,9 @@ export const routes: readonly Route[] = [
13191343 },
13201344 api: {
13211345 summary:
1322 "Set how many days before it is due a date's first reminder goes out (a whole number, 1 to 30; 400 with field lead_days otherwise). An unsent draft is drafted again for the new day; a sent one keeps its words.",
1323 body: { type: "object", properties: { lead_days: { type: "integer", minimum: 1, maximum: 30 } }, required: ["lead_days"] },
1324 answer: { type: "object", properties: { id: { type: "integer" }, lead_days: { type: "integer" } }, required: ["id", "lead_days"] },
1346 "Change a date: lead_days sets how many days before it is due its first reminder goes out (a whole number, 1 to 30; 400 with field lead_days otherwise; an unsent draft is drafted again for the new day, a sent one keeps its words), and owes changes which party owes it (one of the party roles; 422 otherwise, 409 for a date already done or waived). Today's and later reminders are drafted to the new party; ones already sent stay as they were. Send either or both.",
1347 body: { type: "object", properties: { lead_days: { type: "integer", minimum: 1, maximum: 30 }, owes: ROLE } },
1348 answer: { type: "object", properties: { id: { type: "integer" }, lead_days: { type: "integer" }, owes: ROLE }, required: ["id", "lead_days", "owes"] },
13251349 },
13261350 },
13271351 {
src/server.test.ts +1
@@ -178,6 +178,7 @@ test("the MCP server lists the tools and calls them as the caller", async () =>
178178 "this_week",
179179 "list_people",
180180 "mark_done",
181 "set_owes",
181182 "waive_date",
182183 "move_date",
183184 "set_reminder_lead",

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs