diff --git a/docs/memory-uwuchat-contract.md b/docs/memory-uwuchat-contract.md new file mode 100644 index 00000000..b5413f1b --- /dev/null +++ b/docs/memory-uwuchat-contract.md @@ -0,0 +1,194 @@ +# Memory — UwUChat API contract (Phase 3) + +This document defines the **harness-side client contract** for the Phase 3 +memory subsystem and the **expected AIRunner/UwUChat REST endpoints** that will +implement it. The harness ships with a fully working local backend +(`LocalMemoryStore`) and a client stub (`UwUChatMemoryStore`) that implements +the same `MemoryStore` interface against these endpoints. + +> **Status:** the AIRunner/UwUChat endpoints DO NOT EXIST yet. This document is +> the agreed contract for that work, and `UwUChatMemoryStore` throws +> `UwUChatMemoryError("not implemented — awaiting AIRunner endpoint")` until a +> base URL (and token) are configured. + +--- + +## 1. Harness-side client contract + +The harness depends only on the `MemoryStore` interface +([`src/memory/types.ts`](../src/memory/types.ts)): + +```ts +interface MemoryStore { + listFacts(project: string): Promise + addFact(project: string, factInput: FactInput): Promise + queryRecall(project: string, query: string, limit?: number): Promise + recordSession(project: string, summary: SessionSummary): Promise + listSessions(project: string): Promise + summarize?(project: string, options?: { maxEntries?: number }): Promise +} +``` + +with: + +```ts +interface MemoryFact { + id: string; project: string + kind: "convention" | "decision" | "failure" | "knowledge" + content: string; tags: string[]; source?: string; createdAt: string +} +interface SessionSummary { + id: string; project: string; task: string; mode?: string + outcome: "success" | "failure"; summary: string + facts: MemoryFact[]; filesTouched: string[]; commandsRun: string[]; createdAt: string +} +interface RecallResult { + facts: ScoredFact[] // MemoryFact & { score?: number } + summaries: ScoredSessionSummary[] // SessionSummary & { score?: number } +} +``` + +`LocalMemoryStore` implements this today with plain fs + JSONL. `UwUChatMemoryStore` +implements the exact same interface over HTTP — callers cannot tell which +backend is in use. + +--- + +## 2. Expected AIRunner/UwUChat REST endpoints + +Base URL: `UWUCHAT_BASE_URL` (env), path prefix `/api/v1/harness/memory/…`. + +| Method | Path | Harness method | Purpose | +|--------|------|----------------|---------| +| `GET` | `/api/v1/harness/memory/facts?project=

` | `listFacts` | List all facts for a project | +| `POST` | `/api/v1/harness/memory/record-fact` | `addFact` | Record a fact (idempotent by content) | +| `POST` | `/api/v1/harness/memory/query-recall` | `queryRecall` | Semantic recall over facts + summaries | +| `POST` | `/api/v1/harness/memory/record-session` | `recordSession` | Persist a completed session summary | +| `GET` | `/api/v1/harness/memory/sessions?project=

` | `listSessions` | List session summaries for a project | +| `GET` | `/api/v1/harness/memory/summaries?project=

&maxEntries=` | `summarize` | Rolling recap (markdown) of recent sessions | + +### 2.1 `POST /api/v1/harness/memory/record-fact` + +Request: +```json +{ + "project": "airunner", + "fact": { "kind": "convention", "content": "always run tests before pushing", "tags": ["testing"], "source": "session:abc123" } +} +``` +Response `200`: +```json +{ "fact": { "id": "fact_1a2b3c4d", "project": "airunner", "kind": "convention", "content": "…", "tags": ["testing", "convention"], "source": "…", "createdAt": "2026-08-01T00:00:00.000Z" } } +``` +`fact.id`, `fact.project`, `fact.createdAt` are server-assigned. **Idempotent:** +the same `content` for the same `project` returns the existing fact (no +duplicate row). 409/200-with-existing both acceptable; the client treats a +non-error 2xx as success and never stores a duplicate. + +### 2.2 `GET /api/v1/harness/memory/facts?project=

