| 1 | // Tests for the Claude context shaper. node test/context.test.mjs |
| 2 | import assert from "node:assert/strict"; |
| 3 | import { trimContext } from "../agent/context.mjs"; |
| 4 | |
| 5 | let failures = 0; |
| 6 | function test(name, fn) { |
| 7 | try { |
| 8 | fn(); |
| 9 | console.log(`PASS ${name}`); |
| 10 | } catch (e) { |
| 11 | failures++; |
| 12 | console.log(`FAIL ${name} — ${e && e.message}`); |
| 13 | } |
| 14 | } |
| 15 | |
| 16 | const u = (content = "hi") => ({ role: "user", content }); |
| 17 | const a = (content = "hi") => ({ role: "assistant", content }); |
| 18 | |
| 19 | test("drops a leading assistant turn (API needs user first)", () => { |
| 20 | assert.deepEqual(trimContext([a("greeting"), u("q"), a("ans")]), [u("q")]); |
| 21 | }); |
| 22 | |
| 23 | test("drops a trailing assistant turn (no prefill under thinking)", () => { |
| 24 | // The 400 case: newest message we can see is our own reply. |
| 25 | assert.deepEqual(trimContext([u("q"), a("ans")]), [u("q")]); |
| 26 | }); |
| 27 | |
| 28 | test("keeps a conversation that already ends on a user turn", () => { |
| 29 | const c = [u("a"), a("b"), u("c")]; |
| 30 | assert.deepEqual(trimContext(c), c); |
| 31 | }); |
| 32 | |
| 33 | test("all-assistant collapses to empty (caller falls back to a hello)", () => { |
| 34 | assert.deepEqual(trimContext([a(), a()]), []); |
| 35 | }); |
| 36 | |
| 37 | test("trims both ends at once", () => { |
| 38 | assert.deepEqual(trimContext([a(), u("x"), a("y"), u("z"), a("w")]), [u("x"), a("y"), u("z")]); |
| 39 | }); |
| 40 | |
| 41 | test("empty / nullish input is safe and returns a fresh array", () => { |
| 42 | assert.deepEqual(trimContext([]), []); |
| 43 | assert.deepEqual(trimContext(null), []); |
| 44 | const src = [u("x")]; |
| 45 | assert.notEqual(trimContext(src), src); // never mutates or aliases the caller's array |
| 46 | }); |
| 47 | |
| 48 | console.log(failures === 0 ? "\nALL PASSED" : `\n${failures} FAILED`); |
| 49 | process.exit(failures === 0 ? 0 : 1); |
| 50 | |