dwelldelta-mcp 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,6 +9,9 @@
9
9
  * non-strata (separate houses) and strata (units, town houses, villas), each labelled;
10
10
  * - DCJ's own table has rows that a few unusual sales set (postcode 2034, strata, March 2026: $8.954m, up 478%, from
11
11
  * 184 sales). The feed marks them `unusual_prices`; the answer says UNUSUAL in words, on that line, with the reason;
12
+ * a total the feed notes as mostly such a row's sales (`unusual_part`: Randwick council, 466 of 613) says so on its
13
+ * own line, and is said only to be possibly moved by them - never to have been set by them, nor not; a mark or a
14
+ * note this version does not know is shown as the file gives it, with nothing claimed about it;
12
15
  * - a gap is said with its reason and is never shown as zero.
13
16
  *
14
17
  * The feed keeps DCJ's unit (thousands of dollars) and so does the structured result, which says so; the text writes
@@ -22,7 +25,8 @@
22
25
  import { existsSync } from "node:fs";
23
26
  import { fileURLToPath } from "node:url";
24
27
  import { dirname, join } from "node:path";
25
- import { loadJson, envelope, ToolError, FOOTER, FETCH_TIMEOUT_MS } from "./tools.mjs";
28
+ import { loadJson, envelope, ToolError, FOOTER, FETCH_TIMEOUT_MS, feedSource, CADENCE, SAMPLE_RULES, judgeFigure,
29
+ figureFields, nWords, citeLine, staleNote, flagged, refusalMark } from "./tools.mjs";
26
30
  import { quarterKey } from "./vic-rents-tool.mjs";
27
31
  import { signed, match, nswPostcodes, MAX_ROWS, BUNDLED_DIR, PUBLISHED_BASE } from "./area-rents-tool.mjs";
28
32
 
@@ -31,6 +35,25 @@ const LIVE_DIR = join(HERE, "..", "..", "dwelldelta-data", "market");
31
35
  export const SALES_FILE = "nsw-sales.json";
32
36
  export const DWELLING_TYPES = ["total", "non_strata", "strata"];
33
37
  const LABEL = { total: "all dwellings", non_strata: "houses (non-strata)", strata: "units and town houses (strata)" };
38
+ /** The two reasons the builder writes in `unusual_prices`, word for word; anything else there - the same rule with
39
+ * another threshold included - is a mark this version does not know, and is not called UNUSUAL. */
40
+ const REASONS = ["the median equals a quartile: many sales at one identical price", "the third quartile is more than 3 times the median"];
41
+ /** `unusual_part` as the builder writes it: "its strata row is marked unusual_prices (...), and that row is 466 of this total's 613 sales". */
42
+ const KNOWN_PART = new RegExp(`^its (?:non-strata|strata) row is marked unusual_prices \\((?:${REASONS.join("|")})\\), and that row is (\\d+) of this total's (\\d+) sales$`);
43
+ const has = (v) => v != null && v !== false && v !== "";
44
+ const knownMark = (v) => REASONS.includes(v);
45
+ /** The builder's note, and its own numbers bear it out: the second is this row's sales and the first is more than half of it. */
46
+ function knownPart(r) {
47
+ const m = typeof r.unusual_part === "string" ? KNOWN_PART.exec(r.unusual_part) : null;
48
+ return m !== null && Number(m[2]) === r.sales && 2 * Number(m[1]) > Number(m[2]);
49
+ }
50
+ /** What a row carries, as this version can read it: a mark and a note, each "known", "unknown" or null. The note is
51
+ * known only as the builder writes it: on a total, with no mark of the total's own. */
52
+ function reads(r, type) {
53
+ const mark = !has(r.unusual_prices) ? null : knownMark(r.unusual_prices) ? "known" : "unknown";
54
+ const part = !has(r.unusual_part) ? null : type === "total" && mark === null && knownPart(r) ? "known" : "unknown";
55
+ return { mark, part };
56
+ }
34
57
  const HINT = "NSW sale prices are by four-digit postcode (area: \"2148\") or by council (council: \"Blacktown\").";
35
58
 
36
59
  const wellFormed = (f) => f && f.state === "NSW" && f.measure === "sale_price" && quarterKey(f.quarter) > 0