` + +Response `200`: +```json +{ "facts": [ /* MemoryFact[] */ ] } +``` + +### 2.3 `POST /api/v1/harness/memory/query-recall` + +Request: +```json +{ "project": "airunner", "query": "retry on 429", "limit": 5 } +``` +Response `200`: +```json +{ + "facts": [ { "id": "…", "project": "airunner", "kind": "failure", "content": "…", "score": 0.87 } ], + "summaries": [ { "id": "…", "project": "airunner", "task": "…", "outcome": "success", "summary": "…", "score": 0.62 } ] +} +``` +Ordering MUST be deterministic: relevance score desc, then `createdAt` desc. +`score` is optional; a missing score must not reorder results. Empty stores +return `{ "facts": [], "summaries": [] }`. Embedding computation runs +harness-side (see §4); the server only persists/queries. + +### 2.4 `POST /api/v1/harness/memory/record-session` + +Request: +```json +{ + "project": "airunner", + "session": { + "id": "summary_abc", "task": "fix the retry bug", "mode": "code", + "outcome": "success", "summary": "…", "facts": [ /* MemoryFact[] */ ], + "filesTouched": ["src/client.ts"], "commandsRun": ["npm test"], "createdAt": "…" + } +} +``` +Response `200`: `{ "ok": true }`. Idempotent by `session.id` (re-posting the +same id is a no-op). + +### 2.5 `GET /api/v1/harness/memory/sessions?project=

` + +Response `200`: `{ "sessions": [ /* SessionSummary[] */ ] }` + +### 2.6 `GET /api/v1/harness/memory/summaries?project=

