@ultimat3/ai 31.39.0 → 31.40.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/CLAUDE.md CHANGED
@@ -268,7 +268,7 @@ One switch (`GenerateRequest.promptCache`), `promptCacheRule`: provider rows (`P
268
268
 
269
269
  In brief ([full text](../../docs/history/ai.md#evals-retrieval-fix-lines)): no fix line names
270
270
  an `ai` command (none exists); an eval gates on the DROP from its baseline, mean AND per case, and every prompt has one;
271
- retrieval is hybrid only; an unbound store read under an org actor is `X_VECTOR_UNSCOPED`;
271
+ retrieval is hybrid only; an unbound store used in any request, by any actor, is `X_VECTOR_UNSCOPED`;
272
272
  `postgresVectorStore()` filters tenant and policy in SQL on every statement (hnsw reads widen the
273
273
  scan, `pg-vector-recall.ts`); `scoped()` TIGHTENS.
274
274
 
package/README.md CHANGED
@@ -1100,9 +1100,14 @@ Allow-lists are default deny: a row missing the key is invisible, and an empty l
1100
1100
  nothing. `scoped()` only ever **tightens** — re-scoping to a different tenant is
1101
1101
  `X_VECTOR_SCOPE_WIDENED`, never a silent widening.
1102
1102
 
1103
- A store opened without a scope binds no tenant, and **reading it inside a request acting for an
1104
- org is `X_VECTOR_UNSCOPED`** — the forgotten `.scoped()` that searched every tenant's rows. Outside a
1105
- request, or for an actor with no org, it reads as before. The backfill path opts in by name:
1103
+ A store opened without a scope binds no tenant, and **reading or writing it inside any request is
1104
+ `X_VECTOR_UNSCOPED`** — `search`, `searchText`, `hybrid`, `upsert`, `prune`, `delete`, so
1105
+ `indexDocument()` too, whoever the actor: an org's, an org-less user's, anonymous, a `tenant: 'none'`
1106
+ job's. The forgotten `.scoped()` searched every tenant's rows, deleted every tenant's row sharing an
1107
+ id, or wrote into the shared no-tenant bucket; an actor with no org has no tenant to be confined to,
1108
+ so it reached every org too — the actors `entity` refuses as `X_TENANCY_ACTOR_ORG_REQUIRED`.
1109
+ Outside any request (a script, a boot task) it reads and writes as written, as entity derives
1110
+ nothing there either. The backfill path and a single-tenant app opt in by name:
1106
1111
  `postgresVectorStore({ name, dimension, scope: UNSCOPED })`, or `store.scoped(UNSCOPED)`.
1107
1112
 
1108
1113
  `chunkDocument()` is token-aware with overlap and splits at paragraph, then sentence, then hard wrap
@@ -1176,7 +1181,7 @@ fail-closed `terminal` default.
1176
1181
  | `X_EVAL_THRESHOLD` | an eval scored below its bar |
1177
1182
  | `X_VECTOR_DIM_MISMATCH` | a vector's length disagrees with the store |
1178
1183
  | `X_VECTOR_SCOPE_WIDENED` | a derived vector scope tried to leave the tenant it was bound to |
1179
- | `X_VECTOR_UNSCOPED` | a store with no tenant bound was read inside a request acting for an org; `scope: UNSCOPED` is the named opt-out |
1184
+ | `X_VECTOR_UNSCOPED` | a store with no tenant bound was read or written inside a request, for any actor; `scope: UNSCOPED` is the named opt-out |
1180
1185
  | `X_NOT_IMPLEMENTED` | a remote driver with no key or transport; the fix names the env var |
1181
1186
 
1182
1187
  A failure thrown after a provider call was started carries what the run was billed on `meta.billed` (`billedOf(error)` → `{ usage, cost, calls, unsettled }`); `unsettled` counts the calls whose bill cannot be known. [Agents → Unattended runs](https://github.com/developerz-ai/ultimate/wiki/Agents#unattended-runs).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/ai",
3
- "version": "31.39.0",
3
+ "version": "31.40.1",
4
4
  "description": "LLM gateway, versioned prompts, evals as tests, embeddings, hybrid vector search, RAG",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -45,17 +45,17 @@
45
45
  "test": "bun test"
46
46
  },
47
47
  "dependencies": {
48
- "@ultimat3/action": "31.39.0",
49
- "@ultimat3/cache": "31.39.0",
50
- "@ultimat3/core": "31.39.0",
51
- "@ultimat3/db": "31.39.0",
52
- "@ultimat3/http": "31.39.0",
53
- "@ultimat3/jobs": "31.39.0",
54
- "@ultimat3/money": "31.39.0",
55
- "@ultimat3/schema": "31.39.0",
56
- "@ultimat3/time": "31.39.0"
48
+ "@ultimat3/action": "31.40.1",
49
+ "@ultimat3/cache": "31.40.1",
50
+ "@ultimat3/core": "31.40.1",
51
+ "@ultimat3/db": "31.40.1",
52
+ "@ultimat3/http": "31.40.1",
53
+ "@ultimat3/jobs": "31.40.1",
54
+ "@ultimat3/money": "31.40.1",
55
+ "@ultimat3/schema": "31.40.1",
56
+ "@ultimat3/time": "31.40.1"
57
57
  },
58
58
  "devDependencies": {
59
- "@ultimat3/policy": "31.39.0"
59
+ "@ultimat3/policy": "31.40.1"
60
60
  }
61
61
  }
@@ -70,7 +70,8 @@ export const AI_ERROR_TITLES: Readonly<Record<AiErrorCode, string>> = {
70
70
  X_VECTOR_DIM_MISMATCH: 'embedding dimensions differ from the store',
71
71
  X_VECTOR_SCOPE_WIDENED: 'a derived vector scope tried to leave its tenant',
72
72
  X_AI_EMBEDDER_INVALID: 'an Embedder returned fewer vectors than texts it was given',
73
- X_VECTOR_UNSCOPED: 'a vector store was read with no tenant bound inside an org request',
73
+ X_VECTOR_UNSCOPED:
74
+ 'a vector store was read or written with no tenant bound inside an org request',
74
75
  X_AI_CONTENT_UNSUPPORTED: 'an image or document block the role, model or wire format cannot take',
75
76
  X_AI_MODEL_UNRESOLVED: 'a model call named no model',
76
77
  X_AGENT_TOOL_LOOP: 'an agent repeated one tool call with one result and was stopped',
package/src/pg-vector.ts CHANGED
@@ -25,7 +25,13 @@ import type {
25
25
  VectorRecord,
26
26
  VectorStore,
27
27
  } from './vector';
28
- import { assertTenantRead, narrowScope, tenantOf, UNBOUND, type VectorScope } from './vector-scope';
28
+ import {
29
+ assertTenantBound,
30
+ narrowScope,
31
+ tenantOf,
32
+ UNBOUND,
33
+ type VectorScope,
34
+ } from './vector-scope';
29
35
 
30
36
  export interface PostgresVectorStoreInput {
31
37
  /** The table. Also the store's name in errors, and the stem of every index name. */
@@ -87,6 +93,9 @@ export class PostgresVectorStore implements VectorStore {
87
93
  }
88
94
 
89
95
  async upsert(records: readonly VectorRecord[]): Promise<void> {
96
+ // Before the empty-batch return, as in `delete`: a refusal that depends on the batch size is a
97
+ // forgotten `.scoped()` that only shows up once there is data to leak.
98
+ assertTenantBound(this.name, this.scope);
90
99
  if (records.length === 0) return;
91
100
  for (const record of records) this.assertDimension(record.vector.length);
92
101
  // One row per id, the LAST one winning — what `MemoryVectorStore` answers. Postgres refuses a
@@ -112,7 +121,7 @@ export class PostgresVectorStore implements VectorStore {
112
121
  k: number,
113
122
  filter?: MetadataFilter,
114
123
  ): Promise<readonly SearchHit[]> {
115
- assertTenantRead(this.name, this.scope);
124
+ assertTenantBound(this.name, this.scope);
116
125
  this.assertDimension(vector.length);
117
126
  // `k` is the statement's `limit` and reaches Postgres as a bound parameter, so a `NaN` is the
118
127
  // database's error to report rather than this store's — and a fractional one is an error there
@@ -129,14 +138,14 @@ export class PostgresVectorStore implements VectorStore {
129
138
  k: number,
130
139
  filter?: MetadataFilter,
131
140
  ): Promise<readonly SearchHit[]> {
132
- assertTenantRead(this.name, this.scope);
141
+ assertTenantBound(this.name, this.scope);
133
142
  return this.run(
134
143
  textSql(this.target, query, { scope: this.scope, filter, k: finiteCount(HYBRID, 'k', k) }),
135
144
  );
136
145
  }
137
146
 
138
147
  async hybrid(input: HybridSearchInput): Promise<readonly SearchHit[]> {
139
- assertTenantRead(this.name, this.scope);
148
+ assertTenantBound(this.name, this.scope);
140
149
  this.assertDimension(input.vector.length);
141
150
  // The same three bounds `MemoryVectorStore.hybrid` screens, and they have to be screened in
142
151
  // BOTH stores: `rrfK` lands in `1.0 / (rrfK + rank)`, Postgres has a float8 `NaN`, and it
@@ -154,10 +163,12 @@ export class PostgresVectorStore implements VectorStore {
154
163
  }
155
164
 
156
165
  async prune(filter: MetadataFilter, keep: readonly string[]): Promise<void> {
166
+ assertTenantBound(this.name, this.scope);
157
167
  await this.client().execute(pruneSql(this.target, this.scope, filter, keep));
158
168
  }
159
169
 
160
170
  async delete(ids: readonly string[]): Promise<void> {
171
+ assertTenantBound(this.name, this.scope);
161
172
  if (ids.length === 0) return;
162
173
  await this.client().execute(deleteSql(this.target, this.scope, ids));
163
174
  }
@@ -19,7 +19,7 @@ export interface VectorScope {
19
19
  readonly allow?: Readonly<Record<string, readonly string[]>> | undefined;
20
20
  /**
21
21
  * Every tenant, ON PURPOSE — `UNSCOPED`'s mark, and the only way a read with no tenant bound
22
- * runs inside a request acting for an org. Meaningless once a tenant is bound, so dropped then.
22
+ * runs inside a request. Meaningless once a tenant is bound, so dropped then.
23
23
  */
24
24
  readonly crossTenant?: true | undefined;
25
25
  }
@@ -27,7 +27,7 @@ export interface VectorScope {
27
27
  /**
28
28
  * Every tenant, every row, named on purpose: the backfill and migration path. Pass it as a
29
29
  * store's `scope` (or `.scoped(UNSCOPED)`) where a cross-tenant read is the point. A store opened
30
- * with no scope binds no tenant either, but reading it inside an org's request is refused.
30
+ * with no scope binds no tenant either, but reading or writing it inside any request is refused.
31
31
  */
32
32
  export const UNSCOPED: VectorScope = Object.freeze({ crossTenant: true });
33
33
 
@@ -58,14 +58,20 @@ export function narrowScope(store: string, base: VectorScope, next: VectorScope)
58
58
  }
59
59
 
60
60
  /**
61
- * Refuse a read that would search every tenant inside a request acting for one. Entities derive
62
- * the tenant from the ambient actor; a vector store is bound by `.scoped({ tenant })`, and a
63
- * forgotten call answered with every org's rows. Outside a request, or for an actor with no org,
64
- * there is no tenant to leak across — a single-tenant app and a job's system actor read as before.
61
+ * Refuse any statement — read or write — that would reach every tenant from inside a request.
62
+ * Entities derive the tenant from the ambient actor; a vector store is bound by
63
+ * `.scoped({ tenant })`, and a forgotten call answered with every org's rows, deleted every org's
64
+ * rows sharing an id (the key is `(tenant, id)`, so ids collide across tenants by design), or wrote
65
+ * into the shared no-tenant bucket. An actor with no org is no exception: anonymous, an org-less
66
+ * user and a `tenant: 'none'` job have NO tenant to be confined to, so an unbound statement under
67
+ * them reached every org — the same actors `entity`'s `actorTenant` refuses
68
+ * (`X_TENANCY_ACTOR_ORG_REQUIRED`). A single-tenant app says so once, with `scope: UNSCOPED`.
69
+ * Outside any request (a script, a boot task) there is no identity to confine, and entity derives
70
+ * nothing there either: the statement runs as written.
65
71
  */
66
- export function assertTenantRead(store: string, scope: VectorScope): void {
72
+ export function assertTenantBound(store: string, scope: VectorScope): void {
67
73
  if (scope.tenant !== undefined || scope.crossTenant === true) return;
68
- if (tryUseContext()?.actor.orgId === undefined) return;
74
+ if (tryUseContext() === undefined) return;
69
75
  throw new VectorUnscopedError({ store });
70
76
  }
71
77
 
@@ -75,9 +81,10 @@ export class VectorUnscopedError extends UltimateError {
75
81
  super({
76
82
  code: 'X_VECTOR_UNSCOPED',
77
83
  cause:
78
- `vector store "${input.store}" was read with no tenant bound, inside a request acting ` +
79
- 'for an org — the read would answer with every tenant’s rows. A deliberate cross-tenant ' +
80
- 'read (a backfill, a migration) opens the store with scope: UNSCOPED',
84
+ `vector store "${input.store}" was read or written with no tenant bound, inside a request ` +
85
+ '— the statement would reach every tenant’s rows, whoever the actor (an org-less or ' +
86
+ 'anonymous one included). A deliberate cross-tenant read or write (a backfill, a ' +
87
+ 'migration, a single-tenant app) opens the store with scope: UNSCOPED',
81
88
  fix: 'vectorStore.scoped({ tenant: ctx.actor.orgId })',
82
89
  });
83
90
  }
package/src/vector.ts CHANGED
@@ -12,7 +12,7 @@ import { finiteCount, finiteOption } from '@ultimat3/core';
12
12
  import { cosine, wordTokens } from './embeddings';
13
13
  import { VectorDimMismatchError } from './errors';
14
14
  import {
15
- assertTenantRead,
15
+ assertTenantBound,
16
16
  NO_VECTOR_TENANT,
17
17
  narrowScope,
18
18
  scopeAdmits,
@@ -140,6 +140,7 @@ export class MemoryVectorStore implements VectorStore {
140
140
  }
141
141
 
142
142
  async upsert(records: readonly VectorRecord[]): Promise<void> {
143
+ assertTenantBound(this.name, this.scope);
143
144
  const tenant = this.scope.tenant ?? NO_VECTOR_TENANT;
144
145
  // Every width checked before any row is written, as `PostgresVectorStore.upsert` does: checked
145
146
  // per record, a refused batch had already written the rows ahead of the bad one.
@@ -154,7 +155,7 @@ export class MemoryVectorStore implements VectorStore {
154
155
  k: number,
155
156
  filter?: MetadataFilter,
156
157
  ): Promise<readonly SearchHit[]> {
157
- assertTenantRead(this.name, this.scope);
158
+ assertTenantBound(this.name, this.scope);
158
159
  this.assertDimension(vector.length);
159
160
  // `k` carries no default, so `??` never sees it and nothing else does either: `slice(0, NaN)`
160
161
  // is `[]`, which is a search that answers "no matches" for every query and reports success.
@@ -169,7 +170,7 @@ export class MemoryVectorStore implements VectorStore {
169
170
  k: number,
170
171
  filter?: MetadataFilter,
171
172
  ): Promise<readonly SearchHit[]> {
172
- assertTenantRead(this.name, this.scope);
173
+ assertTenantBound(this.name, this.scope);
173
174
  return this.lexical(query, finiteCount(SUBJECT, 'k', k), filter).map(({ record, score }) =>
174
175
  this.hit(record, score),
175
176
  );
@@ -186,7 +187,7 @@ export class MemoryVectorStore implements VectorStore {
186
187
  * rankings reach it under the row's storage key and leave under the caller's id again.
187
188
  */
188
189
  async hybrid(input: HybridSearchInput): Promise<readonly SearchHit[]> {
189
- assertTenantRead(this.name, this.scope);
190
+ assertTenantBound(this.name, this.scope);
190
191
  this.assertDimension(input.vector.length);
191
192
  // Three bounds, none of which `Math.max` screens — it PROPAGATES a `NaN`. A `NaN` `k` collapses
192
193
  // both candidate widths and the final slice to `[]`; a `NaN` `rrfK` makes every fused score
@@ -251,6 +252,7 @@ export class MemoryVectorStore implements VectorStore {
251
252
 
252
253
  /** Scoped and filtered, exactly like `pruneSql`: everything `filter` matches but `keep`. */
253
254
  async prune(filter: MetadataFilter, keep: readonly string[]): Promise<void> {
255
+ assertTenantBound(this.name, this.scope);
254
256
  const kept = new Set(keep);
255
257
  for (const record of this.candidates(filter)) {
256
258
  if (kept.has(record.id)) continue;
@@ -260,6 +262,7 @@ export class MemoryVectorStore implements VectorStore {
260
262
 
261
263
  /** Scoped, exactly like the SQL `delete ... where id in (...) and <scope>`. */
262
264
  async delete(ids: readonly string[]): Promise<void> {
265
+ assertTenantBound(this.name, this.scope);
263
266
  const wanted = new Set(ids);
264
267
  for (const [key, record] of this.records) {
265
268
  if (!wanted.has(record.id)) continue;