@@ -62,18 +85,40 @@ export async function loadNswSales({ env = process.env, fetchImpl = globalThis.f
62
85
  /** 1033 (thousands, as DCJ reports) -> "$1,033,000". */
63
86
  const price = (k) => `$${(k * 1000).toLocaleString("en-AU")}`;
64
87
 
88
+ /** DCJ's small-sample rule for its sales tables (tools.mjs SAMPLE_RULES): below it a figure is refused, never given. */
89
+ export const RULE = SAMPLE_RULES.NSW_SALES;
90
+
91
+ /** One figure's sample and, if it rests on too few sales or is not in DCJ's table, its refusal. */
92
+ export function saleFigure(r, label) {
93
+ const why = r == null ? "no row in DCJ's table" : r.median_price_k_aud == null ? (r.withheld ?? "not reported") : null;
94
+ return judgeFigure(r, { name: label, median: "median_price_k_aud", count: "sales", band: "sales_band", rule: RULE, why,
95
+ missing: r && r.withheld ? "too_few_records" : "not_published" });
96
+ }
97
+
65
98
  function line(r, name, type) {
66
99
  const label = `${name}, ${LABEL[type]}`;
67
100
  if (r == null) return `${label}: no row in DCJ's table.`;
68
101
  if (r.median_price_k_aud == null) return `${label}: no median (${r.withheld ?? "not reported"}).`;
102
+ // A median below DCJ's own rule is refused, not printed: never a weak number.
103
+ const refusal = saleFigure(r, label).refusal;
104
+ if (refusal) return `${label}: no median (${refusal.reason}).`;
69
105
  const sales = r.sales_band ? ` from ${r.sales_band} sales (DCJ withholds the count)`
70
106
  : r.sales == null ? "" : ` from ${r.sales.toLocaleString("en-AU")} sales`;
71
107
  const change = r.change_pct == null ? "" : `, ${signed(r.change_pct)} on a year before`;
72
108
  const spread = r.first_quartile_k_aud == null || r.third_quartile_k_aud == null ? ""
73
109
  : `; half of sales between ${price(r.first_quartile_k_aud)} and ${price(r.third_quartile_k_aud)}`;
110
+ // UNUSUAL is the word the tool's description says means "set by a few very large sales", so only the two
111
+ // reasons that mean that are printed under it.
112
+ const carries = reads(r, type);
113
+ const mark = carries.mark === null ? ""
114
+ : (carries.mark === "known" ? ` UNUSUAL - ${r.unusual_prices}`
115
+ : ` MARKED (unusual_prices) - ${typeof r.unusual_prices === "string" ? r.unusual_prices : "a mark this version of the tool cannot put in words"}`) +
116
+ ": do not quote this as the going price of a home there.";
117
+ const part = carries.part === null ? ""
118
+ : carries.part === "known" ? ` MOSTLY A MARKED ROW - ${r.unusual_part}: its median and its change may be moved by that row's sales.`
119
+ : ` NOTE (unusual_part) - ${typeof r.unusual_part === "string" ? r.unusual_part : "a note this version of the tool cannot put in words"}.`;
74
120
  return `${label}: median ${price(r.median_price_k_aud)}${sales}${change}${spread}` +
75
- `${r.small_sample ? " (small sample: treat with caution)" : ""}.` +
76
- `${r.unusual_prices ? ` UNUSUAL - ${r.unusual_prices}: do not quote this as the going price of a home there.` : ""}`;
121
+ `${r.small_sample ? " (small sample: treat with caution)" : ""}.${mark}${part}`;
77
122
  }
78
123
 
79
124
  /** nsw_sale_prices: a postcode, a council, or neither for the state; optionally one dwelling type. */
@@ -114,10 +159,19 @@ export function salePricesResult({ area, council, dwelling_type } = {}, feed, no
114
159
  councils = councils.slice(0, MAX_ROWS);
115
160
  const shown = [...(whole ? [["New South Wales (whole state)", feed.state_total]] : []),
116
161
  ...councils.map((g) => [`${g.council} (council)`, g]), ...areas.map((g) => [`${g.area} (postcode)`, g])];
117
- const marked = shown.some(([, g]) => types.some((t) => g[t]?.unusual_prices));
118
- const env = envelope({ sources: [{ source: feed.source, licence: feed.licence, attribution: feed.attribution }],
119
- dataAsOf: feed.quarter, origin: feed.origin ?? null }, now);
162
+ // Only rows that are shown and have a median are spoken of: line() says nothing of a mark on any other.
163
+ const seen = shown.flatMap(([, g]) => types.filter((t) => g[t] && g[t].median_price_k_aud != null).map((t) => reads(g[t], t)));
164
+ const marked = seen.some((s) => s.mark !== null), noted = seen.some((s) => s.part !== null);
165
+ const setByAFew = seen.some((s) => s.mark === "known"), mostlyARow = seen.some((s) => s.part === "known");
166
+ const unknown = seen.some((s) => s.mark === "unknown" || s.part === "unknown");
167
+ const feedUrl = PUBLISHED_BASE + SALES_FILE;
168
+ const env = envelope({ sources: [feedSource(feed, feedUrl, feed.quarter)], dataAsOf: feed.quarter,
169
+ origin: feed.origin ?? null, cadence: CADENCE.sales_quarterly }, now);
170
+ // Each place's figures by dwelling type, in the order the answer gives them.
171
+ const judged = new Map(shown.map(([name, g]) => [g, Object.fromEntries(types.map((t) => [t, saleFigure(g[t], `${name}, ${LABEL[t]}`)]))]));
172
+ const figures = shown.flatMap(([, g]) => types.map((t) => judged.get(g)[t]));
120
173
  const text = [
174
+ ...staleNote(env),
121
175
  `${feed.what}. Quarter: ${feed.quarter}, against ${feed.compared_with}. Medians of homes sold - not asking ` +
122
176
  "prices, not valuations, and not the price or value of any one home.",
123
177
  "",
@@ -125,21 +179,36 @@ export function salePricesResult({ area, council, dwelling_type } = {}, feed, no
125
179
  ...dropped,
126
180
  ...(whole ? ["", `${feed.areas.length.toLocaleString("en-AU")} postcode rows and ${feed.councils.length} councils ` +
127
181
  "are available: call again with area or council."] : []),
128
- ...(marked ? ["", "At least one row above is marked UNUSUAL: its figure is DCJ's own, and a few very large sales " +
182
+ ...(setByAFew ? ["", "At least one row above is marked UNUSUAL: its figure is DCJ's own, and a few very large sales " +
129
183
  "or many sales at one identical price have set it. Say so if you mention it."] : []),
184
+ ...(mostlyARow ? ["", "A total above is mostly the sales of a row marked UNUSUAL, by DCJ's own numbers of sales. The " +
185
+ "total's figure is DCJ's own and carries no UNUSUAL mark of its own, but its median and its change may be moved " +
186
+ "by that row's sales. Say so if you mention it."] : []),
187
+ ...(unknown ? ["", "At least one row above carries a mark or a note this version of the tool does not know; it is shown " +
188
+ "on its line as the file gives it. Its figure is DCJ's own. Do not quote that row as a going price, and read " +
189
+ "\"What DwellDelta changed\" below for what the file's marks mean."] : []),
130
190
  "",
131
191
  "Limits:",
132
192
  ...feed.limits.map((l) => "- " + l),
133
193
  "",
134
194
  `Source: ${feed.attribution}`,
135
195
  `What DwellDelta changed: ${feed.changes_made}`,
196
+ citeLine({ source: feed.source, period: `${feed.quarter} (against ${feed.compared_with})`, licence: feed.licence,
197
+ n: nWords(figures, RULE.unit), url: env.sources[0].source_url, notice: env.sources[0].source_notice_url,
198
+ feedUrl, stale: flagged(env) }),
136
199
  FOOTER,
137
200
  ].join("\n");
138
- const pick = (g) => Object.fromEntries(Object.entries(g).filter(([k]) => !DWELLING_TYPES.includes(k) || types.includes(k)));
201
+ // Each place as the file gives it, for the dwelling types asked for, and each dwelling type's row with its own refusal
202
+ // marker. A type with no row in DCJ's table stays null, as the file has it - there is no figure on it to misread -
203
+ // and its not_published refusal is in refusals[]. Copies: the loaded feed is never written to.
204
+ const pick = (g) => Object.fromEntries(Object.entries(g).filter(([k]) => !DWELLING_TYPES.includes(k) || types.includes(k))
205
+ .map(([k, v]) => [k, DWELLING_TYPES.includes(k) && v && typeof v === "object" ? { ...v, ...refusalMark(judged.get(g)[k]) } : v]));
139
206
  return { text, structured: { ...env, state: "NSW", measure: "sale_price", unit: feed.unit, area_kind: "postcode",
140
207
  quarter: feed.quarter, compared_with: feed.compared_with,
141
208
  dwelling_types: feed.dwelling_types ?? null,
142
209
  state_total: whole ? pick(feed.state_total) : null,
143
210
  councils: councils.map(pick), areas: areas.map(pick), any_unusual: marked,
144
- truncated: dropped.length > 0, limits: feed.limits, changes_made: feed.changes_made } };
211
+ any_unusual_part: noted,
212
+ truncated: dropped.length > 0, limits: feed.limits, changes_made: feed.changes_made,
213
+ ...figureFields(figures), sample_rule: RULE } };
145
214
  }
package/server.mjs CHANGED
@@ -2,10 +2,12 @@
2
2
  // DwellDelta MCP server: Australian property market data for AI agents. Runs on the user's machine over stdio and
3
3
  // records nothing unless the user chooses to add their rent. From 0.4.0 it fetches the week's indicators once at start from tools.dwelldelta.com.au - one
4
4
  // public file; nothing about the user or their questions is sent - and falls back to its bundled copy
5
- // (DWELLDELTA_OFFLINE=1 never fetches). Six read-only tools; the logic lives in tools.mjs, vic_rents
5
+ // (DWELLDELTA_OFFLINE=1 never fetches); from 0.9.0 so is the ABS rents index behind rent_check. Six read-only
6
+ // tools; the logic lives in tools.mjs, vic_rents
6
7
  // (Victorian rents by suburb group, 0.5.0) in vic-rents-tool.mjs, area_rents (NSW postcodes, Queensland suburbs
7
8
  // and WA localities, 0.6.0) in area-rents-tool.mjs, and nsw_sale_prices (NSW median sale prices by postcode, 0.7.0)
8
- // in sale-prices-tool.mjs, each feed loaded the same way. A seventh tool,
9
+ // in sale-prices-tool.mjs, each feed loaded the same way. area_rents also answers by dwelling type and bedrooms for
10
+ // NSW and Queensland (0.8.0), from two larger files that are not bundled. A seventh tool,
9
11
  // contribute_rent (contribute-tool.mjs), is connected from 0.5.0 (2026-10-03): it sends a rent only on a second call carrying the user's agreement.
10
12
  //
11
13
  // Every result carries text to quote and a structured result (the figures plus where they come from, under which
@@ -16,16 +18,18 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
16
18
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
17
19
  import { z } from "zod";
18
20
  import {
19
- rentCheckResult, marketIndicatorsResult, dataSourcesResult, loadJson, loadSnapshot, ToolError,
21
+ rentCheckResult, marketIndicatorsResult, dataSourcesResult, loadJson, loadSnapshot, loadRentsIndex, ToolError,
20
22
  RENTS_PATH, INDICATORS_PATH, SERVER_VERSION,
21
23
  } from "./tools.mjs";
22
24
  import { makeContributeTool, INSTRUCTION } from "./contribute-tool.mjs";
23
25
  import { loadVicRents, vicRentsResult } from "./vic-rents-tool.mjs";
24
- import { loadAllAreaRents, areaRentsResult, STATES } from "./area-rents-tool.mjs";
26
+ import { loadAllAreaRents, loadAllRentsByType, wantsByType, areaRentsResult, STATES } from "./area-rents-tool.mjs";
25
27
  import { loadNswSales, salePricesResult, DWELLING_TYPES } from "./sale-prices-tool.mjs";
26
28
  import { HOME_TYPES, BEDROOMS, LEASE_KINDS, WHOSE } from "./vendor/contribute.mjs";
27
29
 
28
- const rents = await loadJson(RENTS_PATH);
30
+ // The ABS rents index: the published copy if it is well formed, covers each bundled city's months and runs to no
31
+ // month after this one, else the bundled copy (DWELLDELTA_OFFLINE=1 never fetches). With neither readable, reading the bundled file fails as it always has.
32
+ const rents = (await loadRentsIndex()).rents ?? await loadJson(RENTS_PATH);
29
33
  const { suburbs } = await loadJson(new URL("./vendor/nsw-suburbs.json", import.meta.url));
30
34
  const contributeRent = makeContributeTool({ suburbs });
31
35
  const loaded = await loadSnapshot();
@@ -33,6 +37,10 @@ const snapshot = loaded.snapshot ? { ...loaded.snapshot, origin: loaded.origin }
33
37
  const vicLoaded = await loadVicRents();
34
38
  const vic = vicLoaded.feed ? { ...vicLoaded.feed, origin: vicLoaded.origin } : null;
35
39
  const areaRents = await loadAllAreaRents();
40
+ // The NSW and Queensland rents by dwelling type files are large and are not bundled. They are asked for here, once,
41
+ // at start - never in response to a question - and NOT awaited: the server is ready without them, and the first
42
+ // by-type question waits for this promise. It never rejects.
43
+ const rentsByType = loadAllRentsByType();
36
44
  const salesLoaded = await loadNswSales();
37
45
  const nswSales = salesLoaded.feed ? { ...salesLoaded.feed, origin: salesLoaded.origin } : null;
38
46
  const readOnly = { readOnlyHint: true, idempotentHint: true, openWorldHint: false, destructiveHint: false };
@@ -118,15 +126,29 @@ server.registerTool("area_rents", {
118
126
  "Communities and Justice), QLD by suburb or council (Residential Tenancies Authority), WA by locality " +
119
127
  "(calculated by DwellDelta from the Government of Western Australia's bond records). Each CC BY 4.0. With no " +
120
128
  "area or council it gives the state's own figure. New-bond medians, not advertised rents; never add or compare " +
121
- "the states as one series; quote the quarter, the source line and the limits. Victoria is in vic_rents.",
129
+ "the states as one series; quote the quarter, the source line and the limits. Victoria is in vic_rents. " +
130
+ "For NSW and QLD, give dwelling_type or bedrooms (or both) for the publisher's figure for that kind of home " +
131
+ "instead - a two-bedroom unit, a three-bedroom house. Only combinations the publisher reports are answered: " +
132
+ "one with no published median is said to have none, and must not be filled from another area or from the " +
133
+ "all-dwellings figure. Many such figures rest on few bonds. WA has no figures by dwelling type or bedrooms.",
122
134
  inputSchema: {
123
135
  state: z.enum(Object.keys(STATES)).describe("NSW, QLD or WA - one state per call"),
124
136
  area: z.string().optional().describe("NSW: a four-digit postcode (a suburb name returns its postcodes to try). " +
125
137
  "QLD: a suburb. WA: a locality. Part of a suburb or locality name works"),
126
138
  council: z.string().optional().describe("A council (NSW or QLD), or part of its name"),
139
+ dwelling_type: z.string().optional().describe("NSW and QLD only. NSW (DCJ's labels): House, Townhouse, " +
140
+ "Flat/Unit, Other. QLD (the RTA's): Flat, House, Townhouse. 'unit' and 'apartment' are read as flat/unit. " +
141
+ "Without bedrooms, every size the publisher reports for that type is given"),
142
+ bedrooms: z.string().optional().describe("NSW and QLD only: a number of bedrooms, as '2' or '2 bedrooms'. NSW " +
143
+ "also has Bedsitter, and 4 means DCJ's '4 or more Bedrooms'; a number above 4 is answered under that label " +
144
+ "too, and the answer says it is not for that number alone. QLD: the RTA publishes flats of 1 to 3, houses " +
145
+ "of 2 to 4 and town houses of 2 to 3, and does not define its labels - reading the number as bedrooms is " +
146
+ "DwellDelta's. A plus means 'or more', which only DCJ's 4 has: '3+', and any 'N+' for QLD, is refused, not " +
147
+ "answered as exactly N. Without dwelling_type, every type the publisher reports at that size is given"),
127
148
  },
128
149
  annotations: readOnly,
129
- }, guard((args) => areaRentsResult(args, areaRents, new Date(), { nswSuburbs: suburbs })));
150
+ }, guard(async (args) => areaRentsResult(args, areaRents, new Date(),
151
+ { nswSuburbs: suburbs, byType: wantsByType(args) ? await rentsByType : {} })));
130
152
 
131
153
  server.registerTool("nsw_sale_prices", {
132
154
  title: "NSW median sale prices by postcode or council",
@@ -135,7 +157,9 @@ server.registerTool("nsw_sale_prices", {
135
157
  "dwellings, non_strata (separate houses) and strata (units, town houses, villas). From the NSW Department of " +
136
158
  "Communities and Justice's Rent and Sales Report (CC BY 4.0). Medians of homes sold: not asking prices, not " +
137
159
  "valuations, and never what any one home sold for or is worth. A line marked UNUSUAL was set by a few very " +
138
- "large sales - say so, and do not quote it as a going price. Always name the dwelling type, the quarter and " +
160
+ "large sales - say so, and do not quote it as a going price. A total noted as mostly a marked row's sales may " +
161
+ "be moved by them - say that, and no more. A line with any other mark or note: do not quote it as a going " +
162
+ "price, and claim nothing about why. Always name the dwelling type, the quarter and " +
139
163
  "the source line, and repeat the limits. With no area or council it gives the state's own figures.",
140
164
  inputSchema: {
141
165
  area: z.string().optional().describe("A four-digit NSW postcode (a suburb name returns its postcodes to try)"),
package/tools.mjs CHANGED
@@ -17,7 +17,7 @@ import { fileURLToPath } from "node:url";
17
17
  import { dirname, join } from "node:path";
18
18
  // 0.3.0: the package is self-contained. vendor/ holds copies of the rent check's arithmetic and ABS data, and the
19
19
  // latest indicators snapshot, made by scripts/vendor.mjs before every pack; a repo test fails if a copy drifts.
20
- import { assess, sentences, LIMITS } from "./vendor/rent-check.mjs";
20
+ import { assess, sentences, LIMITS, isMonth } from "./vendor/rent-check.mjs";
21
21
 
22
22
  const HERE = dirname(fileURLToPath(import.meta.url));
23
23
  export const RENTS_PATH = join(HERE, "vendor", "rents-index.json");
@@ -62,7 +62,7 @@ export async function loadSnapshot({ env = process.env, fetchImpl = globalThis.f
62
62
  }
63
63
 
64
64
  export const FOOTER = "Information, not advice. From DwellDelta (dwelldelta.com.au), built on public data.";
65
- export const SERVER_VERSION = "0.7.0";
65
+ export const SERVER_VERSION = "0.9.0";
66
66
  // The indicators snapshot is rebuilt every Monday. Older than this and the answer says so, in words and in the
67
67
  // structured result, rather than serving a stale figure as current.
68
68
  export const STALE_DAYS = 10;
@@ -71,6 +71,227 @@ export async function loadJson(path) {
71
71
  return JSON.parse(await readFile(path, "utf8"));
72
72
  }
73
73
 
74
+ // --- provenance an agent can check (from 0.9.0; prepared 2026-10-20) ---------------------------------------------
75
+ // Control advisory 2026-10-20 (competitor research), recommendation 2, "make the edge checkable": every figure carries
76
+ // its source with a URL (or, where the file names only a copyright notice, that notice, called so), its period, a
77
+ // licence id, its as-at date, its sample size where the data has one, and an overdue flag from the data's own release
78
+ // cadence (period_overdue); a figure that rests on too few records is a typed refusal, never a weak number. Every
79
+ // field below is NEW: the fields answers carried before keep their meaning - stale is still only the weekly snapshot.
80
+
81
+ /** DwellDelta's published copy of the rents index - the file an agent can fetch to check a rent check. */
82
+ export const RENTS_FEED_URL = "https://tools.dwelldelta.com.au/rent/data/rents-index.json";
83
+
84
+ // From 0.9.0 rent_check reads that published copy like every other feed. Up to 0.8.0 it read
85
+ // only the copy bundled at pack time and answered to that copy's latest month, never saying the index had moved on. The
86
+ // ABS releases a month at a time; the site's copy (rent/data/rents-index.json) is updated with each release.
87
+ /** The month after a YYYY-MM month. */
88
+ const nextMonth = (ym) => {
89
+ const [y, m] = ym.split("-").map(Number);
90
+ return m === 12 ? `${y + 1}-01` : `${y}-${String(m + 1).padStart(2, "0")}`;
91
+ };
92
+ /** The latest month of a rents index: the last month any city's series reaches ("" if none). */
93
+ export const rentsLatest = (r) => Object.values(r?.cities ?? {})
94
+ .map((c) => Object.keys(c?.points ?? {}).sort().at(-1) ?? "").sort().at(-1) ?? "";
95
+ /**
96
+ * Well formed, as the shipped file is held to (tests/rent-check.test.mjs): its source, attribution, licence and
97
+ * release named; every city a run of contiguous months, each with a positive index value; and, beside a bundled copy,
98
+ * every city that copy has - rent_check's list of cities is built from this file, and a copy that dropped one would
99
+ * take it away.
100
+ */
101
+ const rentsWellFormed = (r, shipped = null) => r && typeof r === "object"
102
+ && ["source", "attribution", "licence", "release"].every((k) => typeof r[k] === "string" && r[k].trim() !== "")
103
+ && r.cities && typeof r.cities === "object" && Object.keys(r.cities).length > 0
104
+ && Object.values(r.cities).every((c) => {
105
+ const months = c && c.points && typeof c.points === "object" ? Object.keys(c.points).sort() : [];
106
+ return months.length > 0 && months.every((m, i) => isMonth(m) && (i === 0 || nextMonth(months[i - 1]) === m))
107
+ && Object.values(c.points).every((v) => Number.isFinite(v) && v > 0);
108
+ })
109
+ && (!shipped || Object.keys(shipped.cities).every((city) => city in r.cities));
110
+ /** A city's months, in order. */
111
+ const monthsOf = (c) => Object.keys(c?.points ?? {}).sort();
112
+ /**
113
+ * Covers the bundled copy city by city: for every city the bundled copy has, the published series starts no later
114
+ * and ends no earlier. A copy that is newer overall can still end one city early, or start later and drop the older
115
+ * months a lease start needs; either answers worse than the bundle, so the bundle answers instead.
116
+ */
117
+ const rentsCover = (r, shipped) => Object.entries(shipped.cities).every(([city, c]) => {
118
+ const have = monthsOf(r.cities[city]), want = monthsOf(c);
119
+ return have.length > 0 && want.length > 0 && have[0] <= want[0] && have.at(-1) >= want.at(-1);
120
+ });
121
+ /**
122
+ * No month later than the current one (UTC), read from the clock every answer's staleness is read from: a copy
123
+ * that runs into the future is not an ABS release, whatever else is right with it.
124
+ */
125
+ const rentsNotAhead = (r, now) => {
126
+ const month = now.toISOString().slice(0, 7);
127
+ return Object.values(r.cities).every((c) => (monthsOf(c).at(-1) ?? "") <= month);
128
+ };
129
+
130
+ /**
131
+ * The rents index and where it came from: "published" (DwellDelta's copy at RENTS_FEED_URL, fetched once at start -
132
+ * a plain request for one public file; nothing about the user or their questions is sent - and used only if it is
133
+ * well formed, covers every city of the bundled copy from that city's first month to its last, and has no month
134
+ * later than the current one) or "bundled" (the copy shipped in the package). DWELLDELTA_OFFLINE=1 never fetches.
135
+ * Never throws for a failed fetch; { rents: null } only when no copy can be read at all.
136
+ */
137
+ export async function loadRentsIndex({ env = process.env, fetchImpl = globalThis.fetch, bundled = RENTS_PATH,
138
+ now = new Date() } = {}) {
139
+ const shipped = await loadJson(bundled).then((r) => (rentsWellFormed(r) ? r : null)).catch(() => null);
140
+ if (env.DWELLDELTA_OFFLINE !== "1" && typeof fetchImpl === "function") {
141
+ try {
142
+ const res = await fetchImpl(RENTS_FEED_URL, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
143
+ const got = res.ok ? await res.json() : null;
144
+ if (rentsWellFormed(got, shipped) && rentsNotAhead(got, now) && (!shipped || rentsCover(got, shipped))) {
145
+ return { rents: got, origin: "published" };
146
+ }
147
+ } catch {
148
+ // Offline, blocked or slow: the bundled copy answers, and the overdue flag says how old it is.
149
+ }
150
+ }
151
+ return { rents: shipped, origin: shipped ? "bundled" : null };
152
+ }
153
+
154
+ /** SPDX ids for the licences the data files name. Any other licence (the RBA's permission) has no id: null. */
155
+ const SPDX = { "CC BY 4.0": "CC-BY-4.0", "CC BY 3.0 AU": "CC-BY-3.0-AU" };
156
+ export const licenceId = (licence) => SPDX[String(licence ?? "").trim()] ?? null;
157
+
158
+ const httpUrl = (v) => (typeof v === "string" && /^https?:\/\/\S+$/.test(v) ? v : null);
159
+
160
+ /**
161
+ * The address of the data's own page, as the data file gives it, and never made up: its source_url or url field,
162
+ * else an address written in its source line (Homes Victoria's "via DataVic (discover.data.vic.gov.au/dataset/...)",
163
+ * given https://). Null when the file has none. A file's source_notice is NOT read here: for DCJ and the RTA it is
164
+ * the publisher's copyright notice, which is not where the data is (see feedSource).
165
+ */
166
+ export function sourceUrl(s) {
167
+ for (const key of ["source_url", "url"]) {
168
+ if (httpUrl(s?.[key])) return s[key];
169
+ }
170
+ const m = /\b((?:https?:\/\/)?(?:[a-z0-9-]+\.)+(?:au|org|com|net)\/[^\s)]+)/i.exec(String(s?.source ?? ""));
171
+ if (!m) return null;
172
+ const found = m[1].replace(/[.,;]+$/, "");
173
+ return /^https?:\/\//.test(found) ? found : `https://${found}`;
174
+ }
175
+
176
+ /**
177
+ * A data file as the one source of an answer: what envelope() needs to say where its figures come from.
178
+ * The files' source_notice is the page their attribution rests on. For DCJ (NSW rents, rents by type, sale prices)
179
+ * and the RTA (Queensland) that is a copyright notice, not a page of the data: it is source_notice_url, labelled
180
+ * "copyright notice" in the Cite line, and source_url stays null. Only a tool that knows its file's notice IS the
181
+ * data's page (WA: the Housing Data Exchange dataset page) passes noticeIsData, and then it is the source_url.
182
+ */
183
+ export const feedSource = (f, feedUrl, period, { noticeIsData = false } = {}) => ({
184
+ source: f.source, licence: f.licence, attribution: f.attribution, licence_url: f.licence_url,
185
+ source_url: f.source_url ?? (noticeIsData ? f.source_notice : null), url: f.url,
186
+ source_notice_url: noticeIsData ? null : f.source_notice ?? null, feed_url: feedUrl, period,
187
+ });
188
+
189
+ /**
190
+ * Release cadence, and when a figure is overdue for replacing. months: from the end of the data's latest period
191
+ * to the end of the month by which the next release was due.
192
+ * - The ABS monthly CPI comes out about four weeks after each month, so the month after the latest is due within
193
+ * two months of the latest month's end.
194
+ * - A quarterly rents feed: one quarter for the next quarter, then up to four months for the publisher to release
195
+ * it (DCJ's June 2026 rents reached the feed on 2026-10-10).
196
+ * - NSW sale prices: three months more, because DCJ's sales quarter runs one quarter behind its rents quarter in
197
+ * the same report (March 2026 sales came with June 2026 rents).
198
+ */
199
+ export const CADENCE = {
200
+ abs_monthly: { cadence: "monthly", months: 2 },
201
+ rents_quarterly: { cadence: "quarterly", months: 7 },
202
+ sales_quarterly: { cadence: "quarterly", months: 10 },
203
+ };
204
+ const MON = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
205
+
206
+ /**
207
+ * The last day of the month `months` after a period - "Jun 2026" or "2026-08" - as YYYY-MM-DD; null if unreadable.
208
+ * That is the day by which the release after the period was due: past it, the period is overdue (period_overdue).
209
+ */
210
+ export function periodDueBy(period, months) {
211
+ const p = String(period ?? "");
212
+ let y, m;
213
+ const iso = /^(\d{4})-(\d{2})$/.exec(p);
214
+ if (iso) { y = Number(iso[1]); m = Number(iso[2]); }
215
+ else {
216
+ const [mon, yr] = p.split(" ");
217
+ m = MON.indexOf(String(mon ?? "").slice(0, 3)) + 1;
218
+ y = Number(yr);
219
+ if (!m || !/^\d{4}$/.test(yr ?? "")) return null;
220
+ }
221
+ return new Date(Date.UTC(y, m + months, 0)).toISOString().slice(0, 10);
222
+ }
223
+
224
+ /**
225
+ * The publishers' own small-sample rules: below them there is no median, and the answer is a refusal. Each is the
226
+ * rule its data file states in its limits, and a test holds the vendored files to them. min_n is the fewest records
227
+ * a median may rest on; null where the publisher withholds medians but states no number.
228
+ */
229
+ export const SAMPLE_RULES = {
230
+ NSW_RENTS: { unit: "new bonds", min_n: 11, rule: "DCJ reports nothing where 10 or fewer new bonds were lodged" },
231
+ QLD_RENTS: { unit: "new bonds", min_n: null, rule: "the RTA publishes no median where too few bonds were lodged, and states no number" },
232
+ WA_RENTS: { unit: "new bonds", min_n: 10, rule: "a locality needs 10 bonds in the quarter for a median (DwellDelta's rule for its own calculation)" },
233
+ VIC_RENTS: { unit: "new leases", min_n: null, rule: "Homes Victoria publishes no median where too few leases began, and states no number" },
234
+ NSW_SALES: { unit: "sales", min_n: 11, rule: "DCJ reports nothing where 10 or fewer dwellings sold" },
235
+ };
236
+
237
+ /**
238
+ * One figure's sample and, if it rests on too few records, its refusal. median and count name the row's fields;
239
+ * why is the reason the answer already gives for a missing median, and missing its type. A median below the rule's
240
+ * min_n is refused too: the published files have none, so this guards against a builder that ever lets one
241
+ * through. No figure is changed here.
242
+ */
243
+ export function judgeFigure(r, { name, median, count, band = null, rule, why = null, missing = "too_few_records" }) {
244
+ const n = Number.isFinite(r?.[count]) ? r[count] : null;
245
+ const nBand = band && r?.[band] ? r[band] : null;
246
+ const base = { n, n_band: nBand, unit: rule.unit, min_n: rule.min_n, rule: rule.rule };
247
+ let refusal = null;
248
+ if (r == null) refusal = { refused: true, type: "not_published", reason: why ?? "no row in the publisher's table", ...base };
249
+ else if (r[median] == null) refusal = { refused: true, type: missing, reason: why ?? `too few ${rule.unit}`, ...base };
250
+ else if (rule.min_n != null && n != null && n < rule.min_n) {
251
+ refusal = { refused: true, type: "too_few_records",
252
+ reason: `${n} ${rule.unit}, fewer than the ${rule.min_n} a published median needs (${rule.rule})`, ...base };
253
+ }
254
+ return { name, n, n_band: nBand, unit: rule.unit, small_sample: r?.small_sample === true, refusal };
255
+ }
256
+
257
+ /**
258
+ * The marker each structured row carries for its own figure (from 0.9.0; additions only): refused, and the
259
+ * refusal's type (too_few_records or not_published, as in refusals[]) - false and null for a figure that is given.
260
+ * A refused row keeps every field the file gives it, the weak median included; this says the text refused it, on
261
+ * the row itself, so an agent reading the rows need not match them to figures[] by name.
262
+ */
263
+ export const refusalMark = (figure) => ({ refused: Boolean(figure?.refusal), refusal_type: figure?.refusal?.type ?? null });
264
+
265
+ /** The structured fields every figure-giving answer adds: each figure's sample, and the refusals among them. */
266
+ export function figureFields(figures) {
267
+ const refusals = figures.filter((f) => f.refusal).map((f) => ({ name: f.name, ...f.refusal }));
268
+ return { figures, refusals, all_refused: figures.length > 0 && refusals.length === figures.length };
269
+ }
270
+
271
+ const sampleWords = (f) => (f.refusal
272
+ ? `none: ${f.refusal.type === "too_few_records" ? "too few records" : "not published"} (${f.refusal.reason})`
273
+ : f.n != null ? `${f.n.toLocaleString("en-AU")} ${f.unit}`
274
+ : f.n_band ? `${f.n_band} ${f.unit} (the publisher withholds the exact count)` : `not published (${f.unit})`);
275
+
276
+ /** What n is, in words, for the Cite line: one figure's own count, or how the lines above give it. */
277
+ export function nWords(figures, unit) {
278
+ if (figures.length === 1) return sampleWords(figures[0]);
279
+ const refused = figures.filter((f) => f.refusal).length;
280
+ return `on each line above, in ${unit}` +
281
+ (refused ? `; ${refused} of ${figures.length} refused (too few records, or not published)` : "");
282
+ }
283
+
284
+ /**
285
+ * The quotable provenance line: source, period, licence, n, the source's URL (or the copyright notice the
286
+ * publisher's attribution rests on, called that and nothing else) and DwellDelta's data file. stale: the answer
287
+ * opens with a STALE line (staleNote) - the weekly snapshot is old, or the period is overdue.
288
+ */
289
+ export function citeLine({ source, period, licence, n, url, notice = null, feedUrl, stale }) {
290
+ return `Cite: ${String(source ?? "").replace(/[.\s]+$/, "")}; period ${period}; licence ${licenceId(licence) ?? licence}; ` +
291
+ `n ${n}; source URL ${url ?? "none in the data file"}${notice ? `; copyright notice ${notice}` : ""}; ` +
292
+ `data file ${feedUrl}${stale ? "; STALE" : ""}.`;
293
+ }
294
+
74
295
  /** A failed call: marked as an error so an agent cannot mistake it for data, with the next step to take. */
75
296
  export class ToolError extends Error {
76
297
  constructor(message, recovery) {
@@ -83,9 +304,15 @@ export class ToolError extends Error {
83
304
  * The provenance that travels WITH every answer, as structured data an agent can carry into its own output.
84
305
  * "The attribution must travel with the data" - the principle, from abs-mcp's DataResponse.
85
306
  */
86
- export function envelope({ sources, dataAsOf, built = null, origin = null }, now = new Date()) {
307
+ export function envelope({ sources, dataAsOf, built = null, origin = null, cadence = null }, now = new Date()) {
308
+ // stale and stale_reason mean what they have meant since 0.2.0: the weekly indicators snapshot is more than
309
+ // STALE_DAYS old. They are false and null for every answer without a snapshot (rents, sale prices, rent_check).
87
310
  const age = built ? Math.floor((now - new Date(built + "T00:00:00Z")) / 86400000) : null;
88
311
  const stale = age !== null && age > STALE_DAYS;
312
+ // New in 0.9.0, in fields of their own: from the data's own release cadence, whether the release after this
313
+ // period was due and has not reached the file (period_overdue). A released field keeps its meaning.
314
+ const dueBy = cadence ? periodDueBy(dataAsOf, cadence.months) : null;
315
+ const overdue = dueBy !== null && now.toISOString().slice(0, 10) > dueBy;
89
316
  return {
90
317
  publisher: "DwellDelta, a service of Xcelerent Pty Ltd",
91
318
  server_version: SERVER_VERSION,
@@ -95,12 +322,34 @@ export function envelope({ sources, dataAsOf, built = null, origin = null }, now
95
322
  snapshot_origin: origin,
96
323
  stale,
97
324
  stale_reason: stale ? `the indicators snapshot was built ${built}, ${age} days ago; it is rebuilt weekly` : null,
98
- sources: sources.map((s) => ({ source: s.source, licence: s.licence, attribution: s.attribution ?? null })),
325
+ stale_after: built ? isoDay(new Date(built + "T00:00:00Z"), STALE_DAYS) : null,
326
+ cadence: cadence ? cadence.cadence : built ? "weekly" : null,
327
+ period_due_by: dueBy,
328
+ period_overdue: overdue,
329
+ period_overdue_reason: overdue ? `these figures are for ${dataAsOf}; they are published ${cadence.cadence}, and ` +
330
+ `the release after them was due by ${dueBy}` : null,
331
+ sources: sources.map((s) => ({ source: s.source, licence: s.licence, attribution: s.attribution ?? null,
332
+ ...pickProvenance(s) })),
99
333
  advice: false,
100
334
  };
101
335
  }
102
336
 
103
- const staleNote = (env) => (env.stale ? [`STALE: ${env.stale_reason}. Say so if you quote these figures.`, ""] : []);
337
+ const isoDay = (d, plusDays) => new Date(d.getTime() + plusDays * 86400000).toISOString().slice(0, 10);
338
+ /** The new provenance fields of a source, filled from the source itself where the caller did not. */
339
+ function pickProvenance(s) {
340
+ return { licence_id: s.licence_id ?? licenceId(s.licence), licence_url: s.licence_url ?? null,
341
+ source_url: sourceUrl(s), source_notice_url: httpUrl(s.source_notice_url), feed_url: s.feed_url ?? null,
342
+ period: s.period ?? null };
343
+ }
344
+
345
+ /** True when the answer opens with a STALE line: the weekly snapshot is old, or the data's period is overdue. */
346
+ export const flagged = (env) => env.stale || env.period_overdue === true;
347
+
348
+ export const staleNote = (env) => [
349
+ ...(env.stale ? [`STALE: ${env.stale_reason}. Say so if you quote these figures.`] : []),
350
+ ...(env.period_overdue ? [`STALE: ${env.period_overdue_reason}. Say so if you quote these figures.`] : []),
351
+ ...(flagged(env) ? [""] : []),
352
+ ];
104
353
 
105
354
  /** rent_check: the public rent check's own arithmetic, unchanged, with its limits every time. */
106
355
  export function rentCheck(args, rents) {
@@ -117,19 +366,27 @@ export function rentCheckResult({ city, lease_start, current_rent, proposed_rent
117
366
  : "Use a lease start on or before the latest month of the index; call data_sources for coverage.";
118
367
  throw new ToolError(err.message, recovery);
119
368
  }
120
- const env = envelope({ sources: [rents], dataAsOf: r.latest }, now);
369
+ const period = `${r.startUsed} to ${r.latest}`;
370
+ const env = envelope({ sources: [{ ...rents, feed_url: RENTS_FEED_URL, period }], dataAsOf: r.latest,
371
+ cadence: CADENCE.abs_monthly }, now);
121
372
  const text = [
373
+ ...staleNote(env),
122
374
  ...sentences(r),
123
375
  "",
124
376
  "Limits:",
125
377
  ...LIMITS.map((l) => "- " + l),
126
378
  "",
127
379
  `Source: ${rents.source} ${rents.attribution}, ${rents.licence}. ABS release ${rents.release}.`,
380
+ citeLine({ source: rents.source.split(". ")[0], period: `${period} (ABS release ${rents.release})`, licence: rents.licence,
381
+ n: `not applicable (${INDEX_N})`, url: env.sources[0].source_url, feedUrl: RENTS_FEED_URL, stale: flagged(env) }),
128
382
  FOOTER,
129
383
  ].join("\n");
130
- return { text, structured: { ...env, result: r, limits: LIMITS } };
384
+ return { text, structured: { ...env, result: r, limits: LIMITS, sample_size: null, sample_size_note: INDEX_N } };
131
385
  }
132
386
 
387
+ const INDEX_N = "an index of what tenants pay, not a count of leases; the ABS publishes no sample size with it";
388
+ const INDICATOR_N = "these sources publish no sample size with these figures";
389
+
133
390
  function describe(i) {
134
391
  const change = i.change
135
392
  ? `, ${i.change.value >= 0 ? "+" : ""}${i.change.value} ${i.change.unit} over the ${i.change.over}`
@@ -137,7 +394,7 @@ function describe(i) {
137
394
  return [
138
395
  `${i.name} - ${i.geography}, ${i.period}: ${i.value} ${i.unit}${change}.`,
139
396
  i.limit ? ` Limit: ${i.limit}` : null,
140
- ` Source: ${i.source}${i.attribution ? " " + i.attribution + "," : ""} ${i.licence}.`,
397
+ ` Source: ${i.source}${i.attribution ? " " + i.attribution + "," : ""} ${i.licence}.${sourceUrl(i) ? " " + sourceUrl(i) : ""}`,
141
398
  ].filter(Boolean).join("\n");
142
399
  }
143
400
 
@@ -155,7 +412,10 @@ export function marketIndicatorsResult({ geography } = {}, snapshot, now = new D
155
412
  throw new ToolError(`No indicators for "${geography}".`,
156
413
  `Call market_indicators again with one of: ${GEOGRAPHIES(snapshot).join(", ")}; or with no geography for all.`);
157
414
  }
158
- const env = envelope({ sources: snapshot.sources, dataAsOf: items.map((i) => i.period).sort().at(-1),
415
+ // Each source's period is the latest period of the figures shown from it (null for a source none of them uses).
416
+ const latestFrom = (s) => items.filter((i) => i.source === s.source).map((i) => i.period).sort().at(-1) ?? null;
417
+ const env = envelope({ sources: snapshot.sources.map((s) => ({ ...s, feed_url: PUBLISHED_URL, period: latestFrom(s) })),
418
+ dataAsOf: items.map((i) => i.period).sort().at(-1),
159
419
  built: snapshot.built, origin: snapshot.origin ?? null }, now);
160
420
  const text = [
161
421
  ...staleNote(env),
@@ -164,9 +424,15 @@ export function marketIndicatorsResult({ geography } = {}, snapshot, now = new D
164
424
  "",
165
425
  ...items.map(describe),
166
426
  "",
427
+ citeLine({ source: "each figure's source, as on its line", period: "each figure's own, as on its line" +
428
+ ` (latest ${env.data_as_of}; snapshot built ${snapshot.built})`,
429
+ licence: "each figure's own, as on its line", n: `not applicable (${INDICATOR_N})`,
430
+ url: items.some((i) => sourceUrl(i)) ? "each figure's own, as on its line" : null, feedUrl: PUBLISHED_URL, stale: flagged(env) }),
167
431
  FOOTER,
168
432
  ].join("\n");
169
- return { text, structured: { ...env, indicators: items } };
433
+ // Each indicator as the snapshot gives it, plus its licence id, its source's URL (none in today's snapshot) and n.
434
+ const indicators = items.map((i) => ({ ...i, licence_id: licenceId(i.licence), source_url: sourceUrl(i), sample_size: null }));
435
+ return { text, structured: { ...env, indicators, sample_size: null, sample_size_note: INDICATOR_N } };
170
436
  }
171
437
 
172
438
  /** data_sources: what DwellDelta covers, under which licences, and what it cannot answer. */
@@ -182,12 +448,15 @@ export function dataSourcesResult(snapshot, now = new Date()) {
182
448
  `Publisher: ${snapshot.publisher}.`,
183
449
  "",
184
450
  "Sources:",
185
- ...snapshot.sources.map((s) => `- ${s.source} ${s.attribution ? s.attribution + ", " : ""}${s.licence}`),
451
+ ...snapshot.sources.map((s) => `- ${s.source} ${s.attribution ? s.attribution + ", " : ""}${s.licence}` +
452
+ (sourceUrl(s) ? ` (${sourceUrl(s)})` : "")),
186
453
  "",
187
454
  "Cannot answer:",
188
455
  ...snapshot.cannot_answer.map((c) => "- " + c),
189
456
  "",
190
457
  snapshot.rules,
458
+ "Every answer that gives a figure ends with a Cite line: its source, period, licence, sample size (n), the " +
459
+ "source's URL and DwellDelta's data file. A figure that rests on too few records is refused, never given.",
191
460
  FOOTER,
192
461
  ].join("\n");
193
462
  return { text, structured: { ...env, cannot_answer: snapshot.cannot_answer, rules: snapshot.rules } };