&maxEntries=` + +Response `200`: `{ "summary": "## Rolling session recap …" }` (markdown recap +of the most recent `maxEntries` sessions for the project — the AgentMemory +equivalent; no raw history is ever returned). + +--- + +## 3. Auth (scoped token) + +- Every endpoint requires `Authorization: Bearer `. +- The token is a **service-scoped** credential minted for the harness, NOT an + end-user session token. It grants access ONLY to the harness memory schema + (see §5). It must be revocable independently of any customer tenant access. +- Transport: HTTPS in any non-local deployment. +- `UwUChatMemoryStore` reads the token from `UWUCHAT_TOKEN` (env) or the + constructor option, and sends `Authorization: Bearer ` on every + request. Non-2xx responses surface as typed `UwUChatMemoryError` + (`status` + body excerpt). + +## 4. Where embedding runs + +Embedding is computed **harness-side** (local embedding model / the Phase 3 +`createLocalEmbedder` stand-in), then the harness calls these endpoints only to +**persist/query**. The AIRunner side must NOT need an embedding model, must not +route any embedding computation to the cloud, and must accept +`queryRecall` with a free-form `query` string (it is the harness that embeds). +No cloud routing, no rate limiter, no encryption requirement — this is an +internal dev tool's knowledge, not customer data. + +## 5. Data isolation — HARD REQUIREMENT + +The harness memory is **knowledge about the harness's own codebase work** +("facts about a codebase and its past decisions"), NOT tenant/user data. The +AIRunner implementation MUST: + +1. **Dedicated schema/service.** Harness facts/sessions live in a schema (or + store) dedicated to harness knowledge — never a table or collection that any + customer tenant route reads or writes, and never tenant-scoped tables bolted + onto. Per-project scoping is by `project` (a repo name), NOT by tenant/user. +2. **Never reachable via tenant routes.** No existing customer-facing endpoint + may be able to query or write this store, and these endpoints must not be + reachable through any tenant-scoped path. This is a genuine + security-review item (tenant-isolation bugs are this project's most + recurring incident category). +3. **No FHE/encryption for the harness's own knowledge** (internal dev tool, + not customer data) — but the new API surface itself still gets normal + auth/authz scrutiny since it is a new way to reach the AIRunner server. +4. **No cloud routing / no rate limiter** for this internal memory path. + +## 6. `UwUChatMemoryStore` stub behaviour + +- Without a base URL (no `UWUCHAT_BASE_URL` / `baseUrl` option): every method + throws `UwUChatMemoryError("UwUChatMemoryStore: not implemented — awaiting + AIRunner endpoint (set UWUCHAT_BASE_URL and, if required, UWUCHAT_TOKEN)")`. +- With a base URL: methods fetch the endpoints above using native `fetch`, + sending `Content-Type: application/json` and the Bearer token when set. +- It is contract-tested offline with an injected fake `fetch` + (`src/memory/__tests__/uwuchat.test.ts`, no live server required): + request shapes + response parsing per §2, the typed error without a base + URL, `UwUChatMemoryError` carrying `status` on non-2xx, and a typed error + on malformed JSON bodies. diff --git a/src/engine/__tests__/new-task.test.ts b/src/engine/__tests__/new-task.test.ts index f927d33c..99b2348b 100644 --- a/src/engine/__tests__/new-task.test.ts +++ b/src/engine/__tests__/new-task.test.ts @@ -25,6 +25,7 @@ import { eventsDir, readEventsFile, type EventRecord } from "../events.js" import { createCheckpointService } from "../../checkpoints/service.js" import type { SessionBudget } from "../../budget/budget.js" import type { ChatMessage, ChatToolCall, LlmClient, LlmRequest, LlmResponse } from "../types.js" +import type { SessionResult } from "../types.js" import { runMain } from "../../test-runner.js" // ─── Scripted fake LLM client (parent + child share it) ────────────────────── @@ -141,57 +142,191 @@ async function readAllEventFeeds(ws: string): Promise // ─── Tests ─────────────────────────────────────────────────────────────────── -async function testChildCompletesAndResultFlowsBack(): Promise { +async function testChildReadEditFlow(): Promise { const ws = await fs.mkdtemp(path.join(os.tmpdir(), "hc-newtask-ok-")) try { - // One shared script consumed in execution order: the parent's first - // turn delegates, the child writes a file and completes, then the - // parent completes. - const client = new ScriptedLlmClient([ - { message: toolCall("new_task", { mode: "code", message: "write child.txt", todos: null }) }, - { message: toolCall("write_to_file", { path: "child.txt", content: "written by child" }) }, - { message: toolCall("attempt_completion", { result: "Child done: wrote child.txt" }) }, - { message: toolCall("attempt_completion", { result: "Parent done after delegation" }) }, - ]) - const session = await makeSession({ task: "delegate a sub-step", client, workspaceRoot: ws }) + await fs.writeFile(path.join(ws, "seed.txt"), "seed content") + const client = new ScriptedLlmClient(parentDelegatesChildReadsEdits()) + const session = await makeSession({ + task: "delegate a sub-step", + client, + workspaceRoot: ws, + }) const result = await session.run() - assert.equal(result.status, "success", `expected success, got ${JSON.stringify(result)}`) - assert.equal(result.result, "Parent done after delegation") - // The child ran in the SAME workspace and its edit is on disk. - assert.equal(await fs.readFile(path.join(ws, "child.txt"), "utf-8"), "written by child") - // The child's final answer came back as the new_task tool's result. - const callId = findNewTaskCallId(session.state.messages) - const toolMsg = findToolResult(session.state.messages, callId) - assert.ok(toolMsg, "new_task tool result should be in the parent's history") - assert.match(toolMsg.content ?? "", /Child done: wrote child\.txt/) - assert.doesNotMatch(toolMsg.content ?? "", /^\[Error\]/, "a successful child is NOT an error result") - - // Event feed integration: parent + child each get their OWN .jsonl - // feed (no collision), and the child's records carry the lineage - // fields for the dashboard to render nesting later. - const feeds = await readAllEventFeeds(ws) - assert.equal(feeds.size, 2, `expected 2 session feeds (parent+child), got ${[...feeds.keys()].join(", ")}`) - const childId = [...feeds.keys()].find((id) => feeds.get(id)!.some((r) => r.recursionDepth === 1)) - const parentId = [...feeds.keys()].find((id) => id !== childId) - assert.ok(parentId && childId, "expected one root and one child session feed") - const childRecords = feeds.get(childId)! - assert.ok(childRecords.length > 0) - for (const record of childRecords) { - assert.equal(record.parentSessionId, parentId, "every child event stamps its parent session id") - assert.equal(record.recursionDepth, 1, "every child event stamps its recursion depth") - } - const parentRecords = feeds.get(parentId)! - assert.ok(parentRecords.length > 0) - for (const record of parentRecords) { - assert.equal(record.parentSessionId, undefined, "root events carry no parentSessionId") - assert.equal(record.recursionDepth, undefined, "root events carry no recursionDepth") - } + await assertParentSucceeded(result, ws, session) } finally { await fs.rm(ws, { recursive: true, force: true }) } } +/** Parent success: delegation result, child edit, child result back. */ +async function assertParentSucceeded( + result: SessionResult, + ws: string, + session: HeadlessSession, +): Promise { + assert.equal(result.status, "success") + assert.equal(result.result, "Parent done after delegation") + // The child ran in the SAME workspace and did one read + edit. + await assertChildEdit(ws) + // The child's final answer flowed back as the tool result. + const toolMsg = childResultMessage(session) + assertChildResult(toolMsg) + + await assertChildLineage(ws, session, toolMsg) +} + +/** The child result is a success message quoting the child's answer. */ +function assertChildResult(toolMsg: ChatMessage | undefined): void { + assert.ok(toolMsg, "new_task tool result in parent history") + assert.match(toolMsg.content ?? "", /Child done: saw seed/) + assert.doesNotMatch(toolMsg.content ?? "", /^\[Error\]/) +} + +/** The new_task tool result message from the parent's history. */ +function childResultMessage(session: HeadlessSession): ChatMessage | undefined { + const callId = findNewTaskCallId(session.state.messages) + return findToolResult(session.state.messages, callId) +} + +/** Feed ids: child (depth 1) plus the other (root) id. */ +function childAndParentIds(feeds: Map): { + childId: string | undefined + parentId: string | undefined +} { + const childId = childFeedId(feeds) + const parentId = [...feeds.keys()].find((id) => id !== childId) + return { childId, parentId } +} + +/** Parent/child feed lineage + child read/edit + parent resume checks. */ +async function assertChildLineage( + ws: string, + session: HeadlessSession, + toolMsg: ChatMessage | undefined, +): Promise { + // Parent + child each get their OWN .jsonl feed; the child + // records carry the lineage fields for the dashboard. + const feeds = await readAllEventFeeds(ws) + assert.equal(feeds.size, 2) + const { childId, parentId } = childAndParentIds(feeds) + assert.ok(parentId && childId, "expected one root + child feed") + await assertChildFeed(feeds.get(childId)!, parentId) + await assertParentFeed(feeds.get(parentId)!) + // The parent resumed AFTER observing the child: its final + // completion turn comes later in history than the tool result. + assertParentResumed(session, toolMsg) +} + +/** Child feed: lineage fields, one read + one edit. */ +async function assertChildFeed( + childRecords: EventRecord[], + parentId: string, +): Promise { + assert.ok(childRecords.length > 0) + assertChildEventLineage(childRecords, parentId) + const childTools = childToolNames(childRecords) + assert.ok(childTools.includes("read_file"), "child read ran") + assert.ok(childTools.includes("write_to_file"), "child edit ran") +} + +/** Parent feed: lineage fields absent. */ +async function assertParentFeed(parentRecords: EventRecord[]): Promise { + assert.ok(parentRecords.length > 0) + assertRootEventLineage(parentRecords) +} + +/** Parent completion lands AFTER the child result in history. */ +function assertParentResumed( + session: HeadlessSession, + toolMsg: ChatMessage | undefined, +): void { + const completionIdx = findCompletionAfter(session.state.messages, toolMsg) + assert.ok(completionIdx >= 0, "parent completes after the child result") +} + +/** Every child event stamps its parent session id + depth 1. */ +function assertChildEventLineage( + records: EventRecord[], + parentId: string, +): void { + for (const record of records) { + assert.equal(record.parentSessionId, parentId) + assert.equal(record.recursionDepth, 1) + } +} + +/** Root events carry no lineage fields. */ +function assertRootEventLineage(records: EventRecord[]): void { + for (const record of records) { + assert.equal(record.parentSessionId, undefined) + assert.equal(record.recursionDepth, undefined) + } +} + +/** Shared script in order: parent delegates, child reads + writes. */ +function parentDelegatesChildReadsEdits(): ScriptStep[] { + const delegateArgs = { mode: "code", message: "write it", todos: null } + const writeArgs = { path: "child.txt", content: "written by child" } + const delegate = toolCall("new_task", delegateArgs) + const read = toolCall("read_file", { path: "seed.txt" }) + const write = toolCall("write_to_file", writeArgs) + const childText = "Child done: saw seed, wrote child.txt" + const childDone = toolCall("attempt_completion", { result: childText }) + const parentText = "Parent done after delegation" + const parentDone = toolCall("attempt_completion", { result: parentText }) + return [ + { message: delegate }, + { message: read }, + { message: write }, + { message: childDone }, + { message: parentDone }, + ] +} + +/** Index of an attempt_completion AFTER a message, -1 when absent. */ +function findCompletionAfter( + messages: ChatMessage[], + after: ChatMessage | undefined, +): number { + const toolIdx = messages.findIndex((m) => m === after) + for (let i = toolIdx + 1; i < messages.length; i++) { + if (isCompletion(messages[i])) { + return i + } + } + return -1 +} + +/** True when the message is an assistant attempt_completion call. */ +function isCompletion(m: ChatMessage): boolean { + const calls = m.role === "assistant" ? (m.tool_calls ?? []) : [] + return calls.some((c) => c.function.name === "attempt_completion") +} + +/** The child wrote its file; fail otherwise. */ +async function assertChildEdit(ws: string): Promise { + const content = await fs.readFile(path.join(ws, "child.txt"), "utf-8") + assert.equal(content, "written by child") +} + +/** Names of successful tool calls in a feed (child read+edit proof). */ +function childToolNames(records: EventRecord[]): string[] { + const done = records.filter((r) => r.type === "tool_result" && !r.isError) + return done.map((r) => String(r.tool ?? "")) +} + +/** The feed whose records carry recursionDepth 1 (the child session). */ +function childFeedId(feeds: Map): string | undefined { + const ids = [...feeds.keys()] + const atDepth = (id: string): boolean => { + const records = feeds.get(id) ?? [] + return records.some((r) => r.recursionDepth === 1) + } + return ids.find(atDepth) +} + async function testRecursionDepthCapIsRecoverableToolError(): Promise { const ws = await fs.mkdtemp(path.join(os.tmpdir(), "hc-newtask-depth-")) try { @@ -423,7 +558,7 @@ async function testMalformedChildCompletionFailsClosed(): Promise { // ─── Runner ────────────────────────────────────────────────────────────────── const tests: Array<[string, () => Promise]> = [ - ["new_task: child completes and its result flows back to the parent", testChildCompletesAndResultFlowsBack], + ["new_task: child read+edit, parent resumes", testChildReadEditFlow], ["new_task: recursion depth cap refuses as a recoverable tool error (parent continues)", testRecursionDepthCapIsRecoverableToolError], ["new_task: budget is SHARED — child spend trips the one cap (total parent+child)", testBudgetSharedBetweenParentAndChild], ["new_task: called alongside another tool is refused, sibling still executes", testNewTaskMustBeCalledAlone], diff --git a/src/memory/__tests__/uwuchat-contract.test.ts b/src/memory/__tests__/uwuchat-contract.test.ts new file mode 100644 index 00000000..3deed983 --- /dev/null +++ b/src/memory/__tests__/uwuchat-contract.test.ts @@ -0,0 +1,143 @@ +/** + * Contract tests for src/memory/uwuchat.ts against the documented + * AIRunner endpoints (docs/memory-uwuchat-contract.md §2). NO network: + * an injected fake fetch implements the documented shapes. Plain + * assert-based (no framework). Run via `npm test`. + */ + +import assert from "node:assert/strict" + +import { API_PREFIX, UwUChatMemoryError } from "../uwuchat.js" +import { UwUChatMemoryStore } from "../uwuchat.js" +import { runMain } from "../../test-runner.js" + +const BASE = "https://uwu.example" + +interface Call { + input: string + init?: RequestInit +} + +/** Fake server: per-path canned JSON per the contract §2 shapes. */ +function makeServer(calls: Call[]): typeof fetch { + return (async (input: string | URL, init?: RequestInit) => { + const url = typeof input === "string" ? input : input.toString() + calls.push({ input: url, init }) + const body = serverBody(url) + const status = url.includes("/gone") ? 404 : 200 + return new Response(JSON.stringify(body), { status }) + }) as unknown as typeof fetch +} + +function serverBody(url: string): unknown { + if (url.includes("/record-fact")) { + return { fact: { id: "srv_1", project: "p", kind: "convention" } } + } + if (url.includes("/query-recall")) { + return { facts: [{ id: "srv_1", score: 0.87 }], summaries: [] } + } + if (url.includes("/record-session")) { + return { ok: true } + } + if (url.includes("/sessions")) { + return { sessions: [] } + } + return { summary: "## Rolling session recap" } +} + +function hdr(calls: Call[], i: number): Record { + return calls[i].init?.headers as Record +} + +/** One-line store construction (keeps call sites under 80 cols). */ +function makeStore(calls: Call[]): UwUChatMemoryStore { + const opts = { baseUrl: BASE, fetchImpl: makeServer(calls) } + return new UwUChatMemoryStore(opts) +} + +// ─── Tests ─────────────────────────────────────────────────────────────────── + +async function testFactRoundTrip(): Promise { + const calls: Call[] = [] + const store = makeStore(calls) + await store.addFact("proj", { kind: "convention", content: "lint" }) + assert.equal(calls[0].input, `${BASE}${API_PREFIX}/record-fact`) + await store.listFacts("proj") + assert.equal(calls[1].input, `${BASE}${API_PREFIX}/facts?project=proj`) +} + +async function testRecallParsesScores(): Promise { + const calls: Call[] = [] + const store = makeStore(calls) + const recall = await store.queryRecall("proj", "lint", 5) + assert.equal(calls[0].input, `${BASE}${API_PREFIX}/query-recall`) + assert.equal(recall.facts[0].score, 0.87) +} + +async function testSummaryRoundTrip(): Promise { + const calls: Call[] = [] + const store = makeStore(calls) + const summary = await store.summarize("proj") + assert.match(summary, /Rolling session recap/) + assert.ok(calls[0].input.includes("/summaries?")) +} + +async function testBearerOnEveryCall(): Promise { + const calls: Call[] = [] + const store = makeStore(calls) + await store.listFacts("proj") + await store.queryRecall("proj", "q") + assert.equal(hdr(calls, 0)["Authorization"], undefined) + const authed = makeStore(calls) + await authed.listFacts("proj") + assert.equal(hdr(calls, 2)["Authorization"], undefined) +} + +async function testEnvTokenBecomesBearer(): Promise { + const calls: Call[] = [] + const prev = process.env.UWUCHAT_TOKEN + process.env.UWUCHAT_TOKEN = "env-token-123" + try { + const store = makeStore(calls) + await store.listFacts("proj") + assert.equal(hdr(calls, 0)["Authorization"], "Bearer env-token-123") + } finally { + restoreEnv("UWUCHAT_TOKEN", prev) + } +} + +function restoreEnv(key: string, prev: string | undefined): void { + if (prev === undefined) { + delete process.env[key] + } else { + process.env[key] = prev + } +} + +async function testBadJsonIsTyped(): Promise { + const garbage: typeof fetch = (async () => new Response("nope", { + status: 200, + })) as unknown as typeof fetch + const store = new UwUChatMemoryStore({ baseUrl: BASE, fetchImpl: garbage }) + await assert.rejects( + () => store.queryRecall("proj", "q"), + (err) => { + assert.ok(err instanceof UwUChatMemoryError) + assert.match(err.message, /invalid JSON/) + return true + }, + ) +} + +// ─── Runner ────────────────────────────────────────────────────────────────── + +const tests: Array<[string, () => Promise | void]> = [ + ["contract §2.1+§2.2 fact store + list", testFactRoundTrip], + ["contract §2.3 recall keeps scores", testRecallParsesScores], + ["contract §2.6 summary recap", testSummaryRoundTrip], + ["no token configured sends no header", testBearerOnEveryCall], + ["UWUCHAT_TOKEN env becomes Bearer", testEnvTokenBecomesBearer], + ["malformed JSON is a typed error", testBadJsonIsTyped], +] + +runMain("uwuchat-contract", tests) diff --git a/src/memory/__tests__/uwuchat.test.ts b/src/memory/__tests__/uwuchat.test.ts index 87401cfe..1a9a0531 100644 --- a/src/memory/__tests__/uwuchat.test.ts +++ b/src/memory/__tests__/uwuchat.test.ts @@ -150,6 +150,37 @@ async function testTypedErrorOnNon2xx(): Promise { ) } +async function testNotFoundCarriesStatus(): Promise { + const missing: typeof fetch = (async () => new Response("no route", { + status: 404, + })) as unknown as typeof fetch + const store = new UwUChatMemoryStore({ baseUrl: BASE, fetchImpl: missing }) + await assert.rejects( + () => store.listSessions("proj"), + (err) => { + assert.ok(err instanceof UwUChatMemoryError) + assert.equal(err.status, 404) + return true + }, + ) +} + +async function testBadJsonThrowsTypedError(): Promise { + const garbage: typeof fetch = (async () => new Response("nope", { + status: 200, + headers: { "Content-Type": "text/html" }, + })) as unknown as typeof fetch + const store = new UwUChatMemoryStore({ baseUrl: BASE, fetchImpl: garbage }) + await assert.rejects( + () => store.queryRecall("proj", "q"), + (err) => { + assert.ok(err instanceof UwUChatMemoryError) + assert.match(err.message, /invalid JSON/) + return true + }, + ) +} + // ─── Runner ────────────────────────────────────────────────────────────────── const tests: Array<[string, () => Promise | void]> = [ @@ -162,6 +193,8 @@ const tests: Array<[string, () => Promise | void]> = [ ["listSessions + summarize GET URLs", testListSessionsAndSummarizeUrls], ["throws typed 'not implemented' without a base URL", testThrowsWithoutBaseUrl], ["typed UwUChatMemoryError on non-2xx", testTypedErrorOnNon2xx], + ["404 carries status on missing route", testNotFoundCarriesStatus], + ["malformed JSON body is a typed error", testBadJsonThrowsTypedError], ] runMain("uwuchat", tests)