@fadhilp/stateql 0.13.3 → 0.15.0

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.
@@ -6,6 +6,7 @@ export declare function parseJson<T>(value: string, context: string, validate?:
6
6
  export declare function isSqlParameters(value: unknown): value is SqlParameters;
7
7
  export declare function isRows(value: unknown): value is Row[];
8
8
  export declare function isColumns(value: unknown): value is Column[];
9
+ export declare function isRecord(value: unknown): value is Record<string, unknown>;
9
10
  export declare function redact(value: string): string;
10
11
  export declare function compactRows(rows: Row[], maxCellCharacters: number): Row[];
11
12
  export declare function toJsonSafe<T>(value: T): T;
package/dist/src/util.js CHANGED
@@ -49,7 +49,7 @@ export function isColumns(value) {
49
49
  typeof column.name === "string" &&
50
50
  typeof column.type === "string");
51
51
  }
52
- function isRecord(value) {
52
+ export function isRecord(value) {
53
53
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
54
54
  }
55
55
  function corruptedState(context) {
package/docs/agents.md ADDED
@@ -0,0 +1,72 @@
1
+ # Agent guide
2
+
3
+ [StateQL](../README.md) · [Agents](agents.md) · [Connections](connections.md) · [CLI](cli.md) · [Results](results.md) · [Writes](writes.md) · [Batch](batch.md) · [Databases](databases.md) · [Library](library.md)
4
+
5
+ The minimum an agent needs to query a database with `stql`. Read the other pages
6
+ only for the topic at hand.
7
+
8
+ ## Setup
9
+
10
+ ```bash
11
+ export STQL_SESSION=task-42 # keeps handles and aliases across calls
12
+ stql connect ./app.sqlite # read-only by default
13
+ stql connect --env DATABASE_URL # remote URL from an environment variable
14
+ ```
15
+
16
+ ## Read
17
+
18
+ ```bash
19
+ stql objects table --search user # find tables
20
+ stql object table users # table DDL
21
+ stql query "SELECT id, name FROM users WHERE status = ? ORDER BY id" --param active
22
+ ```
23
+
24
+ ```json
25
+ {"ok":true,"handle":"katcitg6un","total":333,"next_offset":5,"columns":["id","name"],"rows":[[2,"Ada"],[3,"Grace"],[5,"Linus"],[6,"Alan"],[8,"Edsger"]]}
26
+ ```
27
+
28
+ - Rows are arrays in `columns` order. If rows have different keys, they stay
29
+ objects and `columns` is omitted.
30
+ - `next_offset` is present only when more rows exist.
31
+ - Null fields and false `cached`/`duplicate` flags are omitted.
32
+ - Long cells come back as `{"type":"text","length":N,"preview":"..."}`.
33
+ - `objects` uses the same `columns` + arrays shape.
34
+ - `rows`, `count`, and `columns` do not repeat the handle you passed.
35
+ - Result handles are short, stable aliases. Full `q_...` IDs also work.
36
+ - Writes return `handle`, `statement_type`, `affected_rows`, `status`, and
37
+ `state_version_after`.
38
+
39
+ ## Reuse a result without querying again
40
+
41
+ ```bash
42
+ stql rows katcitg6un --offset 5 --limit 20
43
+ stql count katcitg6un
44
+ stql filter katcitg6un "name LIKE ?" --param "A%"
45
+ stql export katcitg6un --output users.csv
46
+ ```
47
+
48
+ ## Save tokens
49
+
50
+ - Select only the columns you need, and add `ORDER BY` and `LIMIT`.
51
+ - Use `--preview-rows 0` when you need only the handle and `total`.
52
+ - Use `stql pipe` to run several commands in one call:
53
+
54
+ ```bash
55
+ printf '%s\n' \
56
+ '{"command":"query","sql":"SELECT id, email FROM users ORDER BY id","as":"users"}' \
57
+ '{"command":"count","handle":"users"}' | stql pipe
58
+ ```
59
+
60
+ ## Errors
61
+
62
+ Errors are `{"ok":false,"error":{"code":...,"message":...}}`. Follow
63
+ `suggested_action` or `override_flag` when present. Retry only when
64
+ `retryable` is true (lost connection, deadlock, lock timeout). SQL syntax errors
65
+ give the line, column, and nearby text. Do not replay a write that
66
+ returned `OUTCOME_UNKNOWN` until you have checked the database.
67
+
68
+ ## Writes
69
+
70
+ Connect with `--read-write`. Use `stql exec` with `--idempotency-key KEY` for
71
+ retryable writes. Writes without `WHERE` need `--allow-unbounded`, and
72
+ destructive statements need `--allow-destructive`. See [write safety](writes.md).
package/docs/batch.md ADDED
@@ -0,0 +1,49 @@
1
+ # Batch and pipes
2
+
3
+ [StateQL](../README.md) · [Agents](agents.md) · [Connections](connections.md) · [CLI](cli.md) · [Results](results.md) · [Writes](writes.md) · [Batch](batch.md) · [Databases](databases.md) · [Library](library.md)
4
+
5
+ `batch` reads a JSON array from a `.json` file or JSONL from a `.jsonl` file.
6
+ `pipe` reads JSONL from standard input. Commands run sequentially and stop on
7
+ the first error unless `--continue-on-error` is set. Output defaults to one
8
+ compact `agent` JSON object per line.
9
+
10
+ Pipe commands directly:
11
+
12
+ ```bash
13
+ printf '%s\n' \
14
+ '{"command":"query","sql":"SELECT id, email FROM users ORDER BY id","as":"users"}' \
15
+ '{"command":"filter","handle":"users","where":"email LIKE ?","params":["%@example.com"],"as":"example_users"}' \
16
+ '{"command":"rows","handle":"example_users","limit":10}' |
17
+ stql pipe
18
+ ```
19
+
20
+ Or save a JSON array as `commands.json`:
21
+
22
+ ```json
23
+ [
24
+ {
25
+ "command": "exec",
26
+ "sql": "UPDATE jobs SET claimed = 1 WHERE id = ?",
27
+ "params": [42],
28
+ "idempotency_key": "claim-job-42"
29
+ },
30
+ {
31
+ "command": "query",
32
+ "sql": "SELECT * FROM jobs WHERE id = ?",
33
+ "params": [42]
34
+ }
35
+ ]
36
+ ```
37
+
38
+ ```bash
39
+ stql batch commands.json
40
+ ```
41
+
42
+ Batch fields use snake case. Supported command names match CLI paths, such as
43
+ `actor.show`, `actor.set-name`, `filter`, `transaction.begin`, `session.summary`,
44
+ `alias.set`, `plan`, and `apply`. `actor.set-name` takes the display name in the
45
+ `name` field. Query commands may set `preview_rows` from 0 to 200. Native MongoDB
46
+ batches use `mongo.query`, `mongo.exec`, or `mongo.plan` with the command object
47
+ in `mongo`; the same cache, replay, idempotency, safety, and timeout fields
48
+ apply. Database commands may set `timeout_ms`; otherwise they use the 30-second
49
+ default.
package/docs/cli.md ADDED
@@ -0,0 +1,152 @@
1
+ # CLI reference
2
+
3
+ [StateQL](../README.md) · [Agents](agents.md) · [Connections](connections.md) · [CLI](cli.md) · [Results](results.md) · [Writes](writes.md) · [Batch](batch.md) · [Databases](databases.md) · [Library](library.md)
4
+
5
+ ```bash
6
+ stql connect <target> [--name NAME] [--read-only|--read-write]
7
+ stql connect --env ENV [--name NAME] [--read-only|--read-write]
8
+ stql connect --credential-ref REF [--name NAME] [--read-only|--read-write]
9
+ stql connect --profile NAME
10
+ stql disconnect
11
+ stql status
12
+ stql actor show
13
+ stql actor set-name <display-name>
14
+ stql profile add|update NAME [TARGET | --env ENV | --credential-ref REF]
15
+ [--read-only|--read-write]
16
+ stql profile list|show|remove
17
+ stql session start|list|show|summary|close
18
+ stql query <sql> [--params JSON | --param VALUE...] [--cache auto|bypass|require]
19
+ [--preview-rows 0..200]
20
+ stql filter <result-handle> <predicate> [--params JSON | --param VALUE...]
21
+ stql exec <sql> [--params JSON | --param VALUE...] [--idempotency-key KEY] [--replay]
22
+ [--allow-unbounded] [--allow-destructive]
23
+ stql mongo query|exec|plan '<EJSON command>' [--cache MODE] [--idempotency-key KEY]
24
+ [--replay] [--allow-unbounded] [--allow-destructive]
25
+ stql redis query '<JSON command>' [--cache auto|bypass|require]
26
+ stql redis exec '<JSON command>' [--idempotency-key KEY] [--replay]
27
+ stql redis plan '<JSON command>'
28
+ stql show|count|columns <result-handle>
29
+ stql rows <result-handle> [--offset N] [--limit N]
30
+ stql alias set <name> <result-handle>
31
+ stql export <result-handle> --output FILE [--format json|jsonl|csv]
32
+ stql inspect schema|table|collection|collections|columns|indexes|constraints [name]
33
+ stql objects [KIND] [--schema NAME] [--search TEXT] [--offset N|--cursor CURSOR] [--limit N]
34
+ stql object KIND NAME [IDENTITY] [--schema NAME]
35
+ stql transaction begin|status|commit|rollback [--isolation LEVEL]
36
+ stql plan <sql> [--params JSON | --param VALUE...] [--allow-unbounded] [--allow-destructive]
37
+ stql apply <plan-handle>
38
+ stql history [--limit N] [--offset N] [--category statement|introspection|management]
39
+ [--internal|--external]
40
+ stql receipt <operation-handle>
41
+ stql doctor
42
+ stql purge [expired|results|history|all]
43
+ stql capabilities
44
+ stql batch [commands.json|commands.jsonl|-] [--continue-on-error]
45
+ stql pipe [--continue-on-error]
46
+ stql help
47
+ ```
48
+
49
+ Global options: `--output MODE`, `--timeout-ms N`, `--max-cell-characters N`,
50
+ `--max-state-bytes N`, `--cache-ttl-seconds N`, `--result-ttl-seconds N`.
51
+
52
+ ## SQL parameters
53
+
54
+ For shell-safe positional parameters, repeat `--param`. JSON scalars become
55
+ their native types; other values remain strings.
56
+
57
+ ```bash
58
+ stql exec "INSERT INTO users (name, status) VALUES (?, ?)" `
59
+ --param Ada --param trial
60
+ ```
61
+
62
+ Use `--params JSON` for a JSON array or named parameters. Use
63
+ `--params-file FILE` when JSON is awkward to quote; `--params-file -` reads
64
+ JSON from standard input.
65
+
66
+ ## Catalog inspection
67
+
68
+ Use `objects` to list a bounded page and `object` to describe an entry:
69
+
70
+ ```bash
71
+ stql objects table --search users --limit 50
72
+ stql object table users
73
+ ```
74
+
75
+ SQL/MongoDB offsets are non-negative numbers; limits default to 50 and are at
76
+ most 200. Redis uses `--cursor` with the opaque numeric SCAN cursor string
77
+ returned as `next_offset`. Its limit is a SCAN `COUNT` hint with a hard 200-item
78
+ response bound. Redis pages are not snapshots and can be empty or contain
79
+ duplicates while keys change.
80
+
81
+ Search is a case-insensitive name substring for SQL/MongoDB and escaped glob
82
+ substring matching for Redis. No exact counts are forced. Supported kinds are
83
+ returned on every page: SQLite `table,view,trigger`; PostgreSQL
84
+ `table,view,function,trigger,enum`; MySQL `table,view,function,trigger`; MongoDB
85
+ `collection,view`; Redis `key`. PostgreSQL function identities include identity
86
+ arguments; pass the returned identity to `object` to distinguish overloads.
87
+
88
+ Library equivalents are `listObjects(filter, options?)` and
89
+ `describeObject(object, options?)`, where `object` is a returned structured
90
+ catalog entry. The older `inspect` commands remain available for SQL and
91
+ MongoDB, but not Redis. See [database support](databases.md) for native commands.
92
+
93
+ ## Output modes
94
+
95
+ CLI output defaults to compact, one-line `agent` JSON. Successful responses
96
+ flatten useful data and expose the primary durable ID as `handle`. Errors retain
97
+ their complete error object. Empty warnings and tracing metadata are omitted.
98
+
99
+ Agent mode also removes data that costs tokens but adds no information:
100
+
101
+ - `query`, `filter`, `show`, `mongo.query`, and `rows` return `columns` once and
102
+ each row as an array in that order. When rows have different keys (for
103
+ example, MongoDB documents), rows stay objects and `columns` is omitted.
104
+ - `next_offset` is present only when more rows exist.
105
+ - Null fields and `false` values of `cached`, `duplicate`, and
106
+ `duplicate_override` are omitted.
107
+ - `NON_DETERMINISTIC_PAGINATION` is reported only when more rows exist.
108
+ - `history` lists `session_id`, `actor_id`, `actor_name`, and `origin` once
109
+ when every entry shares them.
110
+ - `capabilities` lists enabled `features` as names.
111
+ - `objects` returns `columns` once and each entry as an array. `identity` is
112
+ omitted when it equals `schema.name` (or `name`) for every entry.
113
+ - `rows`, `count`, and `columns` do not repeat the handle you passed.
114
+ - Result `handle` is the generated alias, which cannot be reassigned. Full
115
+ `q_...` IDs work too and appear in `--output json`, `silent`, and history.
116
+ `alias` is present only when you chose a different name (batch `as`).
117
+ - `exec`, `mongo.exec`, and `apply` omit `actor_id`, `plan_id`,
118
+ `state_version_before`, and `committed` (use `status`). `receipt` keeps them.
119
+
120
+ ```json
121
+ {"ok":true,"handle":"katcitg6un","total":333,"next_offset":2,"columns":["id","name"],"rows":[[2,"Ada"],[3,"Grace"]]}
122
+ ```
123
+
124
+ ```json
125
+ {"ok":false,"error":{"code":"UNBOUNDED_MUTATION","message":"Mutation has no WHERE clause.","retryable":false,"executed":false,"override_flag":"--allow-unbounded"}}
126
+ ```
127
+
128
+ Other modes are:
129
+
130
+ - `--output json`: original pretty, verbose envelope.
131
+ - `--output jsonl`: verbose envelope on one line.
132
+ - `--output text`: short human-readable status.
133
+ - `--output silent`: only a successful handle.
134
+
135
+ Set `STQL_OUTPUT` to choose a mode globally. For `export`, `--output` names the
136
+ file, so use `STQL_OUTPUT` to choose the command's response mode. Library
137
+ responses always keep the full envelope.
138
+
139
+ ## Deadlines and cancellation
140
+
141
+ Database commands accept `--timeout-ms N`; the default is 30,000 ms. `Ctrl+C`
142
+ cancels active work.
143
+
144
+ - SQLite runs in a killable child process so long synchronous statements cannot
145
+ block StateQL's event loop.
146
+ - PostgreSQL combines server-side `statement_timeout` with client deadlines.
147
+ - MySQL deadlines destroy the active connection.
148
+ - MongoDB uses driver deadlines and closes stopped operations.
149
+
150
+ A timed-out or cancelled write may return `OUTCOME_UNKNOWN` when its commit
151
+ status cannot be proven. Cancellation stops that command's driver work; it does
152
+ not close the `StateQL` actor, and later commands remain usable.
@@ -0,0 +1,84 @@
1
+ # Connections and profiles
2
+
3
+ [StateQL](../README.md) · [Agents](agents.md) · [Connections](connections.md) · [CLI](cli.md) · [Results](results.md) · [Writes](writes.md) · [Batch](batch.md) · [Databases](databases.md) · [Library](library.md)
4
+
5
+ A connection accepts exactly one source: a direct target, `--env`,
6
+ `--credential-ref`, or `--profile`. Library and batch callers may additionally
7
+ attach a [password reference](library.md#password-references) to a literal
8
+ password-free remote target; it is not an additional connection source.
9
+
10
+ ```bash
11
+ stql connect <target> [--name NAME] [--read-only|--read-write]
12
+ stql connect --env ENV [--name NAME] [--read-only|--read-write]
13
+ stql connect --credential-ref REF [--name NAME] [--read-only|--read-write]
14
+ stql connect --profile NAME
15
+ stql disconnect
16
+ stql status
17
+ ```
18
+
19
+ Direct targets accept SQLite paths or password-free PostgreSQL, MySQL, MongoDB,
20
+ and Redis/Rediss URLs. Connections default to read-only unless a profile or an
21
+ explicit flag selects read-write access.
22
+
23
+ ## Environment-backed credentials
24
+
25
+ PostgreSQL, MySQL, MongoDB, and Redis credentials should come from environment
26
+ variables. The variable must contain the complete connection URL, not only its
27
+ password. Environment-backed SQLite paths require an explicit `sqlite:` prefix.
28
+ The URLs below are placeholders; supply real values through your secret-management
29
+ workflow rather than recording them in shell history.
30
+
31
+ ```bash
32
+ export APP_DATABASE_URL='postgres://user:password@host/app'
33
+ stql connect --env APP_DATABASE_URL --name app --read-only
34
+
35
+ export MYSQL_DATABASE_URL='mysql://user:password@host/app'
36
+ stql connect --env MYSQL_DATABASE_URL --name mysql-app --read-only
37
+
38
+ export MONGODB_URL='mongodb://user:password@host/app'
39
+ stql connect --env MONGODB_URL --name mongo-app --read-only
40
+
41
+ export REDIS_URL='rediss://user:password@host/0'
42
+ stql connect --env REDIS_URL --name redis-app --read-only
43
+
44
+ export SQLITE_DATABASE='sqlite:./app.sqlite'
45
+ stql connect --env SQLITE_DATABASE --name local --read-only
46
+ ```
47
+
48
+ StateQL stores no PostgreSQL, MySQL, MongoDB, or Redis password.
49
+ Credential-bearing URLs must be supplied through `--env` or an opaque full-URL
50
+ credential reference. SQLite paths remain persisted as connection metadata.
51
+
52
+ ## Local profiles
53
+
54
+ Profiles store exactly one connection target, environment-variable name, or
55
+ opaque credential reference together with read-only policy. A remote literal
56
+ target may additionally store a `password_ref`; SQLite, environment-backed, and
57
+ full-URL `credential_ref` profiles cannot. Credential values are never stored.
58
+ Profiles persist under `STQL_HOME` with other StateQL metadata, and list/show
59
+ responses include nullable `credential_ref` and `password_ref` fields.
60
+
61
+ ```bash
62
+ stql profile add local ./app.sqlite --read-only
63
+ stql profile add production --env PROD_DATABASE_URL --read-only
64
+ stql profile add hosted --credential-ref 'vault://team/app' --read-only
65
+ stql profile list
66
+ stql profile show production
67
+ stql profile update production --read-only
68
+ stql connect local
69
+ stql connect --profile production
70
+ ```
71
+
72
+ Credential references are bounded nonempty opaque strings; StateQL does not
73
+ apply environment-variable syntax or normalization to them. They can only be
74
+ resolved by a trusted host `CredentialResolver`, so the standalone CLI may
75
+ store them in profiles but cannot connect with them.
76
+
77
+ A bare connection target matching a profile name resolves to that profile;
78
+ otherwise it remains a path or database URL.
79
+
80
+ `profile update` changes subsequent connections, not an already-open connection.
81
+ Omitting the source keeps it; supplying a new source replaces the old one.
82
+ Password references are configured through the library or batch API, not a CLI
83
+ `--password-ref` flag. See [safe profile updates](library.md#safe-profile-updates)
84
+ for source-replacement and downgrade restrictions.
package/docs/databases.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Database support
2
2
 
3
- [Home](../README.md) · [Usage](usage.md) · [Database support](databases.md) · [TypeScript library](library.md)
3
+ [StateQL](../README.md) · [Agents](agents.md) · [Connections](connections.md) · [CLI](cli.md) · [Results](results.md) · [Writes](writes.md) · [Batch](batch.md) · [Databases](databases.md) · [Library](library.md)
4
4
 
5
5
  - [Driver notes](#driver-notes)
6
6
  - [SQL statement support](#sql-statement-support)
@@ -10,9 +10,9 @@
10
10
  - [Native MongoDB](#native-mongodb)
11
11
  - [Native Redis](#native-redis)
12
12
 
13
- Connect using the [usage guide](usage.md#connections-and-profiles). All writes
13
+ Connect using the [usage guide](connections.md). All writes
14
14
  require a read-write connection; SQL/MongoDB approvals and retry rules are
15
- covered under [write safety](usage.md#write-safety).
15
+ covered under [write safety](writes.md).
16
16
 
17
17
  ## Driver notes
18
18
 
@@ -37,7 +37,7 @@ StateQL parses and classifies one `SELECT`, `INSERT`, `REPLACE`, `UPDATE`,
37
37
  `node-sql-parser`, subject to dialect support and safety validation. Reads use
38
38
  `query`; mutations and DDL use durable `exec`/`plan`/`apply` operations. Raw
39
39
  transaction-control SQL is unsupported: use
40
- [staged transactions](usage.md#transactions), not `BEGIN` or `COMMIT` statements.
40
+ [staged transactions](writes.md#transactions), not `BEGIN` or `COMMIT` statements.
41
41
  MongoDB and Redis use separate native command APIs.
42
42
 
43
43
  Unrecognized or parser-unsupported forms remain blocked.
package/docs/library.md CHANGED
@@ -1,9 +1,10 @@
1
1
  # TypeScript library
2
2
 
3
- [Home](../README.md) · [Usage](usage.md) · [Database support](databases.md) · [TypeScript library](library.md)
3
+ [StateQL](../README.md) · [Agents](agents.md) · [Connections](connections.md) · [CLI](cli.md) · [Results](results.md) · [Writes](writes.md) · [Batch](batch.md) · [Databases](databases.md) · [Library](library.md)
4
4
 
5
5
  - [Getting started](#getting-started)
6
6
  - [Responses and command context](#responses-and-command-context)
7
+ - [Compact responses for model context](#compact-responses-for-model-context)
7
8
  - [Actor workspaces](#actor-workspaces)
8
9
  - [Credential resolution](#credential-resolution)
9
10
  - [Safe profile updates](#safe-profile-updates)
@@ -49,10 +50,11 @@ the durable session. Await active commands before closing. Use `disconnect()`
49
50
  only when you intend to remove the session's shared active connection.
50
51
 
51
52
  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
53
+ `maxStateBytes`, `maxCellCharacters`, `cacheTtlSeconds`, and
54
+ `resultTtlSeconds`. Database calls also
55
+ accept `signal` for cancellation. See [limits](results.md#result-lifetime-and-limits)
56
+ and [deadlines](cli.md#deadlines-and-cancellation) for defaults and behavior.
57
+ The same [write safety](writes.md) and
56
58
  [database restrictions](databases.md) apply to library calls.
57
59
 
58
60
  ## Responses and command context
@@ -93,6 +95,23 @@ direct calls and `executeCommand(command)` calls are recorded as `legacy`.
93
95
  `BatchCommand` cannot attribute the command. `batch` accepts the same trusted
94
96
  context as `options.executionContext` for all commands in that batch.
95
97
 
98
+ ### Compact responses for model context
99
+
100
+ When a response goes into a model's context, pass it through `agentResponse`
101
+ with the batch command name. It returns the same compact shape as the CLI
102
+ `agent` output mode (see [output modes](cli.md#output-modes)). Keep the full
103
+ response for application logic.
104
+
105
+ ```ts
106
+ import { agentResponse } from "@fadhilp/stateql";
107
+
108
+ const response = await stateql.executeCommand(command, { origin: "model" });
109
+ const forModel = JSON.stringify(agentResponse(response, command.command));
110
+ ```
111
+
112
+ `objects.list` and `object.describe` are accepted as names for catalog
113
+ responses from `listObjects` and `describeObject`.
114
+
96
115
  ## Actor workspaces
97
116
 
98
117
  `StateQL.forWorkspace(...)` is a trusted-host primitive that atomically creates
@@ -0,0 +1,78 @@
1
+ # Durable state and result reuse
2
+
3
+ [StateQL](../README.md) · [Agents](agents.md) · [Connections](connections.md) · [CLI](cli.md) · [Results](results.md) · [Writes](writes.md) · [Batch](batch.md) · [Databases](databases.md) · [Library](library.md)
4
+
5
+ State metadata lives under `STQL_HOME`, or the platform data directory when
6
+ unset. StateQL keeps connections, sessions, handles, aliases, cache entries,
7
+ plans, transactions, history, and receipts available across CLI invocations.
8
+ Stored results contain row data, so protect this directory like the database.
9
+
10
+ ## Sessions and actors
11
+
12
+ Set `STQL_SESSION` to select a named session and `STQL_ACTOR` to select an
13
+ attached actor. A session is a shared workspace: attached actors reuse its
14
+ connection, handles, aliases, cache, and state version. Plans and staged
15
+ transactions remain owned by the actor that created them.
16
+
17
+ Callers that omit `actor` keep the legacy behavior where the actor ID is the
18
+ session name.
19
+
20
+ Actor IDs are immutable authorization and ownership identities. Each actor also
21
+ has a mutable display name, initially equal to its ID. The selected actor may
22
+ change only its own display name with `stql actor set-name <display-name>`;
23
+ names are trimmed, limited to 80 characters, and cannot contain control
24
+ characters. Display names are contextual metadata and must not be used for
25
+ authorization.
26
+
27
+ History records both the stable `actor_id` and the `actor_name` in effect when
28
+ the command began. Renaming therefore does not rewrite earlier attribution; the
29
+ rename is itself recorded as an `actor.set-name` management command.
30
+
31
+ ## Result lifetime and limits
32
+
33
+ Result rows are materialized locally for durable access. By default, read cache
34
+ entries expire after five minutes, and materialized handles expire after 24
35
+ hours. Expired results and plans are deleted the next time StateQL opens.
36
+
37
+ By default, queries exceeding 10,000 rows or 16 MiB of serialized row data fail
38
+ before persistence. Narrow the `WHERE` clause, add `LIMIT`, or select fewer
39
+ columns. These caps bound persisted materialization; the independent deadline
40
+ bounds execution time. Native commands may impose stricter
41
+ [database-specific limits](databases.md).
42
+
43
+ Query responses preview five rows by default. Use `--preview-rows N` to return
44
+ between 0 and 200 preview rows without rerunning or changing the stored result.
45
+ Additional rows remain available through `stql rows <result-handle>`.
46
+
47
+ Cells longer than 200 characters are returned as
48
+ `{"type":"text","length":N,"preview":"..."}`. Change the limit with
49
+ `--max-cell-characters N` (library: `maxCellCharacters`), or use `export` for
50
+ full values.
51
+
52
+ Command history keeps the latest 10,000 entries per session. SQLite cache reuse
53
+ also checks the database file signature. PostgreSQL, MySQL, and MongoDB cache
54
+ reuse is labeled `ttl_based` and is never authoritative.
55
+
56
+ StateQL limits persisted result payloads to 256 MiB by default. When that quota
57
+ is reached it removes the oldest unaliased results; aliases remain protected. A
58
+ single result that cannot fit fails with `STATE_QUOTA_EXCEEDED`. Configure the
59
+ limit with `maxStateBytes` in the library or `--max-state-bytes` in the CLI.
60
+ Cache and result retention can be configured with `cacheTtlSeconds` and
61
+ `resultTtlSeconds`, or their `--cache-ttl-seconds` and
62
+ `--result-ttl-seconds` CLI equivalents.
63
+
64
+ `stql doctor` checks SQLite integrity and stored payload shapes without printing
65
+ SQL, parameters, or result values. `stql purge` removes expired data by default;
66
+ use `results`, `history`, or `all` for explicit session cleanup. On POSIX
67
+ systems, StateQL removes group and world access from its state directory,
68
+ database, and SQLite sidecar files.
69
+
70
+ ## Local filtering
71
+
72
+ `filter` evaluates one scalar SQLite predicate against a stored result. It
73
+ preserves source order, state metadata, and expiry, and never accesses the
74
+ original database.
75
+
76
+ Use parameters for values. Subqueries, query-shaping clauses, and
77
+ non-allowlisted functions are rejected. Common deterministic functions such as
78
+ `lower`, `upper`, `length`, and `coalesce` are supported.
package/docs/writes.md ADDED
@@ -0,0 +1,40 @@
1
+ # Write safety
2
+
3
+ [StateQL](../README.md) · [Agents](agents.md) · [Connections](connections.md) · [CLI](cli.md) · [Results](results.md) · [Writes](writes.md) · [Batch](batch.md) · [Databases](databases.md) · [Library](library.md)
4
+
5
+ Writes require a read-write connection. Destructive and unbounded SQL/MongoDB
6
+ operations require `--allow-destructive` and `--allow-unbounded`, respectively.
7
+ The flags are independent.
8
+
9
+ `plan` validates and stores a write for later application. A plan persists only
10
+ the flags explicitly supplied when it is created; `apply` never adds
11
+ authorization.
12
+
13
+ Use an idempotency key to protect retryable writes from duplicate execution:
14
+
15
+ ```bash
16
+ stql exec "UPDATE jobs SET claimed = 1 WHERE id = ?" \
17
+ --param 42 \
18
+ --idempotency-key claim-job-42
19
+ ```
20
+
21
+ If a write starts but StateQL cannot safely record its final outcome, it returns
22
+ `OUTCOME_UNKNOWN` and blocks automatic replay. Inspect database state before
23
+ using `--replay`. Interrupted commits remain fail-closed; stale `committing`
24
+ records become `outcome_unknown` after five minutes.
25
+
26
+ ## Transactions
27
+
28
+ Transactions are staged in local state so they survive CLI invocations, then
29
+ executed atomically on commit. While a transaction is active, StateQL rejects
30
+ database reads, plans, connection changes, and disconnects. Commit or roll back
31
+ first.
32
+
33
+ SQLite supports `serializable`. PostgreSQL and MySQL also support
34
+ `repeatable read`, `read committed`, and `read uncommitted`. Server reads run
35
+ inside database-enforced read-only transactions. MySQL staged transactions
36
+ reject DDL because MySQL implicitly commits those statements.
37
+ MongoDB transactions use `snapshot` isolation and require a replica set or
38
+ sharded deployment; standalone servers do not support them.
39
+ Redis does not support StateQL staged transactions; see its
40
+ [native write guarantees](databases.md#native-redis).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fadhilp/stateql",
3
- "version": "0.13.3",
3
+ "version": "0.15.0",
4
4
  "description": "Stateful, agent-oriented database CLI for safe result reuse",
5
5
  "repository": {
6
6
  "type": "git",