@skyphusion/create-prism 1.3.0 → 1.3.1

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skyphusion/create-prism",
3
- "version": "1.3.0",
3
+ "version": "1.3.1",
4
4
  "description": "Scaffold a new prism deployment: a multimodal AI playground on Cloudflare Workers.",
5
5
  "license": "AGPL-3.0-only",
6
6
  "author": "Conrad Rockenhaus",
@@ -247,3 +247,33 @@ var.
247
247
  bytes would share an index entry. The D1 join still scopes their results correctly, so the worst case
248
248
  for those users is the old global behaviour, not a disclosure.
249
249
 
250
+
251
+ ## Vector ids without identity (prism#232)
252
+
253
+ **Why.** Before prism#232, ingest minted each Vectorize vector id as `<identity>:<document id>:<chunk
254
+ index>`. In access mode the identity is the raw email address, so every id in the index carried it.
255
+ Vector ids are visible outside D1: in the index, in query results, and in any tool that lists or
256
+ exports ids. New ingests mint a random id (`c_` plus 32 hex digits, `src/vector-id.ts`). Ownership
257
+ stays in the vector's `user_email` metadata and the D1 `chunks` row.
258
+
259
+ **Nothing breaks if you do nothing.** Every reader (retrieval, document delete, account delete) looks
260
+ ids up through D1 `chunks.vector_id`, so old ids keep working next to new ones. Public-mode ids carry
261
+ the opaque `usr_` id, not an email, and are left alone.
262
+
263
+ **To remove the emails from existing ids** (access-mode deployments only), re-key them. The script
264
+ selects the D1 rows whose `vector_id` contains `@`, writes each vector under a new random id with the
265
+ same values and metadata (nothing is re-embedded), points the D1 row at the new id, then deletes the old
266
+ id. It prints counts only, never an id or a value, and is safe to re-run.
267
+
268
+ ```bash
269
+ CLOUDFLARE_API_TOKEN=... CLOUDFLARE_ACCOUNT_ID=... \
270
+ node scripts/vectorize-rekey-vector-ids.mjs --index skyphusion-llm-vec --d1 <D1 database uuid> --dry-run
271
+ CLOUDFLARE_API_TOKEN=... CLOUDFLARE_ACCOUNT_ID=... \
272
+ node scripts/vectorize-rekey-vector-ids.mjs --index skyphusion-llm-vec --d1 <D1 database uuid>
273
+ ```
274
+
275
+ The token needs Vectorize Edit and D1 Edit. `legacy` in the dry-run output is the number of
276
+ email-bearing ids. Exit 0 means every one was re-keyed. Exit 1 means some D1 ids had no vector (`gaps`)
277
+ or a row changed during the run (`conflicts`). Exit 2 means it refused or could not read. Vectorize
278
+ applies writes asynchronously, so retrieval for a re-keyed chunk can miss for a few seconds after its
279
+ batch; run it in a quiet window.
@@ -8,6 +8,7 @@ import { parseDiscordExport, chunkDiscordMessages } from "../discord";
8
8
  import { json, getUserEmail, r2Put, r2DeleteSafe } from "./shared";
9
9
  import type { ChatRequest } from "./shared";
10
10
  import { embedBatch, DOC_MAX_BYTES, EMBED_BATCH_SIZE } from "./rag";
11
+ import { mintVectorId } from "../vector-id";
11
12
 
12
13
  // v0.20.0: project + project_documents join. A project groups documents
13
14
  // (and in v0.20.1, conversations) under a shared system_prompt and
@@ -121,7 +122,7 @@ export async function resolveProjectForChat(
121
122
  .first<ProjectRow>();
122
123
  if (!project) {
123
124
  console.warn(
124
- `Chat referenced unknown project_id=${body.project_id} for user_email='${userEmail}'; ` +
125
+ `Chat referenced unknown project_id=${body.project_id} (not found for this caller); ` +
125
126
  `falling back to no-project semantics (no system prompt fallback, no retrieval scoping).`
126
127
  );
127
128
  } else {
@@ -483,8 +484,8 @@ export async function handleDiscordImport(request: Request, env: Env, projectId:
483
484
  await env.DB.batch(stmts);
484
485
  }
485
486
 
486
- // Embed chunks and upsert to Vectorize. vector_id scheme matches documents:
487
- // `${userEmail}:${docId}:${chunkIndex}`.
487
+ // Embed chunks and upsert to Vectorize. Vector ids are random and carry no
488
+ // identity, the same as documents (src/vector-id.ts, prism#232).
488
489
  const vectorIdsWritten: string[] = [];
489
490
  const chunkRowsToInsert: {
490
491
  chunk_index: number;
@@ -505,7 +506,7 @@ export async function handleDiscordImport(request: Request, env: Env, projectId:
505
506
  }
506
507
  const payload = batch.map((c, i) => {
507
508
  const idx = b + i;
508
- const vid = `${userEmail}:${docId}:${idx}`;
509
+ const vid = mintVectorId();
509
510
  chunkRowsToInsert.push({
510
511
  chunk_index: idx,
511
512
  text: c.text,
@@ -13,6 +13,7 @@ import { requireGatewayCredentials } from "../gateway-credentials";
13
13
  import { chunkText } from "../chunking";
14
14
  import { askSkyphusionSearch } from "../skyphusion-search";
15
15
  import { r2Put, r2DeleteSafe } from "./shared";
16
+ import { mintVectorId } from "../vector-id";
16
17
  import type { RetrievedChunk, RetrievedWebResult } from "./shared";
17
18
 
18
19
  // ---------- RAG: document ingestion (Pass 1) ----------
@@ -255,6 +256,26 @@ export function vecMetadataFilterOn(env: Pick<Env, "VEC_METADATA_FILTER">): bool
255
256
  return v === "on" || v === "1" || v === "true";
256
257
  }
257
258
 
259
+ // Ownership census for the zero-join diagnostic (prism#233). Returns a log
260
+ // fragment of counts only: no identity and no vector id ever leaves here.
261
+ async function zeroJoinCensus(env: Env, userEmail: string, ids: string[]): Promise<string> {
262
+ try {
263
+ const placeholders = ids.map(() => "?").join(",");
264
+ const row = await env.DB.prepare(
265
+ `SELECT COUNT(*) AS held, COALESCE(SUM(user_email = ?), 0) AS own
266
+ FROM chunks WHERE vector_id IN (${placeholders})`
267
+ )
268
+ .bind(userEmail, ...ids)
269
+ .first<{ held: number; own: number }>();
270
+ if (!row) return "census=unavailable";
271
+ const held = Number(row.held) || 0;
272
+ const own = Number(row.own) || 0;
273
+ return `held_by_caller=${own} held_by_other_users=${held - own} not_in_d1=${Math.max(0, ids.length - held)}`;
274
+ } catch {
275
+ return "census=unavailable";
276
+ }
277
+ }
278
+
258
279
  export async function retrieveContext(
259
280
  env: Env,
260
281
  userEmail: string,
@@ -357,21 +378,23 @@ export async function retrieveContext(
357
378
  // documents are members of the requested project.
358
379
  // Two messages, deliberately carrying different things.
359
380
  //
360
- // The Vectorize query above is global: it has no metadata filter, because
361
- // the tenant scope is the D1 join (see the note at the top of this
362
- // section, which is why this works without a Vectorize metadata index).
363
- // So `ids` holds whatever the shared index returned, and vector ids are
364
- // minted as `${userEmail}:${docId}:${chunkIndex}`. On a deployment with
365
- // more than one tenant, ids in that list can belong to somebody else --
366
- // which is precisely the case this branch exists to report on.
367
- //
368
- // The operator diagnostic keeps them. It is what makes a silent retrieval
369
- // failure debuggable, and it goes to a log the operator already owns.
370
- const idSample = ids.slice(0, 3).join(", ");
371
- const scope = projectId !== undefined ? ` project_id=${projectId},` : "";
381
+ // OPERATOR LOG (prism#233): counts and opaque row ids only, never an
382
+ // identity. The Vectorize query can be global (VEC_METADATA_FILTER off),
383
+ // so the matched ids can belong to other users, and pre-prism#232 ids
384
+ // embed an email. Neither the ids nor the caller's identity are logged.
385
+ // An unkeyed hash of an email is not a substitute: it can be reversed by
386
+ // hashing candidate addresses. The census below answers the question the
387
+ // old log was for ("were these vectors written under another identity?")
388
+ // with counts: how many matched ids D1 holds for this caller, for other
389
+ // users, and not at all.
390
+ const census = await zeroJoinCensus(env, userEmail, ids);
391
+ const scope = projectId !== undefined ? ` project_id=${projectId}` : "";
372
392
  console.warn(
373
393
  "retrieveContext:",
374
- `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.`,
394
+ `zero-join matches=${matches.length}${scope} ${census}. ` +
395
+ "held_by_other_users > 0: vectors were written under a different identity. " +
396
+ "held_by_caller > 0 with a project: the matched documents are not members of the project. " +
397
+ "not_in_d1 > 0: vectors with no D1 chunk row.",
375
398
  );
376
399
 
377
400
  // The caller gets a true statement about their own retrieval and nothing
@@ -660,7 +683,7 @@ export async function ingestDocument(env: Env, userEmail: string, filename: stri
660
683
  // Store raw bytes in R2 for audit / future re-processing.
661
684
  const r2Key = await r2Put(env, "in", mime, bytes, userEmail);
662
685
 
663
- // Insert document row first so we have its ID for vector_id generation.
686
+ // Insert document row first so we have its ID for the chunk metadata.
664
687
  const docInsert = await env.DB.prepare(
665
688
  `INSERT INTO documents
