@fadhilp/stateql 0.13.0 → 0.13.2

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/dist/src/cli.js CHANGED
@@ -20,6 +20,7 @@ const parsed = parseArgs({
20
20
  param: { type: "string", multiple: true },
21
21
  "params-file": { type: "string" },
22
22
  cache: { type: "string" },
23
+ "preview-rows": { type: "string" },
23
24
  replay: { type: "boolean" },
24
25
  "idempotency-key": { type: "string" },
25
26
  "allow-unbounded": { type: "boolean" },
@@ -175,6 +176,9 @@ async function dispatch() {
175
176
  return stateql.query(sql, {
176
177
  params,
177
178
  cache: cacheMode(values.cache),
179
+ ...(values["preview-rows"] === undefined
180
+ ? {}
181
+ : { previewRows: Number(values["preview-rows"]) }),
178
182
  });
179
183
  case "filter":
180
184
  return stateql.filter(requireValue(subcommand, "result handle"), requireValue(rest.join(" ").trim(), "filter predicate"), { params });
@@ -656,6 +660,7 @@ Commands:
656
660
  pipe
657
661
 
658
662
  SQL parameters: --params JSON, repeated --param VALUE, or --params-file FILE.
663
+ Query preview: --preview-rows N (default: 5, maximum: 200).
659
664
  Deadline: --timeout-ms N (default: 30000). Ctrl+C cancels database work.
660
665
  Credential refs require a trusted host CredentialResolver; the standalone CLI cannot resolve them.
661
666
  State: --max-state-bytes N, --cache-ttl-seconds N, --result-ttl-seconds N.
@@ -665,6 +665,9 @@ export class StateQL {
665
665
  }
666
666
  async query(sql, options = {}) {
667
667
  return this.run("query", async (session) => {
668
+ const previewRows = options.previewRows === undefined
669
+ ? this.previewRows
670
+ : queryPreviewRows(options.previewRows);
668
671
  const connection = this.requireConnection(session);
669
672
  this.rejectMongoSql(connection, "mongoQuery");
670
673
  this.rejectDuringStagedTransaction(session, "Queries");
@@ -705,7 +708,7 @@ export class StateQL {
705
708
  cached.row_count <= this.maxResultRows &&
706
709
  this.cacheValid(cached, stateVersion, stateSignature)) {
707
710
  return {
708
- data: this.resultData(cached, true),
711
+ data: this.resultData(cached, true, previewRows),
709
712
  handle: cached.id,
710
713
  cached: true,
711
714
  warnings: paginationWarnings(analysis.ordered),
@@ -752,7 +755,7 @@ export class StateQL {
752
755
  expiresAt,
753
756
  });
754
757
  return {
755
- data: this.resultData(saved, false),
758
+ data: this.resultData(saved, false, previewRows),
756
759
  handle: saved.id,
757
760
  executed: true,
758
761
  warnings: paginationWarnings(analysis.ordered),
@@ -2027,6 +2030,7 @@ export class StateQL {
2027
2030
  const response = await this.query(batchString(command.sql, "sql"), {
2028
2031
  params: command.params ?? [],
2029
2032
  cache: command.cache ?? "auto",
2033
+ previewRows: command.preview_rows,
2030
2034
  timeoutMs: command.timeout_ms,
2031
2035
  });
2032
2036
  if (!response.ok || !command.as)
@@ -2931,9 +2935,9 @@ export class StateQL {
2931
2935
  executionContext(options) {
2932
2936
  return createAdapterContext(executionTimeout(options.timeoutMs ?? this.timeoutMs), combineAbortSignals(options.signal, this.commandContexts.getStore()?.signal, this.signal));
2933
2937
  }
2934
- resultData(result, cached) {
2938
+ resultData(result, cached, previewRows = this.previewRows) {
2935
2939
  const rows = this.store.resultRows(result);
2936
- const preview = compactRows(rows.slice(0, this.previewRows), this.maxCellCharacters);
2940
+ const preview = compactRows(rows.slice(0, previewRows), this.maxCellCharacters);
2937
2941
  return {
2938
2942
  result_id: result.id,
2939
2943
  alias: result.alias ?? this.store.generatedAlias(result.id),
@@ -3286,6 +3290,12 @@ function nonNegativeInteger(value, name) {
3286
3290
  return value;
3287
3291
  throw new StateQLError("INVALID_COMMAND", `${name} must be a non-negative integer.`);
3288
3292
  }
3293
+ function queryPreviewRows(value) {
3294
+ const previewRows = nonNegativeInteger(value, "previewRows");
3295
+ if (previewRows <= 200)
3296
+ return previewRows;
3297
+ throw new StateQLError("OUTPUT_LIMIT_EXCEEDED", "previewRows cannot exceed 200 rows.");
3298
+ }
3289
3299
  function positiveInteger(value, name) {
3290
3300
  if (Number.isInteger(value) && value > 0)
3291
3301
  return value;
@@ -281,6 +281,7 @@ export type StateQLWorkspaceOptions = StateQLActorOptions & {
281
281
  export interface QueryOptions extends ExecutionOptions {
282
282
  params?: SqlParameters;
283
283
  cache?: "auto" | "bypass" | "require";
284
+ previewRows?: number;
284
285
  }
285
286
  export interface MongoQueryOptions extends ExecutionOptions {
286
287
  cache?: "auto" | "bypass" | "require";
@@ -360,6 +361,7 @@ export interface BatchCommand {
360
361
  redis?: RedisCommand;
361
362
  object?: CatalogObject;
362
363
  cache?: "auto" | "bypass" | "require";
364
+ preview_rows?: number;
363
365
  read_only?: boolean;
364
366
  secret_env?: string;
365
367
  credential_ref?: string;
@@ -0,0 +1,225 @@
1
+ # Database support
2
+
3
+ [Home](../README.md) · [Usage](usage.md) · [Database support](databases.md) · [TypeScript library](library.md)
4
+
5
+ - [Driver notes](#driver-notes)
6
+ - [SQL statement support](#sql-statement-support)
7
+ - [Dialect upserts](#dialect-upserts)
8
+ - [PostgreSQL diagnostics and maintenance](#postgresql-diagnostics-and-maintenance)
9
+ - [SQLite and MySQL diagnostics and maintenance](#sqlite-and-mysql-diagnostics-and-maintenance)
10
+ - [Native MongoDB](#native-mongodb)
11
+ - [Native Redis](#native-redis)
12
+
13
+ Connect using the [usage guide](usage.md#connections-and-profiles). All writes
14
+ require a read-write connection; SQL/MongoDB approvals and retry rules are
15
+ covered under [write safety](usage.md#write-safety).
16
+
17
+ ## Driver notes
18
+
19
+ - **SQLite:** use a filesystem path for direct connections or `sqlite:` for an
20
+ environment-backed path.
21
+ - **PostgreSQL:** StateQL preserves strict TLS verification by normalizing
22
+ `sslmode=prefer`, `require`, and `verify-ca` to `verify-full` before opening
23
+ the adapter. Use `sslmode=verify-full` explicitly for clarity. Setting
24
+ `uselibpqcompat=true` opts out and keeps libpq-compatible SSL semantics.
25
+ - **MySQL:** uses positional `?` parameters. MariaDB compatibility is not
26
+ currently claimed.
27
+ - **MongoDB:** supports `mongodb://` and `mongodb+srv://` URLs with an explicit
28
+ database path. SQL methods are rejected; use the native MongoDB methods below.
29
+ - **Redis:** supports `redis://` and TLS-backed `rediss://` URLs. SQL methods and
30
+ legacy `inspect` commands are unavailable; use native commands and catalog
31
+ inspection instead.
32
+
33
+ ## SQL statement support
34
+
35
+ StateQL parses and classifies one `SELECT`, `INSERT`, `REPLACE`, `UPDATE`,
36
+ `DELETE`, `CREATE`, `ALTER`, `DROP`, or `TRUNCATE` statement through
37
+ `node-sql-parser`, subject to dialect support and safety validation. Reads use
38
+ `query`; mutations and DDL use durable `exec`/`plan`/`apply` operations. Raw
39
+ transaction-control SQL is unsupported: use
40
+ [staged transactions](usage.md#transactions), not `BEGIN` or `COMMIT` statements.
41
+ MongoDB and Redis use separate native command APIs.
42
+
43
+ Unrecognized or parser-unsupported forms remain blocked. The
44
+ [SQL command roadmap](../SQL_COMMAND_ROADMAP.md) describes future categories,
45
+ not permission to execute them.
46
+
47
+ ## Dialect upserts
48
+
49
+ PostgreSQL `INSERT ... ON CONFLICT DO NOTHING|UPDATE` and MySQL `INSERT ... ON
50
+ DUPLICATE KEY UPDATE` are structurally validated and recorded with statement
51
+ type `upsert`. Finite `VALUES` and MySQL `INSERT ... SET` sources use normal
52
+ write policy. An update-upsert fed by `SELECT` requires `--allow-unbounded`
53
+ because its candidate row count is not statically bounded. Upserts support direct
54
+ `exec`, `plan`/`apply`, and staged transactions; hidden additional writes are rejected.
55
+
56
+ MySQL `INSERT IGNORE` and SQLite `INSERT OR IGNORE` remain non-overwriting
57
+ inserts. SQLite `INSERT OR REPLACE` retains destructive-operation approval,
58
+ while SQLite modern `ON CONFLICT ... DO UPDATE` and every `MERGE` form remain
59
+ blocked until the parser can expose their complete mutation structure.
60
+
61
+ ## PostgreSQL diagnostics and maintenance
62
+
63
+ Run PostgreSQL plans through `query`:
64
+
65
+ ```bash
66
+ stql query "EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) SELECT * FROM jobs WHERE id = 42"
67
+ ```
68
+
69
+ Plain `EXPLAIN` may plan a structurally validated `SELECT`, `INSERT`, `UPDATE`,
70
+ or `DELETE`. Because `EXPLAIN ANALYZE` executes its inner statement, StateQL
71
+ accepts only a validated read-only `SELECT`; `SELECT INTO`, writing CTEs, and
72
+ mutations are rejected. Diagnostics execute inside PostgreSQL `BEGIN READ ONLY`
73
+ and are never reused from cache. `--cache require` therefore returns
74
+ `CACHE_MISS` without executing the diagnostic.
75
+
76
+ Legacy `EXPLAIN [ANALYZE] [VERBOSE] statement` is also supported. Option lists
77
+ allow PostgreSQL boolean diagnostic options plus `FORMAT` and `SERIALIZE`;
78
+ unknown, duplicate, or malformed options fail closed. PostgreSQL's read-only
79
+ transaction protects database writes, but cannot contain external effects from
80
+ user-defined or incorrectly labelled functions.
81
+
82
+ StateQL supports PostgreSQL 14–18. Top-level `VALUES` is a bounded read and
83
+ accepts normal PostgreSQL positional parameters. It is conservatively
84
+ non-cacheable because expressions may be volatile. The following narrow `SHOW`
85
+ allowlist is also available as non-cacheable diagnostics:
86
+ `server_version`, `server_version_num`, `transaction_read_only`,
87
+ `transaction_isolation`, and `default_transaction_isolation`. `SHOW ALL` and
88
+ other settings remain blocked. Syntax accepted by StateQL but introduced by a
89
+ newer PostgreSQL release may be rejected safely by an older server.
90
+
91
+ `VACUUM`, `ANALYZE`, `REINDEX`, and `CLUSTER` are PostgreSQL maintenance writes:
92
+
93
+ ```bash
94
+ stql exec "VACUUM (ANALYZE) public.jobs" --allow-destructive
95
+ stql plan "REINDEX TABLE public.jobs" --allow-destructive
96
+ ```
97
+
98
+ The PostgreSQL 14–18 grammar includes parenthesized `REINDEX CONCURRENTLY`,
99
+ PostgreSQL 16 `BUFFER_USAGE_LIMIT` for `VACUUM`/`ANALYZE`, optional
100
+ `DATABASE`/`SYSTEM` reindex names, and PostgreSQL 18 `ONLY table *` maintenance
101
+ targets. Memory sizes accept an integer number of kilobytes or a quoted
102
+ `B|kB|MB|GB|TB` value. Older servers may reject newer forms after dispatch, so
103
+ StateQL retains conservative unknown-outcome handling.
104
+
105
+ They require a read-write connection and `--allow-destructive`, reject StateQL
106
+ parameters and optimistic row-count preconditions, and run as individually
107
+ tracked autocommit operations. They cannot be staged in a StateQL transaction,
108
+ even where a PostgreSQL variant could run inside a database transaction. A
109
+ timeout, cancellation, or error after dispatch is reported as `OUTCOME_UNKNOWN`;
110
+ inspect database state before replaying it.
111
+
112
+ ## SQLite and MySQL diagnostics and maintenance
113
+
114
+ SQLite supports `EXPLAIN QUERY PLAN` for structurally read-only `SELECT`
115
+ statements. MySQL supports `EXPLAIN SELECT` plus bare `SHOW TABLES`,
116
+ `SHOW COLUMNS FROM table`, and `SHOW INDEX|INDEXES FROM table`. Broader
117
+ `EXPLAIN`, `SHOW`, and write-bearing forms remain blocked.
118
+
119
+ MySQL executable comments (`/*! ... */`) are rejected throughout SQL. Because
120
+ StateQL does not assume a server `sql_mode`, quoting that could expose these
121
+ comments under `ANSI_QUOTES` or `NO_BACKSLASH_ESCAPES` is also rejected.
122
+
123
+ These diagnostics use `query`, work with read-only connections, preserve the
124
+ original statement instead of applying StateQL's limiting SQL wrapper, and are
125
+ never reused from cache. Materialized results still receive StateQL's row and
126
+ byte checks.
127
+
128
+ SQLite also supports bare `VACUUM`, plus `ANALYZE [target]` and
129
+ `REINDEX [target]` with at most one unqualified or double-quoted target:
130
+
131
+ ```bash
132
+ stql exec "ANALYZE jobs" --allow-destructive
133
+ stql exec "REINDEX jobs_created_at_idx" --allow-destructive
134
+ stql exec "VACUUM" --allow-destructive
135
+ ```
136
+
137
+ These commands require a read-write connection, reject parameters, run as
138
+ individually tracked autocommit operations, and cannot be staged. A timeout,
139
+ cancellation, or error after dispatch is reported as `OUTCOME_UNKNOWN`.
140
+ `VACUUM INTO`, schema-qualified targets, paths, `ATTACH`, and arbitrary `PRAGMA`
141
+ remain blocked.
142
+
143
+ MySQL supports one optionally qualified bare or backtick-quoted target for
144
+ `ANALYZE TABLE`, `OPTIMIZE TABLE`, and `CHECK TABLE`:
145
+
146
+ ```bash
147
+ stql exec "ANALYZE TABLE jobs" --allow-destructive
148
+ stql plan "OPTIMIZE TABLE jobs" --allow-destructive
149
+ stql query "CHECK TABLE jobs"
150
+ ```
151
+
152
+ `ANALYZE` and `OPTIMIZE` are durable autocommit writes requiring a read-write
153
+ connection and destructive approval; server-reported error rows become known
154
+ failed operations, while timeout or cancellation after dispatch remains
155
+ `OUTCOME_UNKNOWN`. `CHECK TABLE` is an unwrapped, non-cacheable autocommit read
156
+ that works on read-only connections and retains normal result limits. All three
157
+ reject StateQL parameters, options, multiple targets, and additional
158
+ statements, and none can run during a staged transaction.
159
+ ## Native MongoDB
160
+
161
+ MongoDB commands use official Extended JSON (EJSON), so BSON values survive the
162
+ CLI boundary:
163
+
164
+ ```bash
165
+ stql mongo query '{"operation":"find","collection":"users","filter":{"_id":{"$oid":"507f1f77bcf86cd799439011"}}}'
166
+ stql mongo exec '{"operation":"updateOne","collection":"users","filter":{"_id":{"$oid":"507f1f77bcf86cd799439011"}},"update":{"$set":{"seen_at":{"$date":"2026-01-01T00:00:00Z"}}}}'
167
+ stql mongo plan '{"operation":"deleteMany","collection":"users","filter":{"disabled":true}}' --allow-destructive
168
+ ```
169
+
170
+ The TypeScript equivalents are `mongoQuery(command)`, `mongoExec(command)`, and
171
+ `mongoPlan(command)`. Supported reads are `find` and `aggregate`; writes are
172
+ `insertOne`, `insertMany`, `updateOne`, `updateMany`, `replaceOne`, `deleteOne`,
173
+ and `deleteMany`. Result documents are JSON-safe, order-preserving EJSON: for example,
174
+ ObjectIds and dates appear as `{ "$oid": "..." }` and
175
+ `{ "$date": { "$numberLong": "..." } }`.
176
+
177
+ Empty update, replacement, or delete filters require `--allow-unbounded`;
178
+ deletes and replacements also require `--allow-destructive`. Mongo inspection
179
+ accepts `collections`, `collection`, `columns`, `indexes`, and `constraints`
180
+ (`schema` and `table` remain aliases shared with SQL drivers). MongoDB cache
181
+ confidence is TTL-based: external writes are not detected, so use
182
+ `--cache bypass` for a fresh read.
183
+
184
+ ```ts
185
+ const result = await stateql.mongoQuery({
186
+ operation: "find",
187
+ collection: "users",
188
+ filter: { active: true },
189
+ options: { sort: { _id: 1 }, limit: 50 },
190
+ });
191
+ ```
192
+
193
+ ## Native Redis
194
+
195
+ Redis/Rediss URLs support URL database selection, password or ACL username,
196
+ and TLS (`rediss`). Supply credential-bearing URLs through `--env` or a trusted
197
+ full-URL credential reference. Library/batch callers may instead use a
198
+ [password reference](library.md#password-references) with a password-free target.
199
+ Native commands accept `{command: string, args?: string[]}`:
200
+
201
+ ```bash
202
+ stql redis query '{"command":"GET","args":["app:status"]}'
203
+ stql redis exec '{"command":"SET","args":["app:status","ready"]}' --idempotency-key status-ready
204
+ stql redis plan '{"command":"SET","args":["app:status","paused"]}'
205
+ stql objects key --search app --limit 50
206
+ stql object key app:status
207
+ ```
208
+
209
+ Writes and plans require a read-write connection. The TypeScript methods are:
210
+
211
+ - `redisQuery`: `GET`, `MGET`, `TYPE`, `EXISTS`, `TTL`, `PTTL`, `HGET`, `HMGET`,
212
+ bounded `LRANGE`, and bounded `SCAN`/`HSCAN`/`SSCAN`/`ZSCAN`.
213
+ - `redisExec` and `redisPlan`: one-key `SET`, `DEL`, `HSET`, `HDEL`, `LPUSH`,
214
+ `RPUSH`, `SADD`, `SREM`, `ZADD`, or `ZREM` mutation.
215
+ - `describeObject({kind:"key",name})`: bounded string/hash/list/set/zset value
216
+ inspection with TTL and continuation metadata where applicable.
217
+
218
+ Arguments are UTF-8 strings, at most 100 values/256 KiB; materialized replies are
219
+ at most 1 MiB. `KEYS`, scripts, modules, pub/sub, blocking commands, admin/flush,
220
+ and arbitrary commands are rejected. Key discovery always uses SCAN. A Redis
221
+ plan snapshots one bounded key and `apply` uses an isolated `WATCH` + one-command
222
+ `MULTI/EXEC`; a pre-apply content or expiry change returns `ROW_CONFLICT` and is
223
+ never retried automatically. Direct `redisExec` has Redis single-command
224
+ atomicity only. Redis has no SQL rollback or StateQL staged transaction support;
225
+ a lost write/EXEC reply is reported as `OUTCOME_UNKNOWN` and remains blocked.
@@ -0,0 +1,272 @@
1
+ # TypeScript library
2
+
3
+ [Home](../README.md) · [Usage](usage.md) · [Database support](databases.md) · [TypeScript library](library.md)
4
+
5
+ - [Getting started](#getting-started)
6
+ - [Responses and command context](#responses-and-command-context)
7
+ - [Actor workspaces](#actor-workspaces)
8
+ - [Credential resolution](#credential-resolution)
9
+ - [Safe profile updates](#safe-profile-updates)
10
+
11
+ ## Getting started
12
+
13
+ Install with `npm install @fadhilp/stateql`. This example connects to an existing
14
+ SQLite database containing a `users` table, queries it, and filters the stored
15
+ result. `forActor()` resolves or creates a session; it does not establish a
16
+ database connection for a new session.
17
+
18
+ ```ts
19
+ import { StateQL } from "@fadhilp/stateql";
20
+
21
+ const stateql = StateQL.forActor({
22
+ home: "./.stql",
23
+ actor: "audit",
24
+ });
25
+
26
+ try {
27
+ const connected = await stateql.connect("./app.sqlite", { readOnly: true });
28
+ if (!connected.ok) throw new Error(connected.error.message);
29
+
30
+ const result = await stateql.query(
31
+ "SELECT id, email FROM users WHERE status = ? ORDER BY id LIMIT 50",
32
+ { params: ["active"], timeoutMs: 5_000, previewRows: 20 },
33
+ );
34
+ if (!result.ok) throw new Error(result.error.message);
35
+
36
+ const filtered = await stateql.filter(result.data.result_id, "email LIKE ?", {
37
+ params: ["%@example.com"],
38
+ });
39
+ if (!filtered.ok) throw new Error(filtered.error.message);
40
+
41
+ console.log(filtered.data.preview);
42
+ } finally {
43
+ stateql.close();
44
+ }
45
+ ```
46
+
47
+ `close()` releases the client's local store; it does not disconnect or delete
48
+ the durable session. Await active commands before closing. Use `disconnect()`
49
+ only when you intend to remove the session's shared active connection.
50
+
51
+ Options include `timeoutMs`, `credentialTimeoutMs`, `maxResultBytes`,
52
+ `maxStateBytes`, `cacheTtlSeconds`, and `resultTtlSeconds`. Database calls also
53
+ accept `signal` for cancellation. See [limits](usage.md#result-lifetime-and-limits)
54
+ and [deadlines](usage.md#deadlines-and-cancellation) for defaults and behavior.
55
+ The same [write safety](usage.md#write-safety) and
56
+ [database restrictions](databases.md) apply to library calls.
57
+
58
+ ## Responses and command context
59
+
60
+ Library responses retain the full response envelope regardless of the CLI
61
+ output mode. Check `response.ok` before reading `response.data`; failures expose
62
+ `response.error`. Queries return typed `ResultData` with `result_id`, `preview`,
63
+ and result metadata. Reuse `result_id` with methods such as `filter`, `rows`,
64
+ `count`, and `exportResult`; the CLI instead presents its primary ID as `handle`.
65
+ Queries preview five rows by default. Set `previewRows` from 0 to 200 on an
66
+ individual query to control its response without changing or rerunning the
67
+ materialized result. The constructor-level `previewRows` option changes the
68
+ client default.
69
+
70
+ The following snippets assume an open client and an appropriate connection.
71
+
72
+ Hosts that dispatch batch-shaped commands can attach trusted metadata out of
73
+ band. `origin` is audit/source metadata only; it never changes actor membership,
74
+ workspace access, or write authorization.
75
+
76
+ ```ts
77
+ const controller = new AbortController();
78
+ await stateql.executeCommand(
79
+ { command: "query", sql: "SELECT id, email FROM users ORDER BY id LIMIT 50", cache: "bypass" },
80
+ { origin: "user", signal: controller.signal },
81
+ );
82
+
83
+ const userHistory = await stateql.history(50, { origin: "user" });
84
+ await stateql.executeCommand(
85
+ { command: "history", limit: 50, history_origin: "user" },
86
+ { origin: "model" },
87
+ );
88
+ ```
89
+
90
+ Supported origins are `legacy`, `user`, `model`, `system`, and `api`. Existing
91
+ direct calls and `executeCommand(command)` calls are recorded as `legacy`.
92
+ `history_origin` is only a retrieval filter; putting an `origin` field in a
93
+ `BatchCommand` cannot attribute the command. `batch` accepts the same trusted
94
+ context as `options.executionContext` for all commands in that batch.
95
+
96
+ ## Actor workspaces
97
+
98
+ `StateQL.forWorkspace(...)` is a trusted-host primitive that atomically creates
99
+ or reopens a durable workspace, attaches the requested actor, and returns a
100
+ client bound to that actor:
101
+
102
+ ```ts
103
+ const stateql = StateQL.forWorkspace({
104
+ home: "./.stql",
105
+ workspace: "team-audit",
106
+ actor: "audit-worker-1",
107
+ credentialResolver,
108
+ signal,
109
+ });
110
+ ```
111
+
112
+ Repeated opens of the same actor and workspace are idempotent. An actor already
113
+ attached elsewhere fails with a `StateQLError` whose code is
114
+ `PERMISSION_DENIED`; StateQL never moves or merges it. All actor options,
115
+ including limits, credential resolution, cancellation, `home`, and `now`, are
116
+ preserved. The workspace name also reserves a same-named actor identity for
117
+ legacy compatibility, so workspace and actor identifiers must be globally
118
+ collision-free. The returned client is still bound only to `actor`, preserving
119
+ plan, transaction, operation, and history ownership.
120
+
121
+ `StateQL.forActor(...)` retains its existing behavior: it resolves the actor's
122
+ attached session directly from StateQL storage and creates a legacy-compatible
123
+ session named after the actor on first use. Use `new StateQL({ session, actor })`
124
+ when the session and membership are already known.
125
+
126
+ Membership management and `forWorkspace` are library-only host capabilities,
127
+ not batch or CLI commands. Existing member-authorized management remains
128
+ available through `linkActor(session, actorId)`, `unlinkActor(session, actorId)`,
129
+ `listActors(session)`, and `resolveActor(actorId)`. Integrations should ask for
130
+ user confirmation before changing membership or the shared connection; a host
131
+ calling `forWorkspace` is responsible for authorizing that workspace access.
132
+
133
+ ## Credential resolution
134
+
135
+ Library integrations can resolve environment-variable names, opaque full-URL
136
+ credential references, or password-only references through a trusted approval
137
+ or secret-storage layer instead of mutating `process.env`.
138
+
139
+ Integrations pinned to an older published package should gate setup before
140
+ sending `password_ref`:
141
+
142
+ ```ts
143
+ if ((StateQL.passwordReferenceVersion ?? 0) < 1) {
144
+ throw new Error("Installed StateQL does not support password references.");
145
+ }
146
+ ```
147
+
148
+ `passwordReferenceVersion = 1` guarantees the password-only resolver request,
149
+ validation, persistence, reconnect, and redaction contract documented below.
150
+
151
+ In this adapter example, `credentialBroker` is supplied by the host application;
152
+ it is not a StateQL export.
153
+
154
+ ```ts
155
+ import {
156
+ CredentialResolutionError,
157
+ StateQL,
158
+ type CredentialRequest,
159
+ } from "@fadhilp/stateql";
160
+
161
+ async function resolveCredential(
162
+ request: CredentialRequest,
163
+ ): Promise<string | undefined> {
164
+ const approved = await credentialBroker.request({
165
+ reference: request.reference,
166
+ source: request.source ?? "secret_env",
167
+ actor: request.actorId,
168
+ session: request.session.id,
169
+ operation: request.operation,
170
+ access: request.access,
171
+ signal: request.signal,
172
+ });
173
+
174
+ if (approved.denied) throw new CredentialResolutionError("denied");
175
+ return approved.value;
176
+ }
177
+
178
+ const stateql = StateQL.forActor({
179
+ actor: "agent-session-id",
180
+ credentialResolver: resolveCredential,
181
+ });
182
+ ```
183
+
184
+ Credential resolution has its own two-minute default deadline
185
+ (`credentialTimeoutMs`) and remains cancellable through `request.signal`.
186
+ The database-operation timeout begins after a credential is resolved.
187
+
188
+ When no custom resolver is configured, StateQL reads only `secret_env`
189
+ references from `process.env`; `credential_ref` and `password_ref` never fall
190
+ back to the environment. A configured resolver is authoritative for all
191
+ sources: returning `undefined` produces `CREDENTIAL_UNAVAILABLE` and never falls
192
+ back to the process environment. Resolver requests retain `reference` and
193
+ include `source` (`secret_env`, `credential_ref`, or `password_ref`); source may
194
+ be omitted only on legacy secret-environment request objects. A `password_ref`
195
+ request additionally includes the exact password-free effective `target`.
196
+ Resolvers may throw `CredentialResolutionError` with `denied`, `cancelled`,
197
+ `timeout`, or `unavailable` to produce controlled, secret-free failures. Unknown
198
+ resolver errors are replaced with a generic `CREDENTIAL_RESOLUTION_FAILED`
199
+ response.
200
+
201
+ StateQL calls the resolver only immediately before database access, after SQL
202
+ safety and duplicate checks. Requests contain actor and session identity, the
203
+ operation's effective read/write access, an abort signal, and sanitized
204
+ connection metadata.
205
+
206
+ For `secret_env` and `credential_ref`, returned values must be complete
207
+ PostgreSQL, MySQL, MongoDB, or Redis URLs, or explicit `sqlite:` sources. For
208
+ `password_ref`, the resolver returns only the password; an explicit empty string
209
+ is a resolved password, while `undefined` fails closed. StateQL percent-encodes
210
+ and injects only that password into the original target for adapter use, leaving
211
+ all nonsecret URL/TLS/CA bytes unchanged. It persists only the original target
212
+ and reference. Resolved credentials never enter connection metadata, history,
213
+ snapshots, cache keys, responses, or stored errors.
214
+
215
+ Hosts remain responsible for approval policy, binding lifetime, revocation,
216
+ and keeping values out of their own logs and model-visible data.
217
+
218
+ For writes, credential resolution happens after StateQL atomically reserves the
219
+ operation for duplicate protection. A resolution failure keeps a non-executed
220
+ `failed` audit record, does not consume the idempotency key, and permits a safe
221
+ retry.
222
+
223
+ ### Password references
224
+
225
+ Library callers can keep nonsecret endpoint, username, database, TLS, and CA
226
+ options in the literal URL while resolving only its password:
227
+
228
+ ```ts
229
+ await stateql.connect(
230
+ "postgres://app@db.example/app?sslmode=verify-full&sslrootcert=/etc/app-ca.pem",
231
+ { passwordRef: "vault://database/app/password", readOnly: true },
232
+ );
233
+ ```
234
+
235
+ The same field is accepted by `addProfile`, `updateProfile`, and batch
236
+ `connect`/`profile.add`/`profile.update` commands (snake case in batch input).
237
+ Targets with an embedded password or query parameters that override endpoint or
238
+ credential fields are rejected before credential resolution or driver access.
239
+
240
+ ## Safe profile updates
241
+
242
+ `updateProfile(name, options)` accepts optional `target`, `secretEnv`,
243
+ `credentialRef`, `passwordRef`, and `readOnly` fields. The four string fields
244
+ also accept `null` for explicit clearing.
245
+
246
+ ```ts
247
+ const updated = await stateql.updateProfile("production", { readOnly: true });
248
+ if (!updated.ok) throw new Error(updated.error.message);
249
+ ```
250
+
251
+ Omitting all source and password-reference fields keeps the existing source and
252
+ adjunct reference. Supplying any source field replaces the source atomically:
253
+ exactly one non-null source is required and the other source columns are
254
+ cleared. An omitted `passwordRef` is preserved when the existing literal target
255
+ is unchanged; changing the target clears it unless the update explicitly supplies
256
+ a replacement. Replacing the source with `secretEnv` or `credentialRef` clears
257
+ it. An explicit non-null password reference combined with either
258
+ reference-backed source is rejected. Direct URLs
259
+ with embedded passwords or secret-like query parameters are rejected.
260
+ `profile.list/show/update` return only
261
+ `{profile,target,secret_env,credential_ref,password_ref,read_only}`. Profile
262
+ changes affect subsequent `connect` calls and do not silently mutate an
263
+ already-open connection.
264
+
265
+ The `password_refs_v1` migration adds nullable `password_ref` columns to both
266
+ profiles and connections and enforces that they accompany only literal target
267
+ configuration. It rejects incompatible profile schemas/rows instead of dropping
268
+ references. Downgrading a state home containing password references is
269
+ unsupported: older binaries do not resolve this source and may attempt the
270
+ password-free target using ambient/trust authentication; constraint-protected
271
+ source replacements may also fail. Use the same or newer StateQL binary, or
272
+ explicitly clear all password references before downgrade.