From 915a811b689b65a124f873a1331d03e6c9e0dc13 Mon Sep 17 00:00:00 2001 From: aditya9515 Date: Sun, 6 Dec 2026 11:07:58 +0530 Subject: [PATCH 01/16] test(mobile): cover design and motion tokens (#230) --- apps/mobile/src/tokens.test.ts | 73 ++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 apps/mobile/src/tokens.test.ts diff --git a/apps/mobile/src/tokens.test.ts b/apps/mobile/src/tokens.test.ts new file mode 100644 index 0000000..e5e23ec --- /dev/null +++ b/apps/mobile/src/tokens.test.ts @@ -0,0 +1,73 @@ +/// +// Hermit's design tokens (docs/design/polish/decisions.md): every color is a docs/brand/tokens.json value, or a mix of +// two of them (mix): the surfaces between the canvas and white, the tonal fills between a surface and an accent, and +// the scrims. Light is Quiet craft; dark is Deep sea. The motion tokens live beside them (docs/design/polish/decisions.md, +// "Motion"): plain numbers, no animation library. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mix } from "./theme.ts"; +import { duration, easing, stagger, staggerDelay } from "./motion.ts"; + +test("mix(a, b, t) holds at a when t is 0 and at b when t is 1", () => { + assert.equal(mix("#F5EDE1", "#B4483A", 0), "#F5EDE1"); + assert.equal(mix("#F5EDE1", "#B4483A", 1), "#B4483A"); +}); + +test("mix rounds to a whole hex channel at the midpoint", () => { + // Half of #000000 → #808080: the blend rounds, it does not truncate. + assert.equal(mix("#000000", "#FFFFFF", 0.5), "#808080"); +}); + +test("mix answers in uppercase #RRGGBB even when the inputs are lowercase", () => { + assert.match(mix("#ffffff", "#2b221b", 0.5), /^#[0-9A-F]{6}$/); +}); + +test("mix keeps every channel between the two inputs while t is between 0 and 1", () => { + const pairs: Array<[string, string]> = [ + ["#000000", "#FFFFFF"], + ["#06121D", "#5EF0CF"], + ["#2B221B", "#8A5912"], + ]; + for (const [a, b] of pairs) { + for (const t of [0.25, 0.5, 0.75]) { + const c = mix(a, b, t); + const blend = [0, 1, 2].map((i) => parseInt(c.slice(1 + i * 2, 3 + i * 2), 16)); + const from = [0, 1, 2].map((i) => parseInt(a.slice(1 + i * 2, 3 + i * 2), 16)); + const to = [0, 1, 2].map((i) => parseInt(b.slice(1 + i * 2, 3 + i * 2), 16)); + for (let i = 0; i < 3; i++) { + assert.ok( + blend[i] >= Math.min(from[i], to[i]) && blend[i] <= Math.max(from[i], to[i]), + `channel ${i} of ${c} should stay between ${a} and ${b} at t=${t}`, + ); + } + } + } +}); + +test("staggerDelay spaces items out by one step and stops at stagger.max", () => { + assert.equal(staggerDelay(0), 0); + assert.equal(staggerDelay(1), stagger.step); + assert.equal(staggerDelay(2), stagger.step * 2); + assert.equal(staggerDelay(stagger.max - 1), (stagger.max - 1) * stagger.step); + assert.equal(staggerDelay(stagger.max), stagger.max * stagger.step); + assert.equal(staggerDelay(stagger.max + 4), stagger.max * stagger.step); +}); + +test("duration tokens are positive whole milliseconds, a press is instant and sheet is the longest", () => { + const values = Object.values(duration); + for (const v of values) { + assert.ok(Number.isInteger(v), `duration ${v} should be a whole number of milliseconds`); + assert.ok(v > 0, `duration ${v} should be positive`); + } + assert.ok(duration.press < 100, `a press should read as instant, got ${duration.press}`); + assert.equal(duration.sheet, Math.max(...values), `sheet should be the longest duration, got ${duration.sheet}`); +}); + +test("easing curves are four numbers whose control-x values sit between 0 and 1", () => { + for (const curve of Object.values(easing)) { + assert.equal(curve.length, 4, `a cubic-bezier needs four numbers, got ${curve.length}`); + for (const x of [curve[0], curve[2]]) { + assert.ok(x >= 0 && x <= 1, `a cubic-bezier x value should sit between 0 and 1, got ${x}`); + } + } +}); From 1ddb62e1bb38c629b128b1d94014e9bac2a0a88b Mon Sep 17 00:00:00 2001 From: aditya9515 Date: Sun, 6 Dec 2026 11:44:55 +0530 Subject: [PATCH 02/16] test(core): check the A2A task states table against itself (#223) --- packages/core/test/a2a-store.test.ts | 63 +++++++++++++++++++++++++++- 1 file changed, 62 insertions(+), 1 deletion(-) diff --git a/packages/core/test/a2a-store.test.ts b/packages/core/test/a2a-store.test.ts index ca84579..918c160 100644 --- a/packages/core/test/a2a-store.test.ts +++ b/packages/core/test/a2a-store.test.ts @@ -1,6 +1,6 @@ import { beforeEach, describe, expect, test } from "vitest"; import { nodeSql } from "@hermit/sql-node"; -import { createA2aStore, TASK_STATES, type A2aStore, type TaskState } from "../src/a2a-store.ts"; +import { canTransition, createA2aStore, OPEN_TASK_STATES, TASK_STATES, TERMINAL_TASK_STATES, type A2aStore, type TaskState } from "../src/a2a-store.ts"; import { migrate } from "../src/schema.ts"; import type { SqlPort } from "../src/ports.ts"; @@ -313,3 +313,64 @@ describe("a2a store (A2A 1.0, migration 18)", () => { expect(rejected.status.reason).toBe("hop_cap"); }); }); + +describe("A2A task states", () => { + test("the open and terminal lists hold every state exactly once and share none", () => { + const all = [...OPEN_TASK_STATES, ...TERMINAL_TASK_STATES]; + expect(new Set(all).size).toBe(all.length); + expect([...all].sort()).toEqual([...TASK_STATES].sort()); + for (const state of OPEN_TASK_STATES) { + expect(TERMINAL_TASK_STATES).not.toContain(state); + } + }); + + test("a terminal state cannot move anywhere", () => { + for (const terminal of TERMINAL_TASK_STATES) { + for (const next of TASK_STATES) { + expect(canTransition(terminal, next), `${terminal} to ${next}`).toBe(false); + } + } + }); + + test("no state moves to itself", () => { + for (const state of TASK_STATES) { + expect(canTransition(state, state), state).toBe(false); + } + }); + + test("nothing moves back to submitted", () => { + for (const state of TASK_STATES) { + expect(canTransition(state, "TASK_STATE_SUBMITTED"), state).toBe(false); + } + }); + + test("every open state can reach a terminal state", () => { + const reachesTerminal = (start: TaskState): boolean => { + const seen = new Set([start]); + const queue: TaskState[] = [start]; + while (queue.length > 0) { + const current = queue.shift()!; + if (TERMINAL_TASK_STATES.includes(current)) return true; + for (const next of TASK_STATES) { + if (canTransition(current, next) && !seen.has(next)) { + seen.add(next); + queue.push(next); + } + } + } + return false; + }; + for (const state of OPEN_TASK_STATES) { + expect(reachesTerminal(state), state).toBe(true); + } + }); + + test("the A2A 1.0 spot checks hold", () => { + expect(canTransition("TASK_STATE_SUBMITTED", "TASK_STATE_WORKING")).toBe(true); + expect(canTransition("TASK_STATE_WORKING", "TASK_STATE_INPUT_REQUIRED")).toBe(true); + expect(canTransition("TASK_STATE_INPUT_REQUIRED", "TASK_STATE_WORKING")).toBe(true); + expect(canTransition("TASK_STATE_AUTH_REQUIRED", "TASK_STATE_CANCELED")).toBe(true); + expect(canTransition("TASK_STATE_SUBMITTED", "TASK_STATE_COMPLETED")).toBe(false); + expect(canTransition("TASK_STATE_INPUT_REQUIRED", "TASK_STATE_COMPLETED")).toBe(false); + }); +}); From 1d16fe22bd55374e5dd5e1070f3e783f156492f5 Mon Sep 17 00:00:00 2001 From: aditya9515 Date: Sun, 6 Dec 2026 11:46:35 +0530 Subject: [PATCH 03/16] test(mail): cover how a request picks the email account (#219) --- packages/mail/test/accounts.test.ts | 107 ++++++++++++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 packages/mail/test/accounts.test.ts diff --git a/packages/mail/test/accounts.test.ts b/packages/mail/test/accounts.test.ts new file mode 100644 index 0000000..a3e64a8 --- /dev/null +++ b/packages/mail/test/accounts.test.ts @@ -0,0 +1,107 @@ +// #219: how a request picks the email account (US-MAIL-08). Tests only, accounts.ts is unchanged. +import { describe, expect, test } from "vitest"; +import { accountName, MemoryMailAccountStore, resolveAccounts, type MailAccount } from "../src/accounts.ts"; + +const gmail: MailAccount = { id: "a1", provider: "gmail", address: "ana.personal@example.com", label: "personal", credentialId: "c1", createdAt: 1 }; +const outlook: MailAccount = { id: "a2", provider: "outlook", address: "ana.trabajo@example.com", label: "trabajo", credentialId: "c2", createdAt: 2 }; +const imap: MailAccount = { id: "a3", provider: "imap", address: "bot@example.com", credentialId: "c3", createdAt: 3 }; +const accounts: MailAccount[] = [gmail, outlook, imap]; + +const ids = (r: ReturnType): string[] => { + if (!r.ok) throw new Error(`expected ok, got: ${r.modelText}`); + return r.accounts.map((a) => a.id); +}; + +describe("accountName (#219)", () => { + test("an account with a label reads address and label, one without reads just the address", () => { + expect(accountName(gmail)).toBe("ana.personal@example.com (personal)"); + expect(accountName(imap)).toBe("bot@example.com"); + }); +}); + +describe("resolveAccounts (#219)", () => { + test("with no accounts connected it is not ok", () => { + const r = resolveAccounts([], undefined); + expect(r.ok).toBe(false); + expect(resolveAccounts([], "ana.personal@example.com").ok).toBe(false); + }); + + test("with nothing wanted it gives every account in order", () => { + for (const wanted of [undefined, "", 42, null, {}]) { + expect(ids(resolveAccounts(accounts, wanted))).toEqual(["a1", "a2", "a3"]); + } + }); + + test("an exact address wins in any case and with spaces around it", () => { + expect(ids(resolveAccounts(accounts, " ANA.PERSONAL@EXAMPLE.COM "))).toEqual(["a1"]); + expect(ids(resolveAccounts(accounts, "bot@example.com"))).toEqual(["a3"]); + }); + + test("a label matches without accents or case", () => { + expect(ids(resolveAccounts(accounts, "Trabajo"))).toEqual(["a2"]); + expect(ids(resolveAccounts(accounts, "trabájo"))).toEqual(["a2"]); + expect(ids(resolveAccounts(accounts, "PERSONAL"))).toEqual(["a1"]); + }); + + test("a provider matches by id and by service name", () => { + expect(ids(resolveAccounts(accounts, "gmail"))).toEqual(["a1"]); + expect(ids(resolveAccounts(accounts, "Gmail"))).toEqual(["a1"]); + expect(ids(resolveAccounts(accounts, "outlook"))).toEqual(["a2"]); + expect(ids(resolveAccounts(accounts, "Outlook"))).toEqual(["a2"]); + expect(ids(resolveAccounts(accounts, "imap"))).toEqual(["a3"]); + expect(ids(resolveAccounts(accounts, "Email (IMAP)"))).toEqual(["a3"]); + }); + + test("when a higher tier matches a lower tier is never mixed in", () => { + const labelled: MailAccount = { id: "a9", provider: "imap", address: "owner@example.com", label: "viajes", credentialId: "c9", createdAt: 9 }; + const inAddress: MailAccount = { id: "a8", provider: "gmail", address: "viajes.owner@example.com", credentialId: "c8", createdAt: 8 }; + expect(ids(resolveAccounts([inAddress, labelled], "viajes"))).toEqual(["a9"]); + // An exact address also wins over a label that is part of the same words. + expect(ids(resolveAccounts(accounts, "ana.trabajo@example.com"))).toEqual(["a2"]); + }); + + test("a part of an address or label matches when nothing exact does", () => { + expect(ids(resolveAccounts(accounts, "personal@"))).toEqual(["a1"]); + expect(ids(resolveAccounts(accounts, "trab"))).toEqual(["a2"]); + expect(ids(resolveAccounts(accounts, "bot@exam"))).toEqual(["a3"]); + }); + + test("no match is not ok, names the connected accounts and cuts what was wanted to 100 characters", () => { + const r = resolveAccounts(accounts, "no-existe@example.com"); + if (r.ok) throw new Error("expected a refusal"); + expect(r.modelText).toContain(accountName(gmail)); + expect(r.modelText).toContain(accountName(outlook)); + expect(r.modelText).toContain(accountName(imap)); + expect(r.modelText).toContain("no-existe@example.com"); + + const long = resolveAccounts(accounts, "x".repeat(150)); + if (long.ok) throw new Error("expected a refusal"); + expect(long.modelText).toContain(`"${"x".repeat(100)}"`); + expect(long.modelText).not.toContain("x".repeat(101)); + }); +}); + +describe("MemoryMailAccountStore (#219)", () => { + test("save replaces by id, get and list return copies, delete reports what it removed", async () => { + const store = new MemoryMailAccountStore(); + await store.save(gmail); + await store.save({ ...gmail, label: "nueva" }); + expect((await store.get("a1"))?.label).toBe("nueva"); + expect(await store.list()).toHaveLength(1); + + const got = (await store.get("a1"))!; + got.label = "changed"; + got.address = "changed@example.com"; + expect((await store.get("a1"))?.label).toBe("nueva"); + expect((await store.get("a1"))?.address).toBe(gmail.address); + + const listed = await store.list(); + listed[0]!.label = "changed again"; + expect((await store.get("a1"))?.label).toBe("nueva"); + + expect(await store.get("missing")).toBeUndefined(); + expect(await store.delete("a1")).toBe(true); + expect(await store.get("a1")).toBeUndefined(); + expect(await store.delete("a1")).toBe(false); + }); +}); From ffc5577d67c45fd77bfa21692f461402ccbee53a Mon Sep 17 00:00:00 2001 From: aditya9515 Date: Sun, 6 Dec 2026 11:48:36 +0530 Subject: [PATCH 04/16] test(mail): cover the date, base64, forward and batch helpers (#220) --- packages/mail/test/mime-helpers.test.ts | 107 ++++++++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 packages/mail/test/mime-helpers.test.ts diff --git a/packages/mail/test/mime-helpers.test.ts b/packages/mail/test/mime-helpers.test.ts new file mode 100644 index 0000000..213eefe --- /dev/null +++ b/packages/mail/test/mime-helpers.test.ts @@ -0,0 +1,107 @@ +// #220: the small mail helpers called by name: the RFC 5322 date, base64, the forward text and batched runs. Tests only. +import { describe, expect, test } from "vitest"; +import { inBatches } from "../src/http.ts"; +import { bytesToBase64, forwardText, mailDate } from "../src/mime.ts"; +import { base64ToBytes } from "../src/text.ts"; + +const wait = (ms: number) => new Promise((resolve) => { setTimeout(resolve, ms); }); + +describe("mailDate (#220)", () => { + test("a fixed instant gives the RFC 5322 date in UTC", () => { + expect(mailDate(Date.UTC(2026, 10, 14, 15, 0, 0))).toBe("Sat, 14 Nov 2026 15:00:00 +0000"); + }); + + test("a single digit day, hour, minute and second are zero padded", () => { + expect(mailDate(Date.UTC(2026, 0, 5, 4, 3, 2))).toBe("Mon, 05 Jan 2026 04:03:02 +0000"); + }); +}); + +describe("bytesToBase64 (#220)", () => { + test("inputs of 0, 1, 2 and 3 bytes give the right padding", () => { + expect(bytesToBase64(new Uint8Array([]))).toBe(""); + expect(bytesToBase64(new Uint8Array([0x66]))).toBe("Zg=="); + expect(bytesToBase64(new Uint8Array([0x66, 0x6f]))).toBe("Zm8="); + expect(bytesToBase64(new Uint8Array([0x66, 0x6f, 0x6f]))).toBe("Zm9v"); + }); + + test("with url the result uses minus and underscore and has no padding", () => { + const bytes = new Uint8Array([0xfb, 0xff, 0xfe]); + expect(bytesToBase64(bytes)).toBe("+//+"); + expect(bytesToBase64(bytes, true)).toBe("-__-"); + expect(bytesToBase64(new Uint8Array([0xfb]), true)).toBe("-w"); + expect(bytesToBase64(new Uint8Array([0xfb]), true)).not.toContain("="); + expect(bytesToBase64(bytes, true)).not.toContain("+"); + expect(bytesToBase64(bytes, true)).not.toContain("/"); + }); + + test("a round trip with base64ToBytes gives the same bytes back", () => { + for (const bytes of [new Uint8Array([]), new Uint8Array([0x66]), new Uint8Array([0x66, 0x6f, 0x6f]), new Uint8Array([0xfb, 0xff, 0xfe, 0x00, 0x80])]) { + expect(base64ToBytes(bytesToBase64(bytes))).toEqual(bytes); + expect(base64ToBytes(bytesToBase64(bytes, true))).toEqual(bytes); + } + }); +}); + +describe("forwardText (#220)", () => { + const original = { from: "Ana ", to: ["luis@example.com"], subject: "Hola", date: "Sat, 14 Nov 2026 15:00:00 +0000", text: "Nos vemos mañana." }; + + test("with a note the note comes first and then a blank line", () => { + const text = forwardText(" Mira esto. ", original); + expect(text.startsWith("Mira esto.\n\n---------- Forwarded message ----------")).toBe(true); + }); + + test("with a blank note there is no leading blank line", () => { + const text = forwardText(" ", original); + expect(text.startsWith("---------- Forwarded message ----------")).toBe(true); + expect(text.startsWith("\n")).toBe(false); + }); + + test("a To line appears only when to has addresses", () => { + expect(forwardText("", original)).toContain("\nTo: luis@example.com\n"); + expect(forwardText("", { ...original, to: [] })).not.toContain("\nTo:"); + }); + + test("a line break inside from or subject cannot start a new line", () => { + const text = forwardText("", { ...original, from: "Ana\nBcc: evil@example.com", subject: "Hola\r\nInjected: si" }); + const lines = text.split("\n"); + expect(lines.some((l) => l.startsWith("Bcc:"))).toBe(false); + expect(lines.some((l) => l.startsWith("Injected:"))).toBe(false); + expect(lines.find((l) => l.startsWith("From: "))).toBe("From: Ana Bcc: evil@example.com"); + expect(lines.find((l) => l.startsWith("Subject:"))).toBe("Subject: Hola Injected: si"); + }); +}); + +describe("inBatches (#220)", () => { + test("results keep the order of the input even when later tasks finish first", async () => { + const out = await inBatches([1, 2, 3, 4, 5], 5, async (n) => { + await wait((6 - n) * 10); + return n * 10; + }); + expect(out).toEqual([10, 20, 30, 40, 50]); + }); + + test("no more than the limit run at once", async () => { + let active = 0; + let peak = 0; + const out = await inBatches([1, 2, 3, 4, 5, 6, 7, 8], 2, async (n) => { + active++; + peak = Math.max(peak, active); + await wait(15); + active--; + return n; + }); + expect(out).toEqual([1, 2, 3, 4, 5, 6, 7, 8]); + expect(peak).toBeLessThanOrEqual(2); + expect(peak).toBe(2); + }); + + test("an empty list gives an empty list without calling the task", async () => { + let calls = 0; + const out = await inBatches([], 3, async (n: number) => { + calls++; + return n; + }); + expect(out).toEqual([]); + expect(calls).toBe(0); + }); +}); From 616a0b582dd62238a10a961d52d00147f5cea1f1 Mon Sep 17 00:00:00 2001 From: aditya9515 Date: Sun, 6 Dec 2026 11:50:23 +0530 Subject: [PATCH 05/16] test(mail): cover decodeCharset and headerParams by name (#221) --- packages/mail/test/mime-read.test.ts | 77 +++++++++++++++++++++++++++- 1 file changed, 76 insertions(+), 1 deletion(-) diff --git a/packages/mail/test/mime-read.test.ts b/packages/mail/test/mime-read.test.ts index e1b63a9..13eee17 100644 --- a/packages/mail/test/mime-read.test.ts +++ b/packages/mail/test/mime-read.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from "vitest"; import { binaryString } from "../src/mail-socket.ts"; import { utf8Encode } from "../src/mime.ts"; -import { decodeHeader, mailHeaderDate, quotedPrintable, readMessage } from "../src/mime-read.ts"; +import { decodeCharset, decodeHeader, headerParams, mailHeaderDate, quotedPrintable, readMessage } from "../src/mime-read.ts"; /** A message as IMAP hands it over: bytes, here as a binary string. */ const raw = (text: string) => binaryString(utf8Encode(text.replace(/\n/g, "\r\n"))); @@ -108,3 +108,78 @@ describe("reading a raw message (FR-MAIL-02, IMAP accounts)", () => { expect(binaryString(quotedPrintable("a=3Db=\r\nc = d=ZZ"))).toBe("a=bc = d=ZZ"); }); }); + +describe("decodeCharset (#221)", () => { + const enc = new TextEncoder(); + + it("with utf-8 in any case and with spaces it decodes UTF-8", () => { + for (const cs of ["utf-8", "UTF8", " UtF-8 "]) { + expect(decodeCharset(enc.encode("señal"), cs)).toBe("señal"); + expect(decodeCharset(enc.encode("acción"), cs)).toBe("acción"); + expect(decodeCharset(enc.encode("hola 🦀"), cs)).toBe("hola 🦀"); + } + }); + + it("with iso-8859-1, latin1 and windows-1252 the high bytes read as Windows-1252", () => { + const latin1 = Uint8Array.from([0x73, 0x65, 0xf1, 0x61, 0x6c]); + for (const cs of ["iso-8859-1", "latin1", "windows-1252"]) { + expect(decodeCharset(latin1, cs)).toBe("señal"); + expect(decodeCharset(Uint8Array.from([0x80]), cs)).toBe("€"); + expect(decodeCharset(Uint8Array.from([0x93, 0x94]), cs)).toBe("“”"); + } + }); + + it("with no charset, or one it does not know, valid UTF-8 reads as UTF-8 and anything else falls back to Windows-1252", () => { + const utf8 = enc.encode("acción 🦀"); + const latin1 = Uint8Array.from([0x73, 0x65, 0xf1, 0x61, 0x6c]); + for (const cs of [undefined, "x-unknown-charset"]) { + expect(decodeCharset(utf8, cs)).toBe("acción 🦀"); + const fallen = decodeCharset(latin1, cs); + expect(fallen).toBe("señal"); + expect(fallen).not.toContain("�"); + } + }); +}); + +describe("headerParams (#221)", () => { + it("splits the value from its parameters", () => { + const r = headerParams("text/plain; charset=UTF-8"); + expect(r.value).toBe("text/plain"); + expect(r.params.get("charset")).toBe("UTF-8"); + }); + + it("lowercases the value and the parameter names but keeps the case of parameter values", () => { + const r = headerParams("TEXT/Plain; CHARSET=UTF-8; Name=Notas.TXT"); + expect(r.value).toBe("text/plain"); + expect(r.params.get("charset")).toBe("UTF-8"); + expect(r.params.get("name")).toBe("Notas.TXT"); + }); + + it("a semicolon inside quotes does not split and a backslash escape keeps the next character", () => { + // Today the quotes around a quoted value are dropped; pin it here so changing it is a choice made on purpose. + const r = headerParams('text/plain; name="a;b"; other="x\\"y;z"'); + expect(r.params.get("name")).toBe("a;b"); + expect(r.params.get("other")).toBe('x"y;z'); + expect(r.params.size).toBe(2); + }); + + it("a repeated parameter keeps the first, a piece with no equals sign is skipped, and undefined gives nothing", () => { + const r = headerParams("text/plain; charset=UTF-8; foo; charset=iso-8859-1"); + expect(r.params.get("charset")).toBe("UTF-8"); + expect(r.params.has("foo")).toBe(false); + expect(r.params.size).toBe(1); + + const none = headerParams(undefined); + expect(none.value).toBe(""); + expect(none.params.size).toBe(0); + }); + + it("only the first 31 parameters are read", () => { + const many = `text/plain${Array.from({ length: 40 }, (_, i) => `; p${i}=v${i}`).join("")}`; + const r = headerParams(many); + expect(r.params.size).toBe(31); + expect(r.params.get("p0")).toBe("v0"); + expect(r.params.get("p30")).toBe("v30"); + expect(r.params.has("p31")).toBe(false); + }); +}); From 3800c4c1d74b3d8e984a0da03dda84bb09abe89c Mon Sep 17 00:00:00 2001 From: aditya9515 Date: Sun, 6 Dec 2026 11:52:39 +0530 Subject: [PATCH 06/16] test(night): cover the window and briefing on clock-change nights (#222) --- packages/night/test/settings.test.ts | 77 +++++++++++++++++++++++++++- 1 file changed, 76 insertions(+), 1 deletion(-) diff --git a/packages/night/test/settings.test.ts b/packages/night/test/settings.test.ts index e1e4e58..aaa721d 100644 --- a/packages/night/test/settings.test.ts +++ b/packages/night/test/settings.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from "vitest"; import { - blockers, briefingDate, briefingTime, DEFAULT_NIGHT_SETTINGS, inWindow, nextWindowStart, parseNightSettings, UNKNOWN_DEVICE, validateNightSettings, + blockers, briefingDate, briefingTime, DEFAULT_NIGHT_SETTINGS, inWindow, localMinutes, nextWindowStart, parseNightSettings, UNKNOWN_DEVICE, validateNightSettings, type DeviceState, type NightSettings, } from "../src/index.ts"; @@ -53,6 +53,81 @@ describe("night shift settings (HM-NIGHT-01, US-NIGHT-01)", () => { }); }); +describe("the window and the briefing on the nights the clock changes (#222)", () => { + const w = { start: "23:00", end: "05:00" }; + const NY = "America/New_York"; + const SANTIAGO = "America/Santiago"; + + test("New York in spring: inWindow at local 01:30 and 03:30 on March 8, and not at 05:30", () => { + // 2026-03-08T06:30Z is local 01:30 EST; the clock jumps 02:00 to 03:00 at 07:00Z. + expect(inWindow(Date.UTC(2026, 2, 8, 6, 30), NY, w)).toBe(true); + // 2026-03-08T07:30Z is local 03:30 EDT. + expect(inWindow(Date.UTC(2026, 2, 8, 7, 30), NY, w)).toBe(true); + // 2026-03-08T09:30Z is local 05:30 EDT, past the window end. + expect(inWindow(Date.UTC(2026, 2, 8, 9, 30), NY, w)).toBe(false); + }); + + test("New York in autumn: inWindow at local 01:30 and 03:30 on November 1, and not at 05:30", () => { + // 2026-11-01T05:30Z is local 01:30 EDT; the clock falls back 02:00 to 01:00 at 06:00Z. + expect(inWindow(Date.UTC(2026, 10, 1, 5, 30), NY, w)).toBe(true); + // 2026-11-01T06:30Z is local 01:30 EST, the repeated hour. + expect(inWindow(Date.UTC(2026, 10, 1, 6, 30), NY, w)).toBe(true); + // 2026-11-01T08:30Z is local 03:30 EST. + expect(inWindow(Date.UTC(2026, 10, 1, 8, 30), NY, w)).toBe(true); + // 2026-11-01T10:30Z is local 05:30 EST, past the window end. + expect(inWindow(Date.UTC(2026, 10, 1, 10, 30), NY, w)).toBe(false); + }); + + test("New York: briefingTime gives 07:00 local with each change morning offset", () => { + expect(briefingTime("2026-03-08", "07:00", NY)).toBe(Date.UTC(2026, 2, 8, 11, 0)); // local 07:00 EDT + expect(briefingTime("2026-11-01", "07:00", NY)).toBe(Date.UTC(2026, 10, 1, 12, 0)); // local 07:00 EST + }); + + test("New York: nextWindowStart from local noon on a change day gives 23:00 local that evening", () => { + // 2026-03-08T16:00Z is local noon EDT; that evening 23:00 local is 2026-03-09T03:00Z. + expect(nextWindowStart(Date.UTC(2026, 2, 8, 16, 0), NY, w)).toBe(Date.UTC(2026, 2, 9, 3, 0)); + // 2026-11-01T17:00Z is local noon EST; that evening 23:00 local is 2026-11-02T04:00Z. + expect(nextWindowStart(Date.UTC(2026, 10, 1, 17, 0), NY, w)).toBe(Date.UTC(2026, 10, 2, 4, 0)); + }); + + test("New York: localMinutes is 90 for both instants that read 01:30 on November 1", () => { + expect(localMinutes(Date.UTC(2026, 10, 1, 5, 30), NY)).toBe(90); // local 01:30 EDT + expect(localMinutes(Date.UTC(2026, 10, 1, 6, 30), NY)).toBe(90); // local 01:30 EST + }); + + test("Santiago in autumn: inWindow at local 23:30 and 02:00 on the night of April 4 to 5", () => { + // 2026-04-05T02:30Z is local 23:30 on April 4 (UTC-3); the clock goes back to 23:00 (UTC-4) at 03:00Z. + expect(inWindow(Date.UTC(2026, 3, 5, 2, 30), SANTIAGO, w)).toBe(true); + // 2026-04-05T03:30Z is local 23:30 on April 4 again (UTC-4), the repeated hour. + expect(inWindow(Date.UTC(2026, 3, 5, 3, 30), SANTIAGO, w)).toBe(true); + // 2026-04-05T06:00Z is local 02:00 on April 5 (UTC-4). + expect(inWindow(Date.UTC(2026, 3, 5, 6, 0), SANTIAGO, w)).toBe(true); + }); + + test("Santiago in spring: inWindow at local 23:30 and 02:00 on the night of September 5 to 6", () => { + // 2026-09-06T03:30Z is local 23:30 on September 5 (UTC-4); the clock jumps 00:00 to 01:00 at 04:00Z. + expect(inWindow(Date.UTC(2026, 8, 6, 3, 30), SANTIAGO, w)).toBe(true); + // 2026-09-06T05:00Z is local 02:00 on September 6 (UTC-3). + expect(inWindow(Date.UTC(2026, 8, 6, 5, 0), SANTIAGO, w)).toBe(true); + }); + + test("Santiago: briefingDate for an instant inside the window is the morning the window ends on", () => { + // 2026-04-05T03:30Z is local 23:30 on April 4; its night ends the morning of April 5. + expect(briefingDate(Date.UTC(2026, 3, 5, 3, 30), SANTIAGO, w)).toBe("2026-04-05"); + // 2026-04-05T06:00Z is local 02:00 on April 5. + expect(briefingDate(Date.UTC(2026, 3, 5, 6, 0), SANTIAGO, w)).toBe("2026-04-05"); + // 2026-09-06T03:30Z is local 23:30 on September 5; its night ends the morning of September 6. + expect(briefingDate(Date.UTC(2026, 8, 6, 3, 30), SANTIAGO, w)).toBe("2026-09-06"); + // 2026-09-06T05:00Z is local 02:00 on September 6. + expect(briefingDate(Date.UTC(2026, 8, 6, 5, 0), SANTIAGO, w)).toBe("2026-09-06"); + }); + + test("Santiago: briefingTime gives 07:00 local the next morning with that morning offset", () => { + expect(briefingTime("2026-04-05", "07:00", SANTIAGO)).toBe(Date.UTC(2026, 3, 5, 11, 0)); // local 07:00 (UTC-4) + expect(briefingTime("2026-09-06", "07:00", SANTIAGO)).toBe(Date.UTC(2026, 8, 6, 10, 0)); // local 07:00 (UTC-3) + }); +}); + describe("device guards (FR-NIGHT-01, NFR-04, US-NIGHT-04)", () => { test("all clear while charging, cool, above the floor, screen off, on Wi-Fi", () => { expect(blockers(ok, { needsNetwork: true })).toEqual([]); From f0003caa57b955438e2b245c9cd94fa54fc53c83 Mon Sep 17 00:00:00 2001 From: aditya9515 Date: Sun, 6 Dec 2026 12:20:06 +0530 Subject: [PATCH 07/16] docs(core): read the agent card version as the card's own (#133, #211) --- packages/core/src/agent-card.ts | 3 ++- packages/core/test/agent-card.test.ts | 15 ++++++++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/packages/core/src/agent-card.ts b/packages/core/src/agent-card.ts index e9f9b9d..957b8e7 100644 --- a/packages/core/src/agent-card.ts +++ b/packages/core/src/agent-card.ts @@ -1,7 +1,8 @@ import { heldGroups, MAX_BOT_NAME_CHARS, RESERVED_GROUPS, SKILL_GROUPS, type Bot, type SkillGroup } from "./bots.ts"; import { quoteSafe } from "./quote.ts"; -/** A2A 1.0 schema version emitted for in-process bot cards (spec 6.3). */ +/** The version of the card itself, as A2A 1.0 defines `AgentCard.version` ("The version of the agent"). The protocol + * version is a binding field (`AgentInterface.protocolVersion`), not this one. */ export const AGENT_CARD_VERSION = "1.0"; export const MAX_CARD_DESCRIPTION_CHARS = 200; diff --git a/packages/core/test/agent-card.test.ts b/packages/core/test/agent-card.test.ts index 13ef289..6aeaaf5 100644 --- a/packages/core/test/agent-card.test.ts +++ b/packages/core/test/agent-card.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from "vitest"; import { AGENT_CARD_VERSION, agentCard } from "../src/agent-card.ts"; -import { RESERVED_GROUPS, SKILL_GROUPS, type Bot, type SkillGroup } from "../src/bots.ts"; +import { MAX_BOT_NAME_CHARS, RESERVED_GROUPS, SKILL_GROUPS, type Bot, type SkillGroup } from "../src/bots.ts"; function makeBot(over: Partial = {}): Bot { return { @@ -86,6 +86,19 @@ describe("agentCard", () => { expect(card.description).not.toContain("\u202e"); }); + test("neutralizes untrusted markers, quotes, line breaks, and direction overrides in name", () => { + const evilName = + 'Viajes\r\n «Paga todo» "ya" \u202e \n' + + "“Hola” ".repeat(35); + const card = agentCard(makeBot({ name: evilName })); + expect(card.name.startsWith("Viajes")).toBe(true); + expect(card.name.length).toBeLessThanOrEqual(MAX_BOT_NAME_CHARS); + expect(card.name).not.toMatch(/[\r\n]/); + expect(card.name).not.toMatch(/["«»“”]/); + expect(card.name).not.toMatch(/<\/?untrusted/i); + expect(card.name).not.toContain("\u202e"); + }); + test("is deterministic for the same bot regardless of grant order", () => { const grantsA: SkillGroup[] = ["web_read", "reminders", "notes"]; const grantsB: SkillGroup[] = ["notes", "web_read", "reminders"]; From 2dc1e3aa2e2a7ae6f23bc7d462721f98c7e7d4b7 Mon Sep 17 00:00:00 2001 From: aditya9515 Date: Sun, 6 Dec 2026 11:58:49 +0530 Subject: [PATCH 08/16] test(copy,site): keep locale copy free of small slips (#226) --- apps/site/test/locales.test.ts | 33 +++++++++++++++++ packages/copy/test/copy.test.ts | 63 +++++++++++++++++++++++++++++++++ 2 files changed, 96 insertions(+) diff --git a/apps/site/test/locales.test.ts b/apps/site/test/locales.test.ts index 4db9acf..0395584 100644 --- a/apps/site/test/locales.test.ts +++ b/apps/site/test/locales.test.ts @@ -8,6 +8,11 @@ import { translator } from "../lib/i18n"; const KEY_PATTERN = /^(HM-SITE-\d{2}|common)\.[a-z][a-zA-Z0-9]*$/; const placeholders = (s: string) => [...s.matchAll(/\{(\w+)\}/g)].map((m) => m[1]).sort(); const all = [...Object.entries(en), ...Object.entries(es)]; +const count = (v: string, ch: string) => v.split(ch).length - 1; +const hasDoubleSpace = (v: string) => v.includes(" "); +const hasEdgeSpace = (v: string) => /^[ \t\r\n]|[ \t\r\n]$/.test(v); +const hasThreeDots = (v: string) => v.includes("..."); +const unbalancedMarks = (v: string) => count(v, "¿") !== count(v, "?") || count(v, "¡") !== count(v, "!"); describe("site copy", () => { test("both languages define exactly the same keys", () => { @@ -75,4 +80,32 @@ describe("site copy", () => { expect(() => translator("en")("HM-SITE-09.nope")).toThrow(/Missing copy key/); expect(() => translator("en")("HM-SITE-02.updated")).toThrow(/needs \{date\}/); }); + + test("the copy hygiene checks flag made up slips", () => { + expect(hasDoubleSpace("hola mundo")).toBe(true); + expect(hasDoubleSpace("{count} {unit}")).toBe(false); + expect(hasEdgeSpace(" hola")).toBe(true); + expect(hasEdgeSpace("hola\n")).toBe(true); + expect(hasEdgeSpace("hola\nmundo")).toBe(false); + expect(hasThreeDots("espera...")).toBe(true); + expect(hasThreeDots("espera…")).toBe(false); + expect(unbalancedMarks("¿Cómo estás?")).toBe(false); + expect(unbalancedMarks("Cómo estás?")).toBe(true); + expect(unbalancedMarks("Hola!")).toBe(true); + }); + + test("no value in either language of the site has two spaces in a row, edge space or three dots", () => { + for (const [k, v] of all) { + expect(hasDoubleSpace(v), k).toBe(false); + expect(hasEdgeSpace(v), k).toBe(false); + expect(hasThreeDots(v), k).toBe(false); + } + }); + + test("in the site Spanish the opening marks match the closing ones in every value", () => { + for (const [k, v] of Object.entries(es)) { + expect(count(v, "¿"), k).toBe(count(v, "?")); + expect(count(v, "¡"), k).toBe(count(v, "!")); + } + }); }); diff --git a/packages/copy/test/copy.test.ts b/packages/copy/test/copy.test.ts index 7303fdf..0e02c15 100644 --- a/packages/copy/test/copy.test.ts +++ b/packages/copy/test/copy.test.ts @@ -177,3 +177,66 @@ describe("the biometric's name by platform (issue 128)", () => { } }); }); + +describe("copy hygiene", () => { + const count = (v: string, ch: string) => v.split(ch).length - 1; + const hasDoubleSpace = (v: string) => v.includes(" "); + const hasEdgeSpace = (v: string) => /^[ \t\r\n]|[ \t\r\n]$/.test(v); + const hasThreeDots = (v: string) => v.includes("..."); + const unbalancedMarks = (v: string) => count(v, "¿") !== count(v, "?") || count(v, "¡") !== count(v, "!"); + const all = [...Object.entries(en), ...Object.entries(es)]; + + test("the double space check flags made up slips and leaves single spaces alone", () => { + expect(hasDoubleSpace("hola mundo")).toBe(true); + expect(hasDoubleSpace("hola mundo")).toBe(false); + // The placeholders are not text: single spaces around them are fine. + expect(hasDoubleSpace("{count} {unit}")).toBe(false); + expect(hasDoubleSpace("hola\nmundo")).toBe(false); + }); + + test("the edge space check flags a space, tab or line break at either end only", () => { + expect(hasEdgeSpace(" hola")).toBe(true); + expect(hasEdgeSpace("hola ")).toBe(true); + expect(hasEdgeSpace("\thola")).toBe(true); + expect(hasEdgeSpace("hola\n")).toBe(true); + // A line break inside a value is fine; only the start and the end are checked. + expect(hasEdgeSpace("hola\nmundo")).toBe(false); + expect(hasEdgeSpace("hola mundo")).toBe(false); + }); + + test("the three dots check flags three dots and leaves the ellipsis character alone", () => { + expect(hasThreeDots("espera...")).toBe(true); + expect(hasThreeDots("espera…")).toBe(false); + expect(hasThreeDots("uno. dos.")).toBe(false); + }); + + test("the Spanish marks check flags a question or exclamation with no opening mark", () => { + expect(unbalancedMarks("¿Cómo estás?")).toBe(false); + expect(unbalancedMarks("¡Hola!")).toBe(false); + expect(unbalancedMarks("¿Uno? ¡Dos!")).toBe(false); + expect(unbalancedMarks("sin signos")).toBe(false); + expect(unbalancedMarks("Cómo estás?")).toBe(true); + expect(unbalancedMarks("¿Cómo estás")).toBe(true); + expect(unbalancedMarks("Hola!")).toBe(true); + expect(unbalancedMarks("¡Hola")).toBe(true); + }); + + test("no value in either locale has two spaces in a row", () => { + for (const [k, v] of all) expect(hasDoubleSpace(v), k).toBe(false); + }); + + test("no value in either locale starts or ends with a space, tab or line break", () => { + for (const [k, v] of all) expect(hasEdgeSpace(v), k).toBe(false); + }); + + test("no value in either locale has three dots", () => { + for (const [k, v] of all) expect(hasThreeDots(v), k).toBe(false); + }); + + test("in es-419 the opening marks match the closing ones in every value", () => { + for (const [k, v] of Object.entries(es)) { + expect(count(v, "¿"), k).toBe(count(v, "?")); + expect(count(v, "¡"), k).toBe(count(v, "!")); + } + }); +}); From 8d6ff593934a44fb55859f518c5e6c4014b90138 Mon Sep 17 00:00:00 2001 From: aditya9515 Date: Sun, 6 Dec 2026 12:18:03 +0530 Subject: [PATCH 09/16] docs(copy): explain how copy is added and checked (#225) --- CONTRIBUTING.md | 3 +- packages/copy/README.md | 68 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+), 1 deletion(-) create mode 100644 packages/copy/README.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 271400e..78896db 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -10,7 +10,8 @@ The rules live in [AGENTS.md](AGENTS.md). Read its non-negotiables before your f - Report a bug, with steps to reproduce and no personal data. - Propose a feature. Read [VISION.md](VISION.md) first. - Run Hermit on your phone and send device data: [docs/devices.md](docs/devices.md) explains how. -- Improve the docs, or the Spanish and English copy. +- Improve the docs, or the Spanish and English copy. [How copy works](packages/copy/README.md) explains how to add a + string. - Review open pull requests. Reading and running someone's change helps too. ## Set up diff --git a/packages/copy/README.md b/packages/copy/README.md new file mode 100644 index 0000000..03d9328 --- /dev/null +++ b/packages/copy/README.md @@ -0,0 +1,68 @@ +# Copy in Hermit + +Every string a person sees in the app is a key in this package: [`locales/en.json`](locales/en.json) and +[`locales/es-419.json`](locales/es-419.json), read through the translator in [`src/index.ts`](src/index.ts). Spanish +and English are first class: a string exists in both or it does not exist. + +## Naming a key + +A key is `HM-XXX-NN.element` for one screen, or `common.*` for a string every screen shares, as `KEY_PATTERN` in +[`src/index.ts`](src/index.ts) requires. For example `HM-APPR-01.approve` is one screen's string and `common.retry` +is shared: + +```json +"HM-APPR-01.approve": "Approve with {biometric}", +"common.retry": "Try again" +``` + +## Add a string + +1. Name it as above. +2. Add the same key to both locale files, with the same `{placeholders}` in both. A test holds the two files to + exactly the same keys and placeholders. +3. Use it with `t` from [`apps/mobile/src/i18n.ts`](../../apps/mobile/src/i18n.ts), passing a value for every + placeholder: `t("common.retry")`, or `t("HM-APPR-01.approve")` where the phone's biometric name fills + `{biometric}` by default. + +## When a key or a value is missing + +The translator throws a `CopyError` instead of returning an empty string: `Missing copy key ...` for a key that is +not there, and `Copy key ... needs {name}.` for a placeholder the call did not fill. A forgotten string fails the +tests instead of shipping blank. + +## Counts + +`tCount()` in `apps/mobile/src/i18n.ts` says a count right: with a count of 1 it uses the `key.one` form when the +copy has one, and `key` otherwise. The count fills `{count}` either way. One pair that exists today: + +```json +"HM-SET-02.count": "{count} times", +"HM-SET-02.count.one": "{count} time" +``` + +In Spanish the same pair is `"{count} veces"` and `"{count} vez"`. + +## House style + +The tests in [`test/copy.test.ts`](test/copy.test.ts) hold the copy to it: + +- no em or en dashes in either locale; +- Latin American Spanish (es-419), and tú, never vos: "Tienes un recordatorio:" (`HM-CHAT-01.reminders.one`), not a + voseo form. The tú test names the key it flags. +- any Spanish the phone reports resolves to es-419, and everything else to English (`resolveLocale`). + +## Tests + +```sh +pnpm --filter @hermit/copy test +pnpm --filter @hermit/mobile test +``` + +The first runs this package's tests (key shape, key and placeholder parity, house style, the translator). The +second includes the test in `apps/mobile/src/copy-keys.test.ts` that every literal key named in the app and package +source exists in both locales. + +## The website + +The website has its own locale files in [`apps/site/locales`](../../apps/site/locales), with the same rules: the +same keys in both, the same placeholders, no em or en dashes, and tú in Spanish. It does not read this package. From e293cae975e615c1a01d38c0222b9cc3a55ca78f Mon Sep 17 00:00:00 2001 From: aditya9515 Date: Sun, 6 Dec 2026 12:08:00 +0530 Subject: [PATCH 10/16] test(scripts): check relative links and anchors in the docs (#228) --- scripts/docs-links.mjs | 61 +++++++++++++++++++++++ scripts/docs-links.test.mjs | 97 +++++++++++++++++++++++++++++++++++++ 2 files changed, 158 insertions(+) create mode 100644 scripts/docs-links.mjs create mode 100644 scripts/docs-links.test.mjs diff --git a/scripts/docs-links.mjs b/scripts/docs-links.mjs new file mode 100644 index 0000000..379ef7b --- /dev/null +++ b/scripts/docs-links.mjs @@ -0,0 +1,61 @@ +// The small Markdown reading the docs link test needs: the targets of inline links, and GitHub's heading anchors. +// Pure and offline: nothing here fetches or follows a link, and the parser only covers what the docs use. + +/** The GitHub anchor for a heading: lower case, punctuation dropped, spaces as `-`. Accents are kept. */ +export function slug(heading) { + return heading.trim().toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu, "").replace(/\s/g, "-"); +} + +/** One line with its inline code spans taken out, so a link written as an example is not read as a link. */ +function withoutInlineCode(line) { + let out = ""; + let i = 0; + while (i < line.length) { + if (line[i] !== "`") { + out += line[i]; + i++; + continue; + } + let j = i; + while (line[j] === "`") j++; + const ticks = line.slice(i, j); + const end = line.indexOf(ticks, j); + if (end < 0) { + out += line.slice(i); + break; + } + i = end + ticks.length; + } + return out; +} + +/** The target inside a link's parentheses: an `` target as it stands, otherwise the first word (a title may follow). */ +function targetOf(inner) { + const t = inner.trim(); + if (!t) return ""; + if (t.startsWith("<")) { + const end = t.indexOf(">"); + return end < 0 ? t.slice(1) : t.slice(1, end); + } + return t.split(/\s+/)[0] ?? ""; +} + +/** The targets of the inline links `[text](target)` in a Markdown text, skipping fenced code blocks and inline code. + * External targets (`https:`, `mailto:` and the like) are returned too, so the caller can skip them. */ +export function linksIn(markdown) { + const targets = []; + let fence = null; + for (const rawLine of markdown.split("\n")) { + const line = rawLine.replace(/\r$/, ""); + const fenceMatch = line.match(/^\s{0,3}(`{3,}|~{3,})/); + if (fenceMatch) { + const marker = fenceMatch[1]; + if (!fence) fence = marker; + else if (marker[0] === fence[0] && marker.length >= fence.length) fence = null; + continue; + } + if (fence) continue; + for (const m of withoutInlineCode(line).matchAll(/\[[^\]]*\]\(([^)]*)\)/g)) targets.push(targetOf(m[1])); + } + return targets; +} diff --git a/scripts/docs-links.test.mjs b/scripts/docs-links.test.mjs new file mode 100644 index 0000000..cc5e8ce --- /dev/null +++ b/scripts/docs-links.test.mjs @@ -0,0 +1,97 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { existsSync, readFileSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { linksIn, slug } from "./docs-links.mjs"; + +test("linksIn returns the targets of inline links in order", () => { + const md = "See [the guide](docs/guide.md) and [a section](docs/guide.md#setup), or the [site](https://example.com)."; + assert.deepEqual(linksIn(md), ["docs/guide.md", "docs/guide.md#setup", "https://example.com"]); +}); + +test("linksIn returns https and mailto links so the caller can skip them", () => { + assert.deepEqual(linksIn("[site](https://example.com) and [mail](mailto:ana@example.com)"), ["https://example.com", "mailto:ana@example.com"]); +}); + +test("linksIn skips a link inside a fenced code block", () => { + const md = ["[real](real.md)", "```", "[fake](missing.md)", "```", "[also real](also-real.md)"].join("\n"); + assert.deepEqual(linksIn(md), ["real.md", "also-real.md"]); +}); + +test("linksIn skips a link inside inline code", () => { + assert.deepEqual(linksIn("Run `[fake](missing.md)` then see [real](real.md)."), ["real.md"]); +}); + +test("linksIn takes the target before a title", () => { + assert.deepEqual(linksIn('[guide](docs/guide.md "The guide")'), ["docs/guide.md"]); +}); + +test("slug makes the GitHub anchor for a heading", () => { + assert.equal(slug("How to propose work"), "how-to-propose-work"); + assert.equal(slug("What's new in Wave 1: agent core"), "whats-new-in-wave-1-agent-core"); +}); + +test("slug keeps accents", () => { + assert.equal(slug("Qué hace"), "qué-hace"); +}); + +const root = join(dirname(fileURLToPath(import.meta.url)), ".."); + +/** The anchors a Markdown text actually has: its headings outside code fences, slugged as GitHub slugs them, with the + * repeats suffixed -1, -2 and so on, as GitHub does. */ +function headingSlugs(text) { + const slugs = new Set(); + const seen = new Map(); + let fence = null; + for (const rawLine of text.split("\n")) { + const line = rawLine.replace(/\r$/, ""); + const fenceMatch = line.match(/^\s{0,3}(`{3,}|~{3,})/); + if (fenceMatch) { + const marker = fenceMatch[1]; + if (!fence) fence = marker; + else if (marker[0] === fence[0] && marker.length >= fence.length) fence = null; + continue; + } + if (fence) continue; + const heading = line.match(/^#{1,6}\s+(.*?)\s*#*\s*$/); + if (!heading) continue; + const plain = heading[1] + .replace(/\[([^\]]*)\]\([^)]*\)/g, "$1") + .replace(/<[^>]+>/g, "") + .replace(/[`*~]/g, ""); + const base = slug(plain); + const count = seen.get(base) ?? 0; + seen.set(base, count + 1); + slugs.add(count === 0 ? base : `${base}-${count}`); + } + return slugs; +} + +test("every relative link in the tracked Markdown points at a file that exists, and its anchor at a heading", () => { + const files = execFileSync("git", ["ls-files", "*.md"], { cwd: root, encoding: "utf8" }).trim().split(/\r?\n/).filter(Boolean); + assert.ok(files.length > 0, "git ls-files found no Markdown files"); + const cache = new Map(); + const anchorsOf = (abs) => { + if (!cache.has(abs)) cache.set(abs, headingSlugs(readFileSync(abs, "utf8"))); + return cache.get(abs); + }; + const decode = (v) => { + try { return decodeURIComponent(v); } catch { return v; } + }; + for (const file of files) { + const text = readFileSync(join(root, file), "utf8"); + for (const target of linksIn(text)) { + if (/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(target)) continue; + const hash = target.indexOf("#"); + const pathPart = hash >= 0 ? target.slice(0, hash) : target; + const anchor = hash >= 0 ? target.slice(hash + 1) : ""; + const abs = pathPart ? resolve(join(root, dirname(file)), decode(pathPart)) : join(root, file); + assert.ok(existsSync(abs), `${file}: link "${target}" does not point at an existing file`); + if (anchor && abs.toLowerCase().endsWith(".md")) { + assert.ok(anchorsOf(abs).has(decode(anchor)), `${file}: link "${target}" points at an anchor no heading in ${pathPart || file} has`); + } + } + } +}); From af17cf254fde4ca74aeb07788b574fbd66ae1960 Mon Sep 17 00:00:00 2001 From: aditya9515 Date: Sun, 6 Dec 2026 12:10:32 +0530 Subject: [PATCH 11/16] test(site): check the download page's release fields (#229) --- apps/site/test/release.test.ts | 130 +++++++++++++++++++++++++++++++++ 1 file changed, 130 insertions(+) create mode 100644 apps/site/test/release.test.ts diff --git a/apps/site/test/release.test.ts b/apps/site/test/release.test.ts new file mode 100644 index 0000000..eda6da9 --- /dev/null +++ b/apps/site/test/release.test.ts @@ -0,0 +1,130 @@ +// HM-SITE-03: the download page's release fields, checked before anyone copies a hash by hand. People check the APK +// against the SHA-256 on this page, so a short hash or a link to another tag must not ship. Tests only. +import { describe, expect, test } from "vitest"; +import { readFileSync } from "node:fs"; +import { RELEASE, type Release } from "../lib/release.ts"; +import { REPO_URL } from "../lib/site-config.mjs"; + +const slug = (heading: string) => heading.trim().toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu, "").replace(/\s/g, "-"); + +/** The anchors docs/devices.md actually has: its headings outside code fences, slugged as GitHub slugs them. */ +function headingAnchors(markdown: string): Set { + const anchors = new Set(); + const seen = new Map(); + let fence: string | null = null; + for (const rawLine of markdown.split("\n")) { + const line = rawLine.replace(/\r$/, ""); + const fenceMatch = line.match(/^\s{0,3}(`{3,}|~{3,})/); + if (fenceMatch) { + const marker = fenceMatch[1]!; + if (!fence) fence = marker; + else if (marker[0] === fence[0] && marker.length >= fence.length) fence = null; + continue; + } + if (fence) continue; + const heading = line.match(/^#{1,6}\s+(.*?)\s*#*\s*$/); + if (!heading) continue; + const plain = heading[1]!.replace(/\[([^\]]*)\]\([^)]*\)/g, "$1").replace(/<[^>]+>/g, "").replace(/[`*~]/g, ""); + const base = slug(plain); + const count = seen.get(base) ?? 0; + seen.set(base, count + 1); + anchors.add(count === 0 ? base : `${base}-${count}`); + } + return anchors; +} + +const devicesAnchors = headingAnchors(readFileSync(new URL("../../../docs/devices.md", import.meta.url), "utf8")); + +const HEX64 = /^[0-9a-f]{64}$/; + +/** What is wrong with a published release, field by field. An unpublished one is placeholders, and is fine as it stands. */ +function releaseProblems(r: Release, anchors: ReadonlySet): string[] { + if (!r.published) return []; + const problems: string[] = []; + if (!HEX64.test(r.sha256 ?? "")) problems.push(`sha256 should be 64 lowercase hex characters, got ${JSON.stringify(r.sha256)}`); + if (!HEX64.test(r.certSha256 ?? "")) problems.push(`certSha256 should be 64 lowercase hex characters, got ${JSON.stringify(r.certSha256)}`); + const version = /^hermit-(.+)\.apk$/.exec(r.file)?.[1]; + if (!version) problems.push(`file should look like hermit-.apk, got ${JSON.stringify(r.file)}`); + const tag = version ? `v${version}` : undefined; + + const downloadPrefix = `${REPO_URL}/releases/download/`; + if (!r.url) { + problems.push("url is missing: a published release needs the link to its APK"); + } else { + if (!r.url.startsWith(downloadPrefix)) problems.push(`url should start with ${downloadPrefix}, got ${JSON.stringify(r.url)}`); + else if (tag && r.url.slice(downloadPrefix.length).split("/")[0] !== tag) problems.push(`url is for tag ${JSON.stringify(r.url.slice(downloadPrefix.length).split("/")[0])} but file ${JSON.stringify(r.file)} is version ${JSON.stringify(version)}`); + if (!r.url.endsWith(`/${r.file}`)) problems.push(`url should end with /${r.file}, got ${JSON.stringify(r.url)}`); + } + + const recipePrefix = tag ? `${REPO_URL}/blob/${tag}/docs/devices.md#` : undefined; + if (!r.recipeUrl) { + problems.push("recipeUrl is missing: a published release needs the link to its rebuild recipe"); + } else if (recipePrefix && !r.recipeUrl.startsWith(recipePrefix)) { + problems.push(`recipeUrl should point at docs/devices.md at tag ${tag}, got ${JSON.stringify(r.recipeUrl)}`); + } else if (recipePrefix && !anchors.has(r.recipeUrl.slice(recipePrefix.length))) { + problems.push(`recipeUrl anchor ${JSON.stringify(r.recipeUrl.slice(recipePrefix.length))} matches no heading in docs/devices.md`); + } + return problems; +} + +const good: Release = { + published: true, + file: "hermit-1.2.3.apk", + url: `${REPO_URL}/releases/download/v1.2.3/hermit-1.2.3.apk`, + sha256: "a".repeat(64), + certSha256: "b".repeat(64), + recipeUrl: `${REPO_URL}/blob/v1.2.3/docs/devices.md#or-build-it-yourself`, +}; + +describe("the download page's release (#229)", () => { + test("today's published release has no problems", () => { + expect(RELEASE.published).toBe(true); + expect(releaseProblems(RELEASE, devicesAnchors)).toEqual([]); + }); + + test("an unpublished release is placeholders, and checks out as it stands", () => { + const placeholder: Release = { published: false, file: "", url: null, sha256: null, certSha256: null, recipeUrl: null }; + expect(releaseProblems(placeholder, new Set())).toEqual([]); + }); + + test("a good made-up release gives no problems", () => { + expect(releaseProblems(good, devicesAnchors)).toEqual([]); + }); + + test("a short hash gives one problem naming sha256", () => { + const problems = releaseProblems({ ...good, sha256: "a".repeat(63) }, devicesAnchors); + expect(problems).toHaveLength(1); + expect(problems[0]).toContain("sha256"); + }); + + test("an upper case hash gives one problem naming the field", () => { + const upper = releaseProblems({ ...good, sha256: "A".repeat(64) }, devicesAnchors); + expect(upper).toHaveLength(1); + expect(upper[0]).toContain("sha256"); + const upperCert = releaseProblems({ ...good, certSha256: "B".repeat(64) }, devicesAnchors); + expect(upperCert).toHaveLength(1); + expect(upperCert[0]).toContain("certSha256"); + }); + + test("a link to another tag gives one problem naming url and the tag", () => { + const problems = releaseProblems({ ...good, url: `${REPO_URL}/releases/download/v9.9.9/hermit-1.2.3.apk` }, devicesAnchors); + expect(problems).toHaveLength(1); + expect(problems[0]).toContain("url"); + expect(problems[0]).toContain("v9.9.9"); + }); + + test("a file name that does not match gives one problem naming file", () => { + const problems = releaseProblems({ ...good, file: "other-1.2.3.apk", url: `${REPO_URL}/releases/download/v1.2.3/other-1.2.3.apk` }, devicesAnchors); + expect(problems).toHaveLength(1); + expect(problems[0]).toContain("file"); + }); + + test("a recipe link to another tag, or at a missing heading, gives one problem", () => { + const otherTag = releaseProblems({ ...good, recipeUrl: `${REPO_URL}/blob/v9.9.9/docs/devices.md#or-build-it-yourself` }, devicesAnchors); + expect(otherTag).toHaveLength(1); + expect(otherTag[0]).toContain("recipeUrl"); + const missingAnchor = releaseProblems({ ...good, recipeUrl: `${REPO_URL}/blob/v1.2.3/docs/devices.md#no-such-heading` }, devicesAnchors); + expect(missingAnchor).toHaveLength(1); + expect(missingAnchor[0]).toContain("recipeUrl"); + }); +}); From 43c04fbd43a6f8126c58f5f88063fdf216a3cc88 Mon Sep 17 00:00:00 2001 From: aditya9515 Date: Sun, 6 Dec 2026 12:37:36 +0530 Subject: [PATCH 12/16] test(site): hold the release check either way, published or not (#229) --- apps/site/test/release.test.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/apps/site/test/release.test.ts b/apps/site/test/release.test.ts index eda6da9..5f8e388 100644 --- a/apps/site/test/release.test.ts +++ b/apps/site/test/release.test.ts @@ -77,8 +77,7 @@ const good: Release = { }; describe("the download page's release (#229)", () => { - test("today's published release has no problems", () => { - expect(RELEASE.published).toBe(true); + test("today's release has no problems, published or not", () => { expect(releaseProblems(RELEASE, devicesAnchors)).toEqual([]); }); From 6f4cd9dbcf5a8d25c3cc1db25281a4d33253dc1d Mon Sep 17 00:00:00 2001 From: aditya9515 Date: Sun, 6 Dec 2026 12:14:30 +0530 Subject: [PATCH 13/16] docs(site): describe the website, its commands and its checks (#224) --- apps/site/README.md | 77 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 apps/site/README.md diff --git a/apps/site/README.md b/apps/site/README.md new file mode 100644 index 0000000..5ad54fb --- /dev/null +++ b/apps/site/README.md @@ -0,0 +1,77 @@ +# Hermit website + +The website at [joinhermit.com](https://joinhermit.com) lives in `apps/site`. It is a +static export: no server functions, cookies, analytics or third-party scripts. English +pages are under `/en/` and Spanish pages under `/es/`, each with a privacy page and a +download page. The root address is a language chooser; on Vercel the browser's language +decides before the chooser is reached. + +`next build` writes plain files to `out/`, and no page needs JavaScript. +[`scripts/finalize.mjs`](scripts/finalize.mjs), run at the end of the build, removes every +script tag, preload and JavaScript or payload file Next leaves behind. The only scripts +that stay are the two inline theme scripts in [`lib/theme.mjs`](lib/theme.mjs), which set +the theme before the first paint and run its switch. The content security policy in +[`vercel.json`](vercel.json) allows exactly those two, by hash, and nothing else. + +## Commands + +From the repository root, after `pnpm install`: + +```sh +pnpm --filter @hermit/site build +pnpm --filter @hermit/site check +pnpm --filter @hermit/site test +pnpm --filter @hermit/site typecheck +``` + +- `build` copies the brand files, builds the static export into `apps/site/out` and + strips Next's scripts from it. +- `check` checks the built `out/` (run `build` first): the pages and styles load nothing + from elsewhere, no JavaScript is left but the two theme scripts, the partners line is as + [`lib/site-config.mjs`](lib/site-config.mjs) says, the brand files and store badges are + unmodified, and a published release has every field filled. +- `test` runs the Vitest tests: copy keys and placeholders, the release fields, badges, + theme and contrast, and the checks above on made-up pages. +- `typecheck` runs TypeScript over the site's source and tests. + +These commands are written for macOS and Linux today. The build script sets its telemetry +variable the POSIX way, and `check` assumes forward slashes in file paths, so neither +behaves on Windows yet. + +## Look at it + +There is no dev script. Serve the built files with any static file server, for example +Python's, from the repository root: + +```sh +python3 -m http.server 8000 --directory apps/site/out +``` + +Then open and pick a language, or go straight to + or . + +## Words + +Every string a person sees is a key in [`locales/en.json`](locales/en.json) and +[`locales/es-419.json`](locales/es-419.json), with the same keys and the same +`{placeholders}` in both. The rules are the app copy's rules, from `packages/copy`: plain +words, short sentences, no em or en dashes, and Latin American Spanish that uses tú. +[`test/locales.test.ts`](test/locales.test.ts) holds the keys, placeholders and dashes to +that. + +## Brand files + +[`docs/brand`](../../docs/brand) is the source of truth, under the logo lock: the drawing +is served as it is, never redrawn or recolored. The build first runs +[`scripts/copy-brand.mjs`](scripts/copy-brand.mjs), which copies the files listed in +[`lib/brand.mjs`](lib/brand.mjs) from there into `public/brand`, byte for byte. `check` +fails if a served copy differs from its source. + +## The download page + +The download page reads [`lib/release.ts`](lib/release.ts): the APK's file name and link, +its SHA-256, the signing certificate's SHA-256 and the rebuild recipe's link. A maintainer +updates it for each preview release, following the tag and release steps in +[CONTRIBUTING.md, For maintainers](../../CONTRIBUTING.md#for-maintainers). While +`published` is false every field is a placeholder and the page shows its pending notice +instead. From b6510d4ddcfb968d481c6853d35a3ae87e6fcf23 Mon Sep 17 00:00:00 2001 From: aditya9515 Date: Sun, 6 Dec 2026 12:03:19 +0530 Subject: [PATCH 14/16] fix(preview): stop early with no build or no matching shot (#227) --- apps/mobile/preview/package.json | 2 +- apps/mobile/preview/pick.mjs | 16 ++++++ apps/mobile/preview/pick.test.mjs | 49 +++++++++++++++++ apps/mobile/preview/shoot.mjs | 87 ++++++++++++++++--------------- 4 files changed, 112 insertions(+), 42 deletions(-) create mode 100644 apps/mobile/preview/pick.mjs create mode 100644 apps/mobile/preview/pick.test.mjs diff --git a/apps/mobile/preview/package.json b/apps/mobile/preview/package.json index 30ef2fb..c8f4f3f 100644 --- a/apps/mobile/preview/package.json +++ b/apps/mobile/preview/package.json @@ -7,7 +7,7 @@ "type": "module", "scripts": { "build": "node build.mjs", - "test": "node --test device-lab.test.mjs browser.test.mjs", + "test": "node --test device-lab.test.mjs browser.test.mjs pick.test.mjs", "shoot": "node shoot.mjs", "compress": "python3 -c \"import glob; from PIL import Image; [Image.open(f).convert('RGB').quantize(colors=256, dither=Image.Dither.NONE).save(f, optimize=True) for f in glob.glob('out/screens/*.png')]\"", "clips": "node clips.mjs", diff --git a/apps/mobile/preview/pick.mjs b/apps/mobile/preview/pick.mjs new file mode 100644 index 0000000..8c3f2c5 --- /dev/null +++ b/apps/mobile/preview/pick.mjs @@ -0,0 +1,16 @@ +// Dev-only and pure: the shots one run of shoot.mjs takes, so the filter can be checked without a browser. +// A shot is taken for each of its themes and languages, as a file named `${shot.file}-${theme}-${lang}.png`; +// a filter keeps only the files that contain it, as the loop in shoot.mjs always did. +export function pickShots(shots, filter) { + const picked = []; + for (const shot of shots) { + for (const theme of shot.themes) { + for (const lang of shot.langs) { + const file = `${shot.file}-${theme}-${lang}.png`; + if (filter && !file.includes(filter)) continue; + picked.push({ shot, theme, lang, file }); + } + } + } + return picked; +} diff --git a/apps/mobile/preview/pick.test.mjs b/apps/mobile/preview/pick.test.mjs new file mode 100644 index 0000000..01eaed9 --- /dev/null +++ b/apps/mobile/preview/pick.test.mjs @@ -0,0 +1,49 @@ +// #227: which shots a run takes. Pure picking, so the filter can be checked without a browser. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { pickShots } from "./pick.mjs"; + +const shots = [ + { file: "about", themes: ["light", "dark"], langs: ["es-419", "en"] }, + { file: "wallet-home", themes: ["light"], langs: ["es-419"] }, + { file: "bot-chat", themes: ["dark"], langs: ["en", "es-419"] }, +]; + +test("no filter keeps every theme and language of every shot, in order", () => { + const picked = pickShots(shots, undefined); + assert.deepEqual(picked.map((p) => p.file), [ + "about-light-es-419.png", + "about-light-en.png", + "about-dark-es-419.png", + "about-dark-en.png", + "wallet-home-light-es-419.png", + "bot-chat-dark-en.png", + "bot-chat-dark-es-419.png", + ]); + assert.equal(picked[0].shot, shots[0]); + assert.deepEqual(picked.map((p) => [p.theme, p.lang]), [ + ["light", "es-419"], + ["light", "en"], + ["dark", "es-419"], + ["dark", "en"], + ["light", "es-419"], + ["dark", "en"], + ["dark", "es-419"], + ]); +}); + +test("an empty filter is no filter, as the loop in shoot.mjs treats it", () => { + assert.equal(pickShots(shots, "").length, 7); +}); + +test("a filter keeps only the files that contain it", () => { + assert.deepEqual(pickShots(shots, "wallet").map((p) => p.file), ["wallet-home-light-es-419.png"]); + assert.equal(pickShots(shots, "about").length, 4); + // The filter matches the whole file name, theme and language included, as before. + assert.deepEqual(pickShots(shots, "dark-en").map((p) => p.file), ["about-dark-en.png", "bot-chat-dark-en.png"]); +}); + +test("a filter that matches nothing gives an empty list", () => { + assert.deepEqual(pickShots(shots, "abuot"), []); + assert.deepEqual(pickShots(shots, "nothing-matches-this"), []); +}); diff --git a/apps/mobile/preview/shoot.mjs b/apps/mobile/preview/shoot.mjs index fcb1fba..7260835 100644 --- a/apps/mobile/preview/shoot.mjs +++ b/apps/mobile/preview/shoot.mjs @@ -7,11 +7,23 @@ import { fileURLToPath } from "node:url"; import { chromium } from "playwright-core"; import { chromiumPath } from "./browser.mjs"; import { shots } from "./shots.mjs"; +import { pickShots } from "./pick.mjs"; import { audit, words } from "./audit.mjs"; const here = dirname(fileURLToPath(import.meta.url)); const dist = join(here, "dist"); const outDir = join(here, "out/screens"); + +const filter = process.argv[2]; +if (!existsSync(join(dist, "index.html"))) { + console.error("No build found. Run pnpm build first."); + process.exit(1); +} +const picks = pickShots(shots, filter); +if (!picks.length) { + console.error(`No shot matches "${filter}". Examples: ${shots.slice(0, 3).map((s) => s.file).join(", ")}.`); + process.exit(1); +} mkdirSync(outDir, { recursive: true }); const types = { ".html": "text/html", ".js": "text/javascript", ".png": "image/png", ".json": "application/json", ".ttf": "font/ttf" }; @@ -29,50 +41,43 @@ const server = createServer((req, res) => { await new Promise((r) => server.listen(0, "127.0.0.1", r)); const base = `http://127.0.0.1:${server.address().port}/`; -const filter = process.argv[2]; const browser = await chromium.launch({ executablePath: chromiumPath() }); const results = []; -for (const shot of shots) { - for (const theme of shot.themes) { - for (const lang of shot.langs) { - const file = `${shot.file}-${theme}-${lang}.png`; - if (filter && !file.includes(filter)) continue; - const ctx = await browser.newContext({ viewport: { width: 412, height: 915 }, deviceScaleFactor: 2, locale: lang, colorScheme: theme }); - const page = await ctx.newPage(); - const consoleErrors = []; - // React DOM's nesting warnings (a Pressable inside a Pressable becomes