666
689
  (user_email, filename, mime, r2_key, size_bytes, total_chars, chunk_count)
@@ -677,7 +700,7 @@ export async function ingestDocument(env: Env, userEmail: string, filename: stri
677
700
 
678
701
  // Embed in batches and upsert to Vectorize. We tag every vector with
679
702
  // user_email + document_id so we can filter on retrieval and clean up on delete.
680
- // Vector IDs are scoped: `${userEmail}:${docId}:${chunkIndex}`.
703
+ // Vector ids are random and carry no identity (src/vector-id.ts, prism#232).
681
704
  const vectorIdsWritten: string[] = [];
682
705
  const chunkRowsToInsert: {
683
706
  chunk_index: number;
@@ -697,7 +720,7 @@ export async function ingestDocument(env: Env, userEmail: string, filename: stri
697
720
 
698
721
  const vectorizePayload = batch.map((c, i) => {
699
722
  const idx = b + i;
700
- const vid = `${userEmail}:${docId}:${idx}`;
723
+ const vid = mintVectorId();
701
724
  chunkRowsToInsert.push({
702
725
  chunk_index: idx,
703
726
  text: c.text,
@@ -0,0 +1,27 @@
1
+ // Vectorize vector ids for RAG chunks (prism#232).
2
+ //
3
+ // A vector id is visible outside D1: in the Vectorize index, in query results, and in any tool
4
+ // that lists or exports ids. So an id must not carry who owns the vector. Before prism#232 the
5
+ // id was `${userEmail}:${docId}:${chunkIndex}`, which put the raw email into every id in access
6
+ // mode. Ownership is carried by the vector's `user_email` metadata (retrieval filters on it) and
7
+ // by the D1 `chunks` row, never by the id.
8
+ //
9
+ // The new id is random: `c_` plus 32 hex digits from crypto.randomUUID(). It is 34 bytes, well
10
+ // under the Vectorize id limit, and it is stored in `chunks.vector_id`, which every reader
11
+ // (retrieval join, document delete, account delete) already uses as the source of truth. So
12
+ // old-format ids keep working without any change on the read side.
13
+
14
+ /** Prefix of every vector id minted after prism#232. */
15
+ export const VECTOR_ID_PREFIX = "c_";
16
+
17
+ const NEW_FORMAT = /^c_[0-9a-f]{32}$/;
18
+
19
+ /** Mint a fresh, non-identifying vector id. */
20
+ export function mintVectorId(): string {
21
+ return VECTOR_ID_PREFIX + crypto.randomUUID().replace(/-/g, "");
22
+ }
23
+
24
+ /** True for an id in the post-prism#232 random format. */
25
+ export function isOpaqueVectorId(id: string): boolean {
26
+ return NEW_FORMAT.test(id);
27
+ }
@@ -15,4 +15,4 @@
15
15
  // That distinction is the entire point. In prism-mcp the advertised version was a literal and
16
16
  // the test asserting it carried a TRANSCRIBED duplicate, so the assertion only ever proved
17
17
  // that someone had typed the same thing twice, and a correct version bump went red.
18
- export const VERSION = "1.3.0";
18
+ export const VERSION = "1.3.1";
@@ -0,0 +1,88 @@
1
+ // prism#233: operator logs never carry a user identity.
2
+ //
3
+ // Two layers. A behavioural test drives a shipped log path with an access-mode identity. A source
4
+ // guard reads every console.* call in src/ (the whole argument list, across lines) and fails if it
5
+ // interpolates an identity variable. The guard is a string match, so it catches the common shape
6
+ // (`${userEmail}` in a log template), not every possible leak; the behavioural tests are the proof
7
+ // for the paths they drive.
8
+
9
+ import { describe, it, expect, vi, afterEach } from "vitest";
10
+ import { readdirSync, readFileSync, statSync } from "node:fs";
11
+ import { join } from "node:path";
12
+ import { resolveProjectForChat } from "../src/routes/projects";
13
+ import type { Env } from "../src/env";
14
+
15
+ const EMAIL = "carol@example.net";
16
+
17
+ afterEach(() => vi.restoreAllMocks());
18
+
19
+ /** Every console.* call in `text`, with its full argument list (balanced parens). */
20
+ export function consoleCalls(text: string): string[] {
21
+ const out: string[] = [];
22
+ const re = /console\.(?:warn|log|error|info|debug)\(/g;
23
+ let m: RegExpExecArray | null;
24
+ while ((m = re.exec(text))) {
25
+ let depth = 1;
26
+ let i = m.index + m[0].length;
27
+ for (; i < text.length && depth > 0; i++) {
28
+ if (text[i] === "(") depth++;
29
+ else if (text[i] === ")") depth--;
30
+ }
31
+ out.push(text.slice(m.index, i));
32
+ }
33
+ return out;
34
+ }
35
+
36
+ const IDENTITY_IN_LOG = /\$\{\s*(?:userEmail|email|identity|user_email)\b|user_email='/;
37
+
38
+ function srcFiles(dir: string): string[] {
39
+ return readdirSync(dir).flatMap((name) => {
40
+ const p = join(dir, name);
41
+ return statSync(p).isDirectory() ? srcFiles(p) : p.endsWith(".ts") ? [p] : [];
42
+ });
43
+ }
44
+
45
+ describe("source guard: no console.* call interpolates an identity", () => {
46
+ const files = srcFiles(join(__dirname, "..", "src"));
47
+
48
+ it("scans a real denominator", () => {
49
+ const calls = files.flatMap((f) => consoleCalls(readFileSync(f, "utf8")));
50
+ expect(files.length).toBeGreaterThan(20);
51
+ expect(calls.length).toBeGreaterThanOrEqual(5);
52
+ });
53
+
54
+ it("finds none in src/", () => {
55
+ const hits = files.flatMap((f) =>
56
+ consoleCalls(readFileSync(f, "utf8"))
57
+ .filter((c) => IDENTITY_IN_LOG.test(c))
58
+ .map((c) => `${f}: ${c.slice(0, 120)}`),
59
+ );
60
+ expect(hits).toEqual([]);
61
+ });
62
+
63
+ it("NEGATIVE CONTROL: goes red on both pre-prism#233 log shapes, across lines", () => {
64
+ const zeroJoin = "console.warn(\n \"retrieveContext:\",\n `Vectorize returned ${n} matches. user_email='${userEmail}', sample`,\n);";
65
+ const project = "console.warn(\n `Chat referenced unknown project_id=${id} for user_email='${userEmail}'; ` +\n `falling back`\n);";
66
+ for (const src of [zeroJoin, project]) {
67
+ const calls = consoleCalls(src);
68
+ expect(calls).toHaveLength(1);
69
+ expect(IDENTITY_IN_LOG.test(calls[0])).toBe(true);
70
+ }
71
+ expect(IDENTITY_IN_LOG.test("console.warn(`zero-join matches=${n} held_by_caller=${own}`)")).toBe(false);
72
+ });
73
+ });
74
+
75
+ describe("resolveProjectForChat: unknown project log", () => {
76
+ it("names the opaque project id and not the caller", async () => {
77
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
78
+ const env = {
79
+ DB: { prepare: () => ({ bind: () => ({ first: async () => null }) }) },
80
+ } as unknown as Env;
81
+ const r = await resolveProjectForChat(env, EMAIL, { project_id: 77 } as never);
82
+ expect(r.project).toBeNull();
83
+ const log = warn.mock.calls.map((c) => c.join(" ")).join("\n");
84
+ expect(log).not.toContain(EMAIL);
85
+ expect(log).not.toMatch(/@/);
86
+ expect(log).toContain("project_id=77");
87
+ });
88
+ });
@@ -1,18 +1,14 @@
1
- // The zero-join retrieval diagnostic (skyphusion-labs/fleet-chezmoi#1608).
1
+ // The zero-join retrieval diagnostic (skyphusion-labs/fleet-chezmoi#1608, prism#233).
2
2
  //
3
- // retrieveContext queries Vectorize globally -- no metadata filter, because the
4
- // tenant scope is the D1 join (see the design note above retrieveContext, which
5
- // is deliberate: it avoids requiring a Vectorize metadata index). So the raw
6
- // Vectorize result legitimately contains vector ids belonging to other tenants,
7
- // and vector ids are minted as `${userEmail}:${docId}:${chunkIndex}`.
3
+ // With VEC_METADATA_FILTER off, retrieveContext queries Vectorize globally and scopes by user in the
4
+ // D1 join. So the raw Vectorize result can hold vector ids belonging to other users, and
5
+ // pre-prism#232 ids embed an email. The zero-join branch is where those ids sit next to two outputs:
8
6
  //
9
- // That makes the zero-join branch the one place where foreign identifiers are
10
- // in scope next to a string that gets returned to the caller. These assert the
11
- // split: the operator log keeps the full diagnostic, the client half carries
12
- // nothing derived from the shared index.
7
+ // - the string returned to the caller (fleet-chezmoi#1608): nothing derived from the shared index.
8
+ // - the operator log (prism#233): counts and opaque row ids only. No caller identity, no foreign
9
+ // identity, no vector id.
13
10
  //
14
- // Only env.AI / env.VEC / env.DB are stubbed -- the un-stubbable seams.
15
- // Everything between them is the real shipped retrieveContext.
11
+ // Only env.AI / env.VEC / env.DB are stubbed. Everything between them is the shipped retrieveContext.
16
12
 
17
13
  import { describe, it, expect, vi, afterEach } from "vitest";
18
14
  import { retrieveContext } from "../src/routes/rag";
@@ -25,33 +21,41 @@ const FOREIGN_IDS = [
25
21
  "bob@example.com:99:2",
26
22
  ];
27
23
 
28
- // A caller-visible string must contain none of these substrings. Kept as the
29
- // identity half of the vector id rather than the whole id, so the assertion
30
- // still fires if only the identity survives some future re-formatting.
24
+ // Neither output may contain any of these. Kept as the identity half of each id as well as the whole
25
+ // id, so the assertion still fires if only the identity survives some future re-formatting.
31
26
  const FOREIGN_IDENTITIES = ["victim@example.com", "usr_0123456789abcdef01234567", "bob@example.com"];
27
+ const FORBIDDEN_IN_LOG = [CALLER, ...FOREIGN_IDS, ...FOREIGN_IDENTITIES];
32
28
 
33
- function fakeEnv(): Env {
34
- return {
29
+ type Census = { held: number; own: number } | "throw" | null;
30
+
31
+ function fakeEnv(census: Census = { held: 2, own: 0 }) {
32
+ const vecReturned: string[] = [];
33
+ const env = {
35
34
  AI: {
36
35
  run: async () => ({ shape: [1, 3], data: [[0.1, 0.2, 0.3]] }),
37
36
  },
38
37
  VEC: {
39
- query: async () => ({
40
- matches: FOREIGN_IDS.map((id, i) => ({ id, score: 0.9 - i * 0.01 })),
41
- }),
38
+ query: async () => {
39
+ vecReturned.push(...FOREIGN_IDS);
40
+ return { matches: FOREIGN_IDS.map((id, i) => ({ id, score: 0.9 - i * 0.01 })) };
41
+ },
42
42
  },
43
43
  DB: {
44
44
  prepare(sql: string) {
45
45
  const isPrefs = sql.includes("user_prefs");
46
+ const isCensus = sql.includes("COUNT(*) AS held");
46
47
  return {
47
48
  bind() {
48
49
  return {
49
- // loadUserPrefs -> gateway credentials, so embedBatch proceeds.
50
50
  async first() {
51
- return isPrefs ? { prefs_json: JSON.stringify({ gateway_id: "alice-gw" }) } : null;
51
+ if (isPrefs) return { prefs_json: JSON.stringify({ gateway_id: "alice-gw" }) };
52
+ if (isCensus) {
53
+ if (census === "throw") throw new Error(`D1 down for ${CALLER}`);
54
+ return census;
55
+ }
56
+ return null;
52
57
  },
53
- // The tenant-scoped join finds none of the foreign vectors,
54
- // which is the branch under test.
58
+ // The tenant-scoped join finds none of the matched vectors: the branch under test.
55
59
  async all() {
56
60
  return { results: [] };
57
61
  },
@@ -61,82 +65,87 @@ function fakeEnv(): Env {
61
65
  },
62
66
  },
63
67
  } as unknown as Env;
68
+ return { env, vecReturned };
69
+ }
70
+
71
+ function logged(warn: ReturnType<typeof vi.spyOn>): string {
72
+ return warn.mock.calls.map((c) => c.join(" ")).join("\n");
64
73
  }
65
74
 
66
75
  afterEach(() => {
67
76
  vi.restoreAllMocks();
68
77
  });
69
78
 
70
- describe("retrieveContext zero-join diagnostic", () => {
71
- it("returns a caller-visible message carrying no foreign identity", async () => {
72
- const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
73
- const { chunks, error } = await retrieveContext(fakeEnv(), CALLER, "quarterly revenue");
74
-
79
+ describe("retrieveContext zero-join: the caller-visible message", () => {
80
+ it("carries no foreign identity", async () => {
81
+ vi.spyOn(console, "warn").mockImplementation(() => {});
82
+ const { env } = fakeEnv();
83
+ const { chunks, error } = await retrieveContext(env, CALLER, "quarterly revenue");
75
84
  expect(chunks).toEqual([]);
76
-
77
- // ORDER IS LOAD-BEARING. Do not swap these two blocks.
78
- //
79
- // The disclosure assertion runs FIRST so that it is the assertion that
80
- // fires when the defect is present. With the pin first, driving the
81
- // pre-fix code (888e6bb reversed) reddened this test on the pin's
82
- // `toBe` line and short-circuited, so the loop below never executed:
83
- // the suite detected the defect, but the assertion that names it had
84
- // never been shown capable of failing.
85
- for (const identity of FOREIGN_IDENTITIES) {
86
- expect(error).not.toContain(identity);
87
- }
88
-
89
- // Pin the exact branch SECOND. This is the anti-vacuity control: on any
90
- // earlier failure path ("embed failed: ...", "vectorize query failed:
91
- // ...") the loop above passes for free, because those strings are also
92
- // free of foreign identities and are not the case under test. Running it
93
- // after preserves that guarantee while leaving the loop reachable.
85
+ // Disclosure assertion first, so it is the one that fires under the defect; the branch pin
86
+ // second, as the anti-vacuity control (earlier failure paths are also identity-free).
87
+ for (const identity of FOREIGN_IDENTITIES) expect(error).not.toContain(identity);
94
88
  expect(error).toBe("No indexed documents matched the query.");
89
+ });
95
90
 
96
- // Control: the harness really did feed foreign ids in, so the absence
97
- // above is a redaction rather than an empty input.
98
- expect(warn).toHaveBeenCalled();
99
- const logged = warn.mock.calls.map((c) => c.join(" ")).join("\n");
100
- for (const identity of FOREIGN_IDENTITIES) {
101
- expect(logged).toContain(identity);
102
- }
91
+ it("is scoped the same way with a project", async () => {
92
+ vi.spyOn(console, "warn").mockImplementation(() => {});
93
+ const { env } = fakeEnv();
94
+ const { error } = await retrieveContext(env, CALLER, "quarterly revenue", 5, 42);
95
+ for (const identity of FOREIGN_IDENTITIES) expect(error).not.toContain(identity);
96
+ expect(error).toBe("No indexed documents in this project matched the query.");
103
97
  });
98
+ });
104
99
 
105
- it("keeps the operator diagnostic intact, not deleted", async () => {
106
- // The diagnostic is the thing that makes a silent retrieval failure
107
- // debuggable. The fix is a split, not a removal, and this is what would
108
- // fail if a later cleanup "simplified" the console.warn away.
100
+ describe("retrieveContext zero-join: the operator log (prism#233)", () => {
101
+ it("carries no caller identity, no foreign identity and no vector id", async () => {
109
102
  const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
110
- await retrieveContext(fakeEnv(), CALLER, "quarterly revenue");
103
+ const { env, vecReturned } = fakeEnv();
104
+ await retrieveContext(env, CALLER, "quarterly revenue");
105
+ const log = logged(warn);
106
+ // Disclosure assertion first (see above).
107
+ for (const s of FORBIDDEN_IN_LOG) expect(log, s).not.toContain(s);
108
+ expect(log).not.toMatch(/@/);
109
+ // Anti-vacuity: the log was written, on this branch, after the identities were really fed in.
110
+ expect(log).toContain("zero-join matches=3");
111
+ expect(vecReturned).toEqual(FOREIGN_IDS);
112
+ });
111
113
 
112
- const logged = warn.mock.calls.map((c) => c.join(" ")).join("\n");
113
- expect(logged).toContain("sample vector_ids=[");
114
- expect(logged).toContain("D1 join returned 0");
115
- expect(logged).toContain(CALLER);
114
+ it("keeps the diagnostic: counts say the vectors were written under another identity", async () => {
115
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
116
+ const { env } = fakeEnv({ held: 2, own: 0 });
117
+ await retrieveContext(env, CALLER, "quarterly revenue");
118
+ expect(logged(warn)).toContain("matches=3 held_by_caller=0 held_by_other_users=2 not_in_d1=1");
116
119
  });
117
120
 
118
- it("scopes the project-filtered message the same way", async () => {
121
+ it("with a project: opaque project id and the caller-owned count, still no identity", async () => {
119
122
  const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
120
- const { error } = await retrieveContext(fakeEnv(), CALLER, "quarterly revenue", 5, 42);
123
+ const { env } = fakeEnv({ held: 3, own: 3 });
124
+ await retrieveContext(env, CALLER, "quarterly revenue", 5, 42);
125
+ const log = logged(warn);
126
+ for (const s of FORBIDDEN_IN_LOG) expect(log, s).not.toContain(s);
127
+ expect(log).toContain("matches=3 project_id=42 held_by_caller=3 held_by_other_users=0 not_in_d1=0");
128
+ });
121
129
 
122
- // Same ordering rule as above: disclosure assertion first so it is
123
- // reachable under the defect, branch pin second as the anti-vacuity
124
- // control.
125
- for (const identity of FOREIGN_IDENTITIES) {
126
- expect(error).not.toContain(identity);
127
- }
128
- expect(error).toBe("No indexed documents in this project matched the query.");
129
- expect(warn).toHaveBeenCalled();
130
+ it("a failed census logs census=unavailable, and its error text (which names the caller) is not logged", async () => {
131
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
132
+ const { env } = fakeEnv("throw");
133
+ await retrieveContext(env, CALLER, "quarterly revenue");
134
+ const log = logged(warn);
135
+ for (const s of FORBIDDEN_IN_LOG) expect(log, s).not.toContain(s);
136
+ expect(log).toContain("zero-join matches=3 census=unavailable");
137
+ });
138
+ });
139
+
140
+ describe("NEGATIVE CONTROL", () => {
141
+ it("the log check goes red on a line shaped like the pre-prism#233 diagnostic", () => {
142
+ const old = `Vectorize returned 3 matches but D1 join returned 0. user_email='${CALLER}', sample vector_ids=[${FOREIGN_IDS.join(", ")}].`;
143
+ expect(FORBIDDEN_IN_LOG.some((s) => old.includes(s))).toBe(true);
130
144
  });
131
145
 
132
- it("harness control: the fixture really does supply foreign ids", () => {
133
- // If FOREIGN_IDS were ever emptied, every not-toContain assertion above
134
- // would pass while testing nothing.
146
+ it("the fixture really does supply foreign ids", () => {
135
147
  expect(FOREIGN_IDS.length).toBeGreaterThan(0);
136
148
  expect(FOREIGN_IDENTITIES.length).toBe(FOREIGN_IDS.length);
137
- for (const id of FOREIGN_IDS) {
138
- expect(id).toContain(":");
139
- expect(id.split(":")[0]).not.toBe(CALLER);
140
- }
149
+ for (const id of FOREIGN_IDS) expect(id.split(":")[0]).not.toBe(CALLER);
141
150
  });
142
151
  });
@@ -0,0 +1,154 @@
1
+ // prism#232: RAG vector ids must not carry the owner's identity.
2
+ //
3
+ // Both mint sites are driven through the shipped functions: ingestDocument (upload and ZIP import)
4
+ // and handleDiscordImport (project Discord import). Only env.AI / env.VEC / env.DB / env.R2 are
5
+ // stubbed, plus the request identity. The caller is an access-mode identity (a raw email), which is
6
+ // the case the issue is about.
7
+
8
+ import { describe, it, expect, vi } from "vitest";
9
+
10
+ const EMAIL = "alice.example@example.org";
11
+
12
+ vi.mock("../src/routes/shared", async (orig) => {
13
+ const real = await orig<typeof import("../src/routes/shared")>();
14
+ return { ...real, getUserEmail: async () => EMAIL };
15
+ });
16
+
17
+ import { ingestDocument } from "../src/routes/rag";
18
+ import { handleDiscordImport } from "../src/routes/projects";
19
+ import { mintVectorId, isOpaqueVectorId } from "../src/vector-id";
20
+ import { mintVectorId as scriptMint } from "../scripts/vectorize-rekey-vector-ids.mjs";
21
+ import type { Env } from "../src/env";
22
+
23
+ interface Upserted {
24
+ id: string;
25
+ metadata?: Record<string, unknown>;
26
+ }
27
+
28
+ /** Fake bindings: records every Vectorize upsert and every D1 statement with its bound args. */
29
+ function fakeEnv() {
30
+ const upserts: Upserted[] = [];
31
+ const statements: { sql: string; args: unknown[] }[] = [];
32
+ const stmt = (sql: string, args: unknown[] = []) => ({
33
+ sql,
34
+ args,
35
+ bind: (...a: unknown[]) => stmt(sql, a),
36
+ async first() {
37
+ statements.push({ sql, args });
38
+ if (sql.includes("user_prefs")) return { prefs_json: JSON.stringify({ gateway_id: "gw" }) };
39
+ if (sql.includes("RETURNING id")) return { id: 7, created_at: "2026-11-12 00:00:00" };
40
+ if (sql.includes("FROM projects")) return { id: 3 };
41
+ return null;
42
+ },
43
+ async run() {
44
+ statements.push({ sql, args });
45
+ return { meta: { changes: 1 } };
46
+ },
47
+ async all() {
48
+ statements.push({ sql, args });
49
+ return { results: [] };
50
+ },
51
+ });
52
+ const env = {
53
+ AI: {
54
+ run: async (_m: string, input: { text: string[] }) => ({
55
+ shape: [input.text.length, 3],
56
+ data: input.text.map(() => [0.1, 0.2, 0.3]),
57
+ }),
58
+ },
59
+ VEC: {
60
+ upsert: async (vs: Upserted[]) => {
61
+ upserts.push(...vs);
62
+ return { mutationId: "m" };
63
+ },
64
+ deleteByIds: async () => ({ mutationId: "m" }),
65
+ },
66
+ R2: { put: async () => ({}), delete: async () => {} },
67
+ DB: {
68
+ prepare: (sql: string) => stmt(sql),
69
+ batch: async (ss: { sql: string; args: unknown[] }[]) => {
70
+ for (const s of ss) statements.push({ sql: s.sql, args: s.args });
71
+ return ss.map(() => ({ meta: { changes: 1 } }));
72
+ },
73
+ },
74
+ } as unknown as Env;
75
+ const chunkRowVectorIds = () =>
76
+ statements.filter((s) => s.sql.includes("INSERT INTO chunks")).map((s) => String(s.args[4]));
77
+ return { env, upserts, chunkRowVectorIds };
78
+ }
79
+
80
+ /** The check under test. It must be able to go red: see the negative control below. */
81
+ function carriesIdentity(id: string, identity: string): boolean {
82
+ return id.includes(identity) || id.includes("@");
83
+ }
84
+
85
+ describe("mintVectorId", () => {
86
+ it("is c_ plus 32 hex digits, unique per call, and carries no @", () => {
87
+ const ids = new Set(Array.from({ length: 200 }, () => mintVectorId()));
88
+ expect(ids.size).toBe(200);
89
+ for (const id of ids) {
90
+ expect(isOpaqueVectorId(id), id).toBe(true);
91
+ expect(id.length).toBe(34);
92
+ expect(id).not.toContain("@");
93
+ }
94
+ });
95
+
96
+ it("the re-key script mints the same format as the worker", () => {
97
+ expect(isOpaqueVectorId(scriptMint())).toBe(true);
98
+ });
99
+ });
100
+
101
+ describe("NEGATIVE CONTROL: the identity check can go red", () => {
102
+ it("flags the pre-prism#232 id shape", () => {
103
+ expect(carriesIdentity(`${EMAIL}:7:0`, EMAIL)).toBe(true);
104
+ expect(isOpaqueVectorId(`${EMAIL}:7:0`)).toBe(false);
105
+ expect(carriesIdentity(mintVectorId(), EMAIL)).toBe(false);
106
+ });
107
+ });
108
+
109
+ describe("ingestDocument (upload, ZIP import)", () => {
110
+ it("writes vector ids with no identity, the same id to D1, and keeps ownership in metadata", async () => {
111
+ const { env, upserts, chunkRowVectorIds } = fakeEnv();
112
+ const text = "Paragraph one about the shaft.\n\n".repeat(60);
113
+ const r = await ingestDocument(env, EMAIL, "notes.txt", "text/plain", new TextEncoder().encode(text));
114
+ expect(r.ok).toBe(true);
115
+ expect(upserts.length).toBeGreaterThan(1);
116
+ for (const v of upserts) {
117
+ expect(carriesIdentity(v.id, EMAIL), v.id).toBe(false);
118
+ expect(isOpaqueVectorId(v.id), v.id).toBe(true);
119
+ expect(v.metadata?.user_email).toBe(EMAIL);
120
+ }
121
+ expect(chunkRowVectorIds()).toEqual(upserts.map((v) => v.id));
122
+ });
123
+ });
124
+
125
+ describe("handleDiscordImport (project Discord import)", () => {
126
+ it("writes vector ids with no identity, the same id to D1, and keeps ownership in metadata", async () => {
127
+ const { env, upserts, chunkRowVectorIds } = fakeEnv();
128
+ const exportJson = {
129
+ guild: { id: "1", name: "G" },
130
+ channel: { id: "10", type: "GuildTextChat", category: "c", name: "general", topic: null },
131
+ messages: Array.from({ length: 6 }, (_, i) => ({
132
+ id: String(100 + i),
133
+ type: "Default",
134
+ timestamp: new Date(Date.UTC(2024, 0, 15, 12, i * 30)).toISOString(),
135
+ content: `message ${i} about the transit hub`,
136
+ author: { id: "a", name: "alice", discriminator: "0", nickname: null, isBot: false },
137
+ })),
138
+ };
139
+ const data = Buffer.from(JSON.stringify(exportJson)).toString("base64");
140
+ const req = new Request("https://x/api/projects/3/discord", {
141
+ method: "POST",
142
+ body: JSON.stringify({ filename: "export.json", data }),
143
+ });
144
+ const res = await handleDiscordImport(req, env, 3);
145
+ expect(res.status).toBeLessThan(300);
146
+ expect(upserts.length).toBeGreaterThan(0);
147
+ for (const v of upserts) {
148
+ expect(carriesIdentity(v.id, EMAIL), v.id).toBe(false);
149
+ expect(isOpaqueVectorId(v.id), v.id).toBe(true);
150
+ expect(v.metadata?.user_email).toBe(EMAIL);
151
+ }
152
+ expect(chunkRowVectorIds()).toEqual(upserts.map((v) => v.id));
153
+ });
154
+ });
@@ -0,0 +1,141 @@
1
+ // scripts/vectorize-rekey-vector-ids.mjs (prism#232): which ids move, the add-before-remove order,
2
+ // gaps and conflicts, dry run, refusals, and that no id reaches the printed result.
3
+
4
+ import { describe, it, expect } from "vitest";
5
+ import {
6
+ client,
7
+ isEmailBearingId,
8
+ parseArgs,
9
+ rekey,
10
+ type LegacyRow,
11
+ type RekeyApi,
12
+ type Vec,
13
+ } from "../scripts/vectorize-rekey-vector-ids.mjs";
14
+
15
+ const OLD_A = "alice@example.org:1:0";
16
+ const OLD_B = "alice@example.org:1:1";
17
+ const PUBLIC_ID = "usr_0123456789abcdef01234567:2:0";
18
+
19
+ function fakeApi(opts: { rows?: LegacyRow[]; stored?: Vec[]; changes?: (rowId: number) => number; census?: () => Promise<{ total: number; legacy: number }> } = {}) {
20
+ const rows = opts.rows ?? [];
21
+ const stored = new Map((opts.stored ?? []).map((v) => [v.id, v]));
22
+ const log: string[] = [];
23
+ const d1 = new Map(rows.map((r) => [r.rowId, r.vectorId]));
24
+ const api: RekeyApi = {
25
+ census: opts.census ?? (async () => ({ total: rows.length + 1, legacy: rows.length })),
26
+ legacyRows: async () => rows,
27
+ repoint: async (_d, rowId, oldId, newId) => {
28
+ log.push(`repoint ${rowId}`);
29
+ const n = opts.changes ? opts.changes(rowId) : d1.get(rowId) === oldId ? 1 : 0;
30
+ if (n === 1) d1.set(rowId, newId);
31
+ return n;
32
+ },
33
+ getByIds: async (_i, ids) => ids.map((id) => stored.get(id)).filter((v): v is Vec => !!v),
34
+ upsert: async (_i, vs) => {
35
+ log.push(`upsert ${vs.length}`);
36
+ for (const v of vs) stored.set(v.id, v);
37
+ },
38
+ deleteByIds: async (_i, ids) => {
39
+ log.push(`delete ${ids.length}`);
40
+ for (const id of ids) stored.delete(id);
41
+ },
42
+ };
43
+ return { api, log, stored, d1 };
44
+ }
45
+
46
+ const vec = (id: string): Vec => ({ id, values: [0.1, 0.2], metadata: { user_email: "alice@example.org", document_id: 1 } });
47
+ const opts = { index: "ix", d1: "db", dryRun: false, batch: 20 };
48
+
49
+ describe("isEmailBearingId", () => {
50
+ it("selects the access-mode email form only", () => {
51
+ expect(isEmailBearingId(OLD_A)).toBe(true);
52
+ expect(isEmailBearingId(PUBLIC_ID)).toBe(false);
53
+ expect(isEmailBearingId("c_0123456789abcdef0123456789abcdef")).toBe(false);
54
+ });
55
+ });
56
+
57
+ describe("rekey", () => {
58
+ it("moves every email-bearing vector: same values and metadata, new opaque id, D1 repointed, old deleted", async () => {
59
+ const rows = [{ rowId: 1, vectorId: OLD_A }, { rowId: 2, vectorId: OLD_B }];
60
+ const { api, log, stored, d1 } = fakeApi({ rows, stored: [vec(OLD_A), vec(OLD_B)] });
61
+ const r = await rekey(api, opts);
62
+ expect(r.code).toBe(0);
63
+ expect(r.counts).toMatchObject({ legacy: 2, fetched: 2, rekeyed: 2, old_deleted: 2, gaps: 0, conflicts: 0 });
64
+ // Add before remove: the new vectors exist before D1 moves, and D1 moves before the old go.
65
+ expect(log).toEqual(["upsert 2", "repoint 1", "repoint 2", "delete 2"]);
66
+ expect([...stored.keys()].some((id) => id.includes("@"))).toBe(false);
67
+ for (const id of d1.values()) {
68
+ expect(id).toMatch(/^c_[0-9a-f]{32}$/);
69
+ expect(stored.get(id)?.values).toEqual([0.1, 0.2]);
70
+ expect(stored.get(id)?.metadata).toEqual({ user_email: "alice@example.org", document_id: 1 });
71
+ }
72
+ });
73
+
74
+ it("NEGATIVE CONTROL: a non-email id handed back by D1 is never touched", async () => {
75
+ const { api, log, stored } = fakeApi({ rows: [{ rowId: 9, vectorId: PUBLIC_ID }], stored: [vec(PUBLIC_ID)] });
76
+ const r = await rekey(api, opts);
77
+ expect(r.code).toBe(0);
78
+ expect(r.counts.legacy).toBe(0);
79
+ expect(log).toEqual([]);
80
+ expect(stored.has(PUBLIC_ID)).toBe(true);
81
+ });
82
+
83
+ it("a D1 id with no vector is a GAP (exit 1), not a silent skip", async () => {
84
+ const { api } = fakeApi({ rows: [{ rowId: 1, vectorId: OLD_A }, { rowId: 2, vectorId: OLD_B }], stored: [vec(OLD_A)] });
85
+ const r = await rekey(api, opts);
86
+ expect(r.code).toBe(1);
87
+ expect(r.counts).toMatchObject({ gaps: 1, rekeyed: 1 });
88
+ });
89
+
90
+ it("a row that changed under us is a CONFLICT: its new vector is deleted and the old one kept", async () => {
91
+ const { api, stored } = fakeApi({ rows: [{ rowId: 1, vectorId: OLD_A }], stored: [vec(OLD_A)], changes: () => 0 });
92
+ const r = await rekey(api, opts);
93
+ expect(r.code).toBe(1);
94
+ expect(r.counts).toMatchObject({ conflicts: 1, rekeyed: 0, old_deleted: 0 });
95
+ expect([...stored.keys()]).toEqual([OLD_A]);
96
+ });
97
+
98
+ it("dry run writes nothing but still counts", async () => {
99
+ const { api, log } = fakeApi({ rows: [{ rowId: 1, vectorId: OLD_A }], stored: [vec(OLD_A)] });
100
+ const r = await rekey(api, { ...opts, dryRun: true });
101
+ expect(r.code).toBe(0);
102
+ expect(r.counts).toMatchObject({ legacy: 1, fetched: 1, rekeyed: 0 });
103
+ expect(log).toEqual([]);
104
+ });
105
+
106
+ it("refuses (2) and writes nothing when D1 cannot be counted", async () => {
107
+ const { api, log } = fakeApi({ rows: [{ rowId: 1, vectorId: OLD_A }], census: async () => { throw new Error("boom"); } });
108
+ const r = await rekey(api, opts);
109
+ expect(r.code).toBe(2);
110
+ expect(log).toEqual([]);
111
+ });
112
+
113
+ it("the result carries counts only, never an id", async () => {
114
+ const { api } = fakeApi({ rows: [{ rowId: 1, vectorId: OLD_A }], stored: [vec(OLD_A)] });
115
+ const r = await rekey(api, opts);
116
+ expect(JSON.stringify(r)).not.toMatch(/@|c_[0-9a-f]{32}/);
117
+ });
118
+ });
119
+
120
+ describe("client", () => {
121
+ it("sends the repoint as a parameterized UPDATE guarded on the old id", async () => {
122
+ const seen: { url: string; body: unknown }[] = [];
123
+ const fetchImpl = (async (url: string, init: RequestInit) => {
124
+ seen.push({ url, body: JSON.parse(String(init.body)) });
125
+ return new Response(JSON.stringify({ success: true, result: [{ results: [], meta: { changes: 1 } }] }));
126
+ }) as unknown as typeof fetch;
127
+ const n = await client({ token: "t", accountId: "acc", fetchImpl }).repoint("db", 5, OLD_A, "c_new");
128
+ expect(n).toBe(1);
129
+ expect(seen[0].url).toBe("https://api.cloudflare.com/client/v4/accounts/acc/d1/database/db/query");
130
+ expect(seen[0].body).toEqual({ sql: "UPDATE chunks SET vector_id = ? WHERE id = ? AND vector_id = ?", params: ["c_new", 5, OLD_A] });
131
+ });
132
+ });
133
+
134
+ describe("parseArgs", () => {
135
+ it("requires --index and --d1 and bounds --batch", () => {
136
+ expect(() => parseArgs(["--d1", "x"])).toThrow(/--index/);
137
+ expect(() => parseArgs(["--index", "x"])).toThrow(/--d1/);
138
+ expect(() => parseArgs(["--index", "x", "--d1", "y", "--batch", "0"])).toThrow(/--batch/);
139
+ expect(parseArgs(["--index", "x", "--d1", "y", "--dry-run"])).toMatchObject({ dryRun: true, batch: 20 });
140
+ });
141
+ });