Your agent's truncate() cuts emoji in half: a property test that finds it and an Intl.Segmenter fix
Ask for a string truncation helper and you get slice() and a length check. Two fast-check properties turn that into a failing test with a shrunk counterexample, and the fix is six lines. About 15 minutes to try.

A notification title has to fit in 40 characters, so the ticket says “truncate with an ellipsis”. The helper that comes back is the one everybody writes first: if text.length is over the limit, slice and append โฆ. It passes the three examples in the ticket. Then a user with a smiley in their name gets a title that ends in a lone half of a character and a replacement glyph, or a rejected payload.
This is a classic defect in generated code because the happy path is ASCII and the prompt is ASCII. The fix is small. The part worth keeping is the test, because two properties catch the whole family of bugs (cut surrogate pairs, cut emoji sequences, cut accents) in one go, and they work with any agent that can read files and run npx vitest.
The draft that looks right
// src/truncate.ts
export function truncate(text: string, max: number): string {
if (text.length <= max) return text;
return text.slice(0, max - 1) + "โฆ";
}
JavaScript strings are sequences of UTF-16 code units, and length and slice count those. Anything outside the Basic Multilingual Plane, including most emoji, takes two units. Anything a reader sees as one character can take many more. A family emoji is four emoji joined by zero-width joiners:
const family = "๐จโ๐ฉโ๐งโ๐ฆ";
console.log(family.length, [...family].length);
11 7
Eleven code units, seven code points, one thing on screen. Here’s what the draft does with it, and with a plain smiley:
const t = (x, m) => (x.length <= m ? x : x.slice(0, m - 1) + "โฆ");
for (const [s, m] of [["Hi ๐ there", 5], ["ab๐จโ๐ฉโ๐งโ๐ฆcd", 4]]) {
const out = t(s, m);
console.log(JSON.stringify(out), out.isWellFormed());
}
"Hi \ud83dโฆ" false
"ab\ud83dโฆ" false
Both results end in \ud83d, a high surrogate with no partner. isWellFormed() returns false, which is the signal that a string can’t be encoded to UTF-8 without replacement characters.
Property one: the output is valid and fits
Don’t ask the agent for more example tests. Examples are where the ASCII bias comes from. Ask for properties, and generate the inputs with a Unicode-aware arbitrary. fast-check’s fc.string takes a unit option, and unit: "grapheme" generates printable graphemes that may span several code points, with minLength and maxLength counted in graphemes. The default unit is printable ASCII, which is why a property test written without thinking about it finds nothing.
Install the pieces:
npm i -D vitest fast-check typescript
Then the test file:
// src/truncate.test.ts
import { describe, expect, it } from "vitest";
import fc from "fast-check";
import { truncate } from "./truncate";
const graphemes = (s: string) =>
[...new Intl.Segmenter("en", { granularity: "grapheme" }).segment(s)].map((x) => x.segment);
describe("truncate", () => {
it("keeps short text as it is", () => {
expect(truncate("hello", 10)).toBe("hello");
});
it("never returns a broken string and never exceeds max visible characters", () => {
fc.assert(
fc.property(
fc.string({ unit: "grapheme", maxLength: 40 }),
fc.integer({ min: 1, max: 20 }),
(text, max) => {
const out = truncate(text, max);
expect(out.isWellFormed()).toBe(true);
expect(graphemes(out).length).toBeLessThanOrEqual(max);
},
),
);
});
});
The test measures with Intl.Segmenter at grapheme granularity. Per MDN, segment() returns an iterable of segments for the locale and granularity you set, and the API has been available across browsers since April 2024. The test uses it as the oracle for “what a reader would count as one character”, so the implementation and the check agree on the definition of a character, and that’s the point.
Property two: it only cuts on boundaries
Well-formed isn’t enough. Cutting a family emoji after the second person leaves valid UTF-16 and a wrong picture. The second property says the kept text, minus the ellipsis, must be exactly the first N graphemes of the input:
it("only cuts at grapheme boundaries", () => {
fc.assert(
fc.property(
fc.string({ unit: "grapheme", minLength: 1, maxLength: 40 }),
fc.integer({ min: 2, max: 20 }),
(text, max) => {
const out = truncate(text, max);
if (out === text) return;
const kept = out.slice(0, -1);
const boundaries = new Set([""]);
let acc = "";
for (const g of graphemes(text)) boundaries.add((acc += g));
expect(boundaries.has(kept)).toBe(true);
},
),
);
});
It builds the set of every prefix of the input that ends on a grapheme boundary, then checks that what the function kept is one of them. The min: 2 is deliberate: with a limit of 1 there’s no room for any text besides the ellipsis, and that case is covered by the first property.
Add one concrete test as well, because a shrunk counterexample is hard to read and a named case documents the intent:
it("keeps a family emoji whole", () => {
const family = "๐จโ๐ฉโ๐งโ๐ฆ";
expect(truncate(`ab${family}cd`, 4)).toBe(`ab${family}โฆ`);
});
Watch it fail
Run npx vitest run against the slice draft. The relevant lines:
โฏ src/truncate.test.ts (3 tests | 2 failed) 59ms
โฏ truncate (3)
ร never returns a broken string and never exceeds max visible characters 42ms
ร only cuts at grapheme boundaries 13ms
...
Counterexample: [" ๐",3]
Shrunk 7 time(s)
...
Counterexample: [" ๐ ",3]
Shrunk 15 time(s)
The counterexamples are shrunk to a space and one character outside the BMP, with a limit of 3. Nobody would have written that example by hand, which is the argument for the technique. The seeds change between runs, so yours will show different characters; the failure will not go away.
Paste the failing output into the agent as the next prompt, along with the test file, and tell it not to edit the tests. A prompt that works:
These two property tests fail against src/truncate.ts. Don't change the tests.
Fix truncate() so both pass. The limit counts characters as a reader sees them
(grapheme clusters), and the ellipsis counts as one. Run `npx vitest run` and
paste the result.
The fix
// src/truncate.ts
const segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
export function truncate(text: string, max: number): string {
const graphemes = Array.from(segmenter.segment(text), (s) => s.segment);
if (graphemes.length <= max) return text;
return graphemes.slice(0, max - 1).join("") + "โฆ";
}
Run again:
RUN v5.1.0
Test Files 1 passed (1)
Tests 4 passed (4)
The segmenter is created once at module level so the helper doesn’t build a new one on every call. Passing undefined as the locale uses the runtime default; pass a locale explicitly if you want the result tied to one.
Make it yours
A limit that isn’t about what the reader sees. The notification limit above is visual. Database columns and wire formats count something else: the family emoji is 25 bytes in UTF-8 (Buffer.byteLength reports it), so a varchar(40) measured in bytes or a protocol field with a byte cap needs a different function. Don’t reuse truncate and hope. Write a second helper that accumulates graphemes until the next one would exceed the byte budget, and give it the same two properties with Buffer.byteLength(out) <= budget in place of the grapheme count. Tell the agent which unit the limit is in; it’s the one fact it can’t infer from a function name.
Normalisation. รฉ can be one code point or e plus a combining accent. Graphemes treat both as one character, so truncation is safe either way, but equality checks and deduplication aren’t. If the helper feeds a comparison, normalise with text.normalize("NFC") first and add a property that truncate(x) and truncate(x.normalize("NFD")) have the same grapheme count.
Other helpers with the same blind spot. Anything that reverses, pads, centres, counts or splits strings by index: reverse(), padEnd for table output, a word-wrap function, a “first initial” avatar helper (name[0] returns half of a surrogate pair for a name that starts with an astral character). Run both properties, adapted, against each. The generator is the reusable part.
C# readers get the same bug from string.Substring, which also counts UTF-16 units. The equivalent oracle is StringInfo.GetTextElementEnumerator, and FsCheck can generate the inputs. The structure of the two properties carries over unchanged.
What goes wrong
The generator is the weak link. fc.string() with no unit produces printable ASCII, so a property test written from memory can pass against the broken draft. Run the new tests against the slice version first and confirm they fail. A test that has never failed hasn’t shown it can.
The oracle shares the implementation’s dependency. Both use Intl.Segmenter, so if the runtime’s Unicode data is old, the test and the code agree on a wrong answer for the newest emoji sequences. The runs here were on Node 22.23.4, which reports ICU 78.3 and Unicode 17.0 in process.versions. Print those on your CI image once. A browser target will have its own data, and the segmenter in a bundled runtime may differ from the one on the server.
Segmentation costs more than slice. For a list of a few hundred titles it’s irrelevant. For a hot path that truncates megabytes, measure it, and consider a fast path that returns early when text.length <= max, which is always safe because the code-unit length is an upper bound on the grapheme count.
Don’t bother if the input is guaranteed ASCII (internal identifiers, hex digests, slugs the same code generated). The properties would pass trivially and the segmenter is wasted work.
First 15 minutes
Pick one string helper in your own codebase that takes a number and a string. Ask the agent for the two properties above using fc.string({ unit: "grapheme" }), have it run them against the current implementation, and only then ask for a fix. If they pass on the first run, check the generator before you believe it.