@skyphusion/create-prism 0.175.6 → 1.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/template/README.md +192 -25
- package/template/migrations/0003_conversation_compact.sql +24 -0
- package/template/migrations/0004_csp_reports.sql +58 -0
- package/template/package.json +4 -4
- package/template/public/app.js +107 -4
- package/template/public/index.html +5 -1
- package/template/public/stt.css +25 -0
- package/template/public/stt.html +1 -21
- package/template/public/styles.css +27 -2
- package/template/public/url-safety.js +66 -0
- package/template/schema.sql +75 -0
- package/template/src/conversation-context.ts +126 -0
- package/template/src/csp.ts +253 -0
- package/template/src/index.ts +85 -2
- package/template/src/routes/chat.ts +62 -78
- package/template/src/routes/conversations.ts +285 -3
- package/template/src/routes/csp-report.ts +163 -0
- package/template/src/routes/health.ts +6 -1
- package/template/src/routes/rag.ts +25 -3
- package/template/src/stt-session.ts +17 -1
- package/template/src/version.ts +18 -0
- package/template/tests/conversation-compact.test.ts +103 -0
- package/template/tests/csp.test.ts +444 -0
- package/template/tests/public-url-safety.test.ts +360 -0
- package/template/tests/rag-retrieval-diagnostic.test.ts +142 -0
- package/template/tests/version.test.ts +47 -0
- package/template/tests-integration/csp-report.test.ts +232 -0
- package/template/tests-integration/worker.test.ts +154 -0
- package/template/vitest.workers.config.ts +19 -4
- package/template/wrangler.example.toml +33 -0
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
// POST /api/csp-report -- the CSP violation collector (fleet-chezmoi#1646).
|
|
2
|
+
//
|
|
3
|
+
// THIS ROUTE IS UNAUTHENTICATED AND CANNOT BE OTHERWISE. Browsers post CSP
|
|
4
|
+
// reports without credentials, so a token gate would collect nothing. Every
|
|
5
|
+
// design choice below follows from that: anyone can post here, at any volume,
|
|
6
|
+
// with any body, so the body is capped, the projection is a fixed field set,
|
|
7
|
+
// every field is length-bounded, the rate is limited, and shedding is counted
|
|
8
|
+
// rather than silent.
|
|
9
|
+
//
|
|
10
|
+
// The pure half (policy string, field caps, report projection) is in src/csp.ts
|
|
11
|
+
// and is unit-tested without D1. This file does the window and the insert.
|
|
12
|
+
|
|
13
|
+
import type { Env } from "../env";
|
|
14
|
+
import { rateLimitDecision } from "../rate-limit";
|
|
15
|
+
import {
|
|
16
|
+
CSP_FIELD_CAPS,
|
|
17
|
+
CSP_RATE_LIMIT,
|
|
18
|
+
CSP_RATE_WINDOW_SECONDS,
|
|
19
|
+
CSP_REPORT_MAX_BYTES,
|
|
20
|
+
CSP_RETENTION_DAYS,
|
|
21
|
+
extractCspReport,
|
|
22
|
+
} from "../csp";
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Reports are fire-and-forget from the browser's side; nothing reads the body.
|
|
26
|
+
* Every return is 204 with no body EXCEPT the refusals we want to be able to
|
|
27
|
+
* test and count, which carry a status that says which refusal fired.
|
|
28
|
+
*/
|
|
29
|
+
const NO_CONTENT = () => new Response(null, { status: 204 });
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Rate-limit window against the collector's OWN bucket table.
|
|
33
|
+
*
|
|
34
|
+
* Deliberately not `checkRateLimit` from src/rate-limit.ts: that writes to
|
|
35
|
+
* `auth_attempts`, and pointing an unauthenticated public write path at the
|
|
36
|
+
* table the login limiter depends on couples a flood here to sign-in there.
|
|
37
|
+
* The pure decision function IS reused, so the window semantics cannot drift
|
|
38
|
+
* from the audited ones.
|
|
39
|
+
*/
|
|
40
|
+
async function windowFor(
|
|
41
|
+
db: D1Database,
|
|
42
|
+
bucketKey: string,
|
|
43
|
+
): Promise<{ allowed: boolean }> {
|
|
44
|
+
const row = await db
|
|
45
|
+
.prepare(
|
|
46
|
+
`SELECT count, CAST(strftime('%s', window_start) AS INTEGER) AS ws
|
|
47
|
+
FROM csp_report_buckets WHERE bucket_key = ?`,
|
|
48
|
+
)
|
|
49
|
+
.bind(bucketKey)
|
|
50
|
+
.first<{ count: number; ws: number }>();
|
|
51
|
+
const nowRow = await db
|
|
52
|
+
.prepare(`SELECT CAST(strftime('%s','now') AS INTEGER) AS now`)
|
|
53
|
+
.first<{ now: number }>();
|
|
54
|
+
const now = nowRow?.now ?? 0;
|
|
55
|
+
|
|
56
|
+
const d = rateLimitDecision(
|
|
57
|
+
now,
|
|
58
|
+
row?.ws ?? null,
|
|
59
|
+
row?.count ?? 0,
|
|
60
|
+
CSP_RATE_LIMIT,
|
|
61
|
+
CSP_RATE_WINDOW_SECONDS,
|
|
62
|
+
);
|
|
63
|
+
|
|
64
|
+
// `dropped` is what makes shedding visible. Without it a rate-limited estate
|
|
65
|
+
// and a quiet one produce an identical empty csp_reports table, and the
|
|
66
|
+
// difference between "nothing is violating" and "we threw it away" is the
|
|
67
|
+
// whole question this collector exists to answer.
|
|
68
|
+
await db
|
|
69
|
+
.prepare(
|
|
70
|
+
`INSERT INTO csp_report_buckets (bucket_key, count, dropped, window_start)
|
|
71
|
+
VALUES (?, ?, ?, datetime(?, 'unixepoch'))
|
|
72
|
+
ON CONFLICT(bucket_key) DO UPDATE SET
|
|
73
|
+
count = excluded.count,
|
|
74
|
+
dropped = csp_report_buckets.dropped + excluded.dropped,
|
|
75
|
+
window_start = excluded.window_start`,
|
|
76
|
+
)
|
|
77
|
+
.bind(bucketKey, d.nextCount, d.allowed ? 0 : 1, d.nextWindowStart)
|
|
78
|
+
.run();
|
|
79
|
+
|
|
80
|
+
return { allowed: d.allowed };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export async function handleCspReport(request: Request, env: Env): Promise<Response> {
|
|
84
|
+
// 1. Size. Refuse PAST the cap rather than accepting a truncated record.
|
|
85
|
+
// A collector that stores a mangled row past its limit is worse than one
|
|
86
|
+
// that refuses, because the mangled row looks like a real observation.
|
|
87
|
+
// Content-Length is a claim, so it is checked as a cheap early refusal AND
|
|
88
|
+
// the actual bytes are measured after reading; a lying or absent header
|
|
89
|
+
// cannot get a oversized body past the second check.
|
|
90
|
+
const declared = Number(request.headers.get("content-length") ?? "0");
|
|
91
|
+
if (Number.isFinite(declared) && declared > CSP_REPORT_MAX_BYTES) {
|
|
92
|
+
return new Response(null, { status: 413 });
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
let raw: string;
|
|
96
|
+
try {
|
|
97
|
+
raw = await request.text();
|
|
98
|
+
} catch {
|
|
99
|
+
return new Response(null, { status: 400 });
|
|
100
|
+
}
|
|
101
|
+
if (raw.length > CSP_REPORT_MAX_BYTES) {
|
|
102
|
+
return new Response(null, { status: 413 });
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// 2. Parse. Malformed is refused, not stored as an empty row.
|
|
106
|
+
let parsed: unknown;
|
|
107
|
+
try {
|
|
108
|
+
parsed = JSON.parse(raw);
|
|
109
|
+
} catch {
|
|
110
|
+
return new Response(null, { status: 400 });
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// 3. Project to the bounded row. null means neither wire shape was present,
|
|
114
|
+
// which is a malformed report rather than a violation with no detail.
|
|
115
|
+
const row = extractCspReport(parsed);
|
|
116
|
+
if (!row) return new Response(null, { status: 400 });
|
|
117
|
+
|
|
118
|
+
// 4. Rate limit. Keyed on the connecting IP; CF-Connecting-IP is set by the
|
|
119
|
+
// edge and is not client-settable on this path. A missing header buckets
|
|
120
|
+
// to "unknown", which shares one window rather than bypassing the limit.
|
|
121
|
+
const ip = request.headers.get("cf-connecting-ip") || "unknown";
|
|
122
|
+
const { allowed } = await windowFor(env.DB, `csp:${ip}`.slice(0, 128));
|
|
123
|
+
if (!allowed) {
|
|
124
|
+
// 429 rather than a silent 204: a shed report must be distinguishable from
|
|
125
|
+
// an accepted one by the sender too, not only in our own counter.
|
|
126
|
+
return new Response(null, { status: 429 });
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
await env.DB.prepare(
|
|
130
|
+
`INSERT INTO csp_reports
|
|
131
|
+
(document_uri, referrer, violated_directive, effective_directive,
|
|
132
|
+
blocked_uri, disposition, status_code, source_file, line_number, column_number)
|
|
133
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
134
|
+
)
|
|
135
|
+
.bind(
|
|
136
|
+
row.document_uri,
|
|
137
|
+
row.referrer,
|
|
138
|
+
row.violated_directive,
|
|
139
|
+
row.effective_directive,
|
|
140
|
+
row.blocked_uri,
|
|
141
|
+
row.disposition,
|
|
142
|
+
row.status_code,
|
|
143
|
+
row.source_file,
|
|
144
|
+
row.line_number,
|
|
145
|
+
row.column_number,
|
|
146
|
+
)
|
|
147
|
+
.run();
|
|
148
|
+
|
|
149
|
+
// 5. Retention as an executed deletion, not an intention. Prune-on-write
|
|
150
|
+
// needs no cron, no new trigger and no binding, and it cannot drift out of
|
|
151
|
+
// sync with the write path because it IS the write path.
|
|
152
|
+
await env.DB.prepare(
|
|
153
|
+
`DELETE FROM csp_reports WHERE received_at < datetime('now', ?)`,
|
|
154
|
+
)
|
|
155
|
+
.bind(`-${CSP_RETENTION_DAYS} days`)
|
|
156
|
+
.run();
|
|
157
|
+
|
|
158
|
+
return NO_CONTENT();
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// Re-exported so the route table and the tests agree on the cap without a
|
|
162
|
+
// second copy of the number.
|
|
163
|
+
export { CSP_REPORT_MAX_BYTES, CSP_FIELD_CAPS };
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
import type { Env } from "../env";
|
|
6
6
|
import { probeD1Schema } from "../health-schema";
|
|
7
|
+
import { VERSION } from "../version";
|
|
7
8
|
import { json } from "./shared";
|
|
8
9
|
|
|
9
10
|
// ---------- Health checks ----------
|
|
@@ -97,8 +98,12 @@ export async function handleHealthDeep(env: Env): Promise<Response> {
|
|
|
97
98
|
}
|
|
98
99
|
|
|
99
100
|
const allOk = Object.values(checks).every((c) => c.ok);
|
|
101
|
+
// `version` rides on the readiness payload too, and it matters most when this
|
|
102
|
+
// endpoint is answering 503: a readiness probe goes red for reasons that have
|
|
103
|
+
// nothing to do with which build is running, and that is exactly the moment an
|
|
104
|
+
// operator needs to know which build it is.
|
|
100
105
|
return json(
|
|
101
|
-
{ ok: allOk, ts: Date.now(), checks },
|
|
106
|
+
{ ok: allOk, ts: Date.now(), version: VERSION, checks },
|
|
102
107
|
{ status: allOk ? 200 : 503 }
|
|
103
108
|
);
|
|
104
109
|
}
|
|
@@ -340,11 +340,33 @@ export async function retrieveContext(
|
|
|
340
340
|
// 1. user_email mismatch (vectors written under a different identity).
|
|
341
341
|
// 2. With projectId set: matches were real but none of the matched
|
|
342
342
|
// documents are members of the requested project.
|
|
343
|
+
// Two messages, deliberately carrying different things.
|
|
344
|
+
//
|
|
345
|
+
// The Vectorize query above is global: it has no metadata filter, because
|
|
346
|
+
// the tenant scope is the D1 join (see the note at the top of this
|
|
347
|
+
// section, which is why this works without a Vectorize metadata index).
|
|
348
|
+
// So `ids` holds whatever the shared index returned, and vector ids are
|
|
349
|
+
// minted as `${userEmail}:${docId}:${chunkIndex}`. On a deployment with
|
|
350
|
+
// more than one tenant, ids in that list can belong to somebody else --
|
|
351
|
+
// which is precisely the case this branch exists to report on.
|
|
352
|
+
//
|
|
353
|
+
// The operator diagnostic keeps them. It is what makes a silent retrieval
|
|
354
|
+
// failure debuggable, and it goes to a log the operator already owns.
|
|
343
355
|
const idSample = ids.slice(0, 3).join(", ");
|
|
344
356
|
const scope = projectId !== undefined ? ` project_id=${projectId},` : "";
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
357
|
+
console.warn(
|
|
358
|
+
"retrieveContext:",
|
|
359
|
+
`Vectorize returned ${matches.length} matches but D1 join returned 0. user_email='${userEmail}',${scope} sample vector_ids=[${idSample}]. Check whether vectors were upserted under a different user identity, or whether the project has any document members.`,
|
|
360
|
+
);
|
|
361
|
+
|
|
362
|
+
// The caller gets a true statement about their own retrieval and nothing
|
|
363
|
+
// derived from the shared index. Whatever is returned here is handed to
|
|
364
|
+
// the client verbatim as `retrieval_error` (src/routes/chat.ts), so this
|
|
365
|
+
// string is API output rather than a log line, and is written as such.
|
|
366
|
+
const clientMsg = projectId !== undefined
|
|
367
|
+
? "No indexed documents in this project matched the query."
|
|
368
|
+
: "No indexed documents matched the query.";
|
|
369
|
+
return { chunks: [], error: clientMsg };
|
|
348
370
|
}
|
|
349
371
|
|
|
350
372
|
// 4) Merge scores back in, preserve Vectorize ordering. When projectId
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
// - opens the upstream flux socket (env.AI.run({websocket:true})) and bridges
|
|
8
8
|
// audio up / Deepgram events down,
|
|
9
9
|
// - accumulates each committed turn into DO SQLite (hibernation-safe; the
|
|
10
|
-
// in-memory upstream socket is NOT
|
|
10
|
+
// in-memory upstream socket is NOT -- outbound sockets do not hibernate, so
|
|
11
11
|
// we lean on the fact that an active STT session streams audio continuously
|
|
12
12
|
// and never goes idle long enough to hibernate, with a guard if it does),
|
|
13
13
|
// - on close, concatenates the turns and writes one chats row (model_type
|
|
@@ -17,6 +17,7 @@ import { DurableObject } from "cloudflare:workers";
|
|
|
17
17
|
import type { Env } from "./env";
|
|
18
18
|
import { buildTranscript, sanitizeCloseCode } from "./stt-util";
|
|
19
19
|
import { resolveIdentity } from "./auth";
|
|
20
|
+
import { requireAiContext } from "./routes/shared";
|
|
20
21
|
|
|
21
22
|
export const FLUX_STT_MODEL = "@cf/deepgram/flux";
|
|
22
23
|
|
|
@@ -45,6 +46,21 @@ export class SttSession extends DurableObject<Env> {
|
|
|
45
46
|
// src/index.ts. The session cookie rides the same-origin WS upgrade, so
|
|
46
47
|
// resolveIdentity derives the owner the same way as every HTTP route.
|
|
47
48
|
const userEmail = (await resolveIdentity(request, this.env)) ?? "anonymous";
|
|
49
|
+
|
|
50
|
+
// The live-voice socket is an inference path like any other, so it
|
|
51
|
+
// resolves the caller's own gateway credentials before opening anything
|
|
52
|
+
// upstream. This calls requireAiContext -- the same gate every HTTP
|
|
53
|
+
// inference route uses -- rather than restating the condition here, so
|
|
54
|
+
// this path cannot drift away from the others.
|
|
55
|
+
//
|
|
56
|
+
// The upstream flux socket does bypass the gateway TRANSPORT: the binding
|
|
57
|
+
// opens it with { websocket: true }, which the gateway cannot proxy. That
|
|
58
|
+
// is a transport property and carries no authorization meaning. An
|
|
59
|
+
// unconfigured caller is refused here, before any upstream session exists
|
|
60
|
+
// and before this DO records session metadata for it.
|
|
61
|
+
const ctxOrErr = await requireAiContext(this.env, userEmail, { requireCfToken: false });
|
|
62
|
+
if (ctxOrErr instanceof Response) return ctxOrErr;
|
|
63
|
+
|
|
48
64
|
this.ctx.storage.sql.exec(
|
|
49
65
|
`INSERT OR REPLACE INTO meta (k, v) VALUES ('user', ?), ('model', ?), ('started_at', ?)`,
|
|
50
66
|
userEmail,
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
// The version this Worker advertises on its unauthenticated health surfaces.
|
|
2
|
+
//
|
|
3
|
+
// WHY THIS FILE EXISTS: a green deploy workflow proves the UPLOAD succeeded, not that the
|
|
4
|
+
// running Worker is the code you think it is. Without a version on the wire, "is the fix
|
|
5
|
+
// actually serving?" is answerable only with an account-scoped Cloudflare token, from a
|
|
6
|
+
// system separate from the one serving traffic (fleet-chezmoi#1641).
|
|
7
|
+
//
|
|
8
|
+
// WHY A GUARDED LITERAL AND NOT `import pkg from "../package.json"`: importing package.json
|
|
9
|
+
// would bundle the dependency list into a Worker whose whole point here is to disclose one
|
|
10
|
+
// short string, and it would put the manifest on the deployed surface. The literal is a copy
|
|
11
|
+
// -- but it is a copy that CANNOT SHIP WRONG, because tests/version.test.ts reads package.json
|
|
12
|
+
// off disk and derives the expected value from it rather than carrying a second hand-typed
|
|
13
|
+
// copy of the same string.
|
|
14
|
+
//
|
|
15
|
+
// That distinction is the entire point. In prism-mcp the advertised version was a literal and
|
|
16
|
+
// the test asserting it carried a TRANSCRIBED duplicate, so the assertion only ever proved
|
|
17
|
+
// that someone had typed the same thing twice, and a correct version bump went red.
|
|
18
|
+
export const VERSION = "1.0.4";
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import {
|
|
3
|
+
applyCompactToPriorTurns,
|
|
4
|
+
buildCompactSystemBlock,
|
|
5
|
+
formatTurnsForSummary,
|
|
6
|
+
normalizeSummary,
|
|
7
|
+
splitTurnsForCompact,
|
|
8
|
+
COMPACT_SUMMARY_MAX_CHARS,
|
|
9
|
+
DEFAULT_KEEP_RECENT,
|
|
10
|
+
} from "../src/conversation-context";
|
|
11
|
+
|
|
12
|
+
const turns = [
|
|
13
|
+
{ user_input: "hi", output: "hello", turn_index: 0 },
|
|
14
|
+
{ user_input: "what is 2+2", output: "4", turn_index: 1 },
|
|
15
|
+
{ user_input: "and 3+3", output: "6", turn_index: 2 },
|
|
16
|
+
{ user_input: "thanks", output: "anytime", turn_index: 3 },
|
|
17
|
+
];
|
|
18
|
+
|
|
19
|
+
describe("splitTurnsForCompact", () => {
|
|
20
|
+
it("keeps the last N raw and summarizes the rest", () => {
|
|
21
|
+
const { summarize, keep } = splitTurnsForCompact(turns, 2);
|
|
22
|
+
expect(summarize.map((t) => t.turn_index)).toEqual([0, 1]);
|
|
23
|
+
expect(keep.map((t) => t.turn_index)).toEqual([2, 3]);
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
it("summarizes nothing when keep_recent covers the whole thread", () => {
|
|
27
|
+
const { summarize, keep } = splitTurnsForCompact(turns, 10);
|
|
28
|
+
expect(summarize).toEqual([]);
|
|
29
|
+
expect(keep).toHaveLength(4);
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it("default keep matches DEFAULT_KEEP_RECENT (2)", () => {
|
|
33
|
+
expect(DEFAULT_KEEP_RECENT).toBe(2);
|
|
34
|
+
const { keep } = splitTurnsForCompact(turns, DEFAULT_KEEP_RECENT);
|
|
35
|
+
expect(keep).toHaveLength(2);
|
|
36
|
+
});
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
describe("formatTurnsForSummary", () => {
|
|
40
|
+
it("labels user and assistant and separates turns", () => {
|
|
41
|
+
const text = formatTurnsForSummary(turns.slice(0, 2));
|
|
42
|
+
expect(text).toContain("User:\nhi");
|
|
43
|
+
expect(text).toContain("Assistant:\nhello");
|
|
44
|
+
expect(text).toContain("---");
|
|
45
|
+
expect(text).toContain("what is 2+2");
|
|
46
|
+
});
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
describe("buildCompactSystemBlock", () => {
|
|
50
|
+
it("wraps the summary with markers the model can anchor on", () => {
|
|
51
|
+
const block = buildCompactSystemBlock("User prefers brief answers.");
|
|
52
|
+
expect(block).toMatch(/\[Compacted earlier conversation\]/);
|
|
53
|
+
expect(block).toContain("User prefers brief answers.");
|
|
54
|
+
expect(block).toMatch(/\[End compacted context\]/);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it("returns empty for blank summary", () => {
|
|
58
|
+
expect(buildCompactSystemBlock(" ")).toBe("");
|
|
59
|
+
});
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
describe("applyCompactToPriorTurns", () => {
|
|
63
|
+
it("without compact state returns all usable turns", () => {
|
|
64
|
+
const ctx = applyCompactToPriorTurns(turns, null);
|
|
65
|
+
expect(ctx.priorTurns).toHaveLength(4);
|
|
66
|
+
expect(ctx.compactBlock).toBeNull();
|
|
67
|
+
expect(ctx.turnIndex).toBe(4);
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
it("with compact state drops covered turns and injects the block", () => {
|
|
71
|
+
const ctx = applyCompactToPriorTurns(turns, {
|
|
72
|
+
summary: "Discussed arithmetic; answers were short.",
|
|
73
|
+
through_turn_index: 1,
|
|
74
|
+
keep_recent: 2,
|
|
75
|
+
model: "@cf/meta/llama-3.2-3b-instruct",
|
|
76
|
+
updated_at: "2026-08-06T00:00:00Z",
|
|
77
|
+
});
|
|
78
|
+
expect(ctx.priorTurns.map((t) => t.user_input)).toEqual(["and 3+3", "thanks"]);
|
|
79
|
+
expect(ctx.compactBlock).toContain("Discussed arithmetic");
|
|
80
|
+
expect(ctx.turnIndex).toBe(4);
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
it("skips empty/failed turns when building prior pairs", () => {
|
|
84
|
+
const mixed = [
|
|
85
|
+
...turns,
|
|
86
|
+
{ user_input: "oops", output: "", turn_index: 4 },
|
|
87
|
+
];
|
|
88
|
+
const ctx = applyCompactToPriorTurns(mixed, null);
|
|
89
|
+
expect(ctx.priorTurns).toHaveLength(4);
|
|
90
|
+
// Next index still advances past the empty row's index.
|
|
91
|
+
expect(ctx.turnIndex).toBe(5);
|
|
92
|
+
});
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
describe("normalizeSummary", () => {
|
|
96
|
+
it("trims and truncates oversized summaries", () => {
|
|
97
|
+
expect(normalizeSummary(" short ")).toBe("short");
|
|
98
|
+
const long = "x".repeat(COMPACT_SUMMARY_MAX_CHARS + 50);
|
|
99
|
+
const out = normalizeSummary(long);
|
|
100
|
+
expect(out.length).toBeLessThanOrEqual(COMPACT_SUMMARY_MAX_CHARS + 30);
|
|
101
|
+
expect(out).toContain("[summary truncated]");
|
|
102
|
+
});
|
|
103
|
+
});
|