@fadhilp/stateql 0.15.0 → 0.15.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/README.md CHANGED
@@ -40,11 +40,23 @@ stql filter katcitg6un "name LIKE ?" --param "A%"
40
40
  stql export katcitg6un --output users.csv
41
41
  ```
42
42
 
43
+ ## Agent skill
44
+
45
+ `skills/stateql` is an [Agent Skill](https://agentskills.io) that teaches coding
46
+ agents to use `stql` safely and with few tokens. Copy the folder into your
47
+ agent's skills directory, for example for Claude Code:
48
+
49
+ ```bash
50
+ cp -r "$(npm root -g)/@fadhilp/stateql/skills/stateql" ~/.claude/skills/
51
+ ```
52
+
53
+ Use `.claude/skills/` inside a project to share it with your team.
54
+
43
55
  ## Documentation
44
56
 
45
57
  | Page | Contents |
46
58
  | --- | --- |
47
- | [Agent guide](docs/agents.md) | The short version for agents: connect, query, reuse, save tokens |
59
+ | [Agent skill](skills/stateql/SKILL.md) | Rules, workflow, response format, quoting, and errors for coding agents |
48
60
  | [Connections](docs/connections.md) | Targets, environment credentials, profiles |
49
61
  | [CLI reference](docs/cli.md) | Commands, parameters, catalog, output modes, deadlines |
50
62
  | [Results and state](docs/results.md) | Sessions, actors, limits, caching, local filtering |
package/dist/src/cli.js CHANGED
@@ -406,7 +406,7 @@ function parseParameters(value, values, file) {
406
406
  : value;
407
407
  let parsedValue;
408
408
  try {
409
- parsedValue = JSON.parse(json);
409
+ parsedValue = JSON.parse(withoutBom(json));
410
410
  }
411
411
  catch {
412
412
  throw new Error(`Invalid JSON from ${file ? "--params-file" : "--params"}. ` +
@@ -447,6 +447,10 @@ async function* readBatchCommands(source) {
447
447
  yield parseBatchCommand(parseBatchJson(line, `line ${lineNumber}`), `line ${lineNumber}`);
448
448
  }
449
449
  }
450
+ // PowerShell pipes and Out-File/Notepad files can start with a UTF-8 BOM, which JSON.parse rejects.
451
+ function withoutBom(value) {
452
+ return value.startsWith("") ? value.slice(1) : value;
453
+ }
450
454
  function parseBatchCommand(value, location) {
451
455
  if (!value ||
452
456
  typeof value !== "object" ||
@@ -457,7 +461,7 @@ function parseBatchCommand(value, location) {
457
461
  }
458
462
  function parseBatchJson(value, location) {
459
463
  try {
460
- return JSON.parse(value);
464
+ return JSON.parse(withoutBom(value));
461
465
  }
462
466
  catch {
463
467
  throw new Error(`Invalid JSON at ${location}.`);
@@ -598,7 +602,7 @@ Credential refs require a trusted host CredentialResolver; the standalone CLI ca
598
602
  State: --max-state-bytes N, --cache-ttl-seconds N, --result-ttl-seconds N.
599
603
  Output: --output agent|json|jsonl|text|silent (default: agent).
600
604
  Agent rows: arrays in "columns" order (objects when shapes differ). next_offset only when more rows exist.
601
- Agent output omits null fields and false cached/duplicate flags. Guide: docs/agents.md.
605
+ Agent output omits null fields and false cached/duplicate flags. Agent skill: skills/stateql/SKILL.md.
602
606
  Batch/pipe accept JSON array files or JSONL streams. Stop on first error.`;
603
607
  }
604
608
  function packageVersion() {
package/docs/batch.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Batch and pipes
2
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)
3
+ [StateQL](../README.md) · [Agent skill](../skills/stateql/SKILL.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
  `batch` reads a JSON array from a `.json` file or JSONL from a `.jsonl` file.
6
6
  `pipe` reads JSONL from standard input. Commands run sequentially and stop on
package/docs/cli.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # CLI reference
2
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)
3
+ [StateQL](../README.md) · [Agent skill](../skills/stateql/SKILL.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
  ```bash
6
6
  stql connect <target> [--name NAME] [--read-only|--read-write]
@@ -1,6 +1,6 @@
1
1
  # Connections and profiles
2
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)
3
+ [StateQL](../README.md) · [Agent skill](../skills/stateql/SKILL.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
  A connection accepts exactly one source: a direct target, `--env`,
6
6
  `--credential-ref`, or `--profile`. Library and batch callers may additionally
package/docs/databases.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Database support
2
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)
3
+ [StateQL](../README.md) · [Agent skill](../skills/stateql/SKILL.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)
package/docs/library.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # TypeScript library
2
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)
3
+ [StateQL](../README.md) · [Agent skill](../skills/stateql/SKILL.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)
package/docs/results.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Durable state and result reuse
2
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)
3
+ [StateQL](../README.md) · [Agent skill](../skills/stateql/SKILL.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
  State metadata lives under `STQL_HOME`, or the platform data directory when
6
6
  unset. StateQL keeps connections, sessions, handles, aliases, cache entries,
package/docs/writes.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Write safety
2
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)
3
+ [StateQL](../README.md) · [Agent skill](../skills/stateql/SKILL.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
  Writes require a read-write connection. Destructive and unbounded SQL/MongoDB
6
6
  operations require `--allow-destructive` and `--allow-unbounded`, respectively.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fadhilp/stateql",
3
- "version": "0.15.0",
3
+ "version": "0.15.1",
4
4
  "description": "Stateful, agent-oriented database CLI for safe result reuse",
5
5
  "repository": {
6
6
  "type": "git",
@@ -22,6 +22,7 @@
22
22
  "dist/src",
23
23
  "README.md",
24
24
  "docs",
25
+ "skills",
25
26
  "LICENSE"
26
27
  ],
27
28
  "scripts": {
@@ -0,0 +1,166 @@
1
+ ---
2
+ name: stateql
3
+ description: Query, inspect, and safely change SQLite, PostgreSQL, MySQL, MongoDB, and Redis databases with the `stql` CLI, which stores each result behind a short handle and returns compact JSON. Use when the user asks to look at a database schema, run SQL, read or page through rows, count or filter query results, export data, or make a guarded write.
4
+ ---
5
+
6
+ # StateQL (`stql`)
7
+
8
+ `stql` runs a query once, stores the full result locally, and returns a short
9
+ preview plus a handle. Page, filter, count, and export from the handle without
10
+ running the query again. Output is one line of JSON per command.
11
+
12
+ If `stql --version` fails, ask the user before installing
13
+ `npm install -g @fadhilp/stateql` (Node.js 22.16+).
14
+
15
+ ## Rules
16
+
17
+ 1. Set a session once per task: `export STQL_SESSION=<short-task-name>`
18
+ (PowerShell: `$env:STQL_SESSION = "<name>"`). Without it, every task shares
19
+ the `default` session.
20
+ 2. Connect read-only (the default). Use `--read-write` only when the user asked
21
+ for a change.
22
+ 3. Never add `--allow-destructive`, `--allow-unbounded`, or `--replay` unless the
23
+ user explicitly approved that operation. They are approvals, not fixes.
24
+ 4. Never put a password in a command. Remote URLs go in an environment variable
25
+ that you pass with `--env`.
26
+ 5. Pass values as parameters (`--param`), never by building SQL strings.
27
+ 6. Do not rerun a query to see more rows. Use its handle.
28
+
29
+ ## Connect
30
+
31
+ ```bash
32
+ stql status # already connected in this session?
33
+ stql connect ./app.sqlite # SQLite path, read-only
34
+ stql connect --env DATABASE_URL # postgres://, mysql://, mongodb://, redis:// URL in the variable
35
+ stql connect --env DATABASE_URL --read-write # only for requested changes
36
+ ```
37
+
38
+ `status` without a `connection` field means no connection is open.
39
+
40
+ ## Read workflow
41
+
42
+ 1. Find objects: `stql objects table --search order`
43
+ 2. Read the shape: `stql object table orders` (returns the DDL or column list)
44
+ 3. Query only the columns you need, with `ORDER BY`:
45
+ `stql query 'SELECT id, total FROM orders WHERE status = $1 ORDER BY id' --param paid`
46
+ 4. Read the response (see below). `total` is the full row count, so you do not
47
+ need a separate `COUNT(*)`.
48
+ 5. More rows: `stql rows <handle> --offset <next_offset> --limit 50`
49
+ (default 20, maximum 1000).
50
+ 6. Narrow down: `stql filter <handle> 'CAST(total AS REAL) > ?' --param 100`.
51
+ This runs locally on the stored rows in SQLite syntax, always with `?`, and
52
+ returns a new handle. PostgreSQL `numeric`/`bigint` and MySQL `DECIMAL` values
53
+ are stored as strings (`"7.50"`), and SQLite treats every string as greater
54
+ than every number, so `total > ?` silently matches all rows. Wrap such
55
+ columns in `CAST(... AS REAL)`, or filter in SQL with a new query.
56
+ 7. Save all rows: `stql export <handle> --output rows.csv` (`--format json|jsonl|csv`).
57
+
58
+ Use `--preview-rows N` (0 to 200) on `query` to change the preview size. Use
59
+ `--cache bypass` when data may have changed outside this session; writes made
60
+ through `stql` invalidate the cache automatically.
61
+
62
+ ## Response format
63
+
64
+ ```json
65
+ {"ok":true,"handle":"katcitg6un","total":331,"next_offset":5,"columns":["id","name"],"rows":[[2,"Ada"],[3,"Grace"],[5,"Linus"],[6,"Alan"],[8,"Edsger"]]}
66
+ ```
67
+
68
+ | Field | Meaning |
69
+ | --- | --- |
70
+ | `handle` | Stable result handle. Pass it to `rows`, `filter`, `count`, `columns`, `show`, `export`. |
71
+ | `columns` + `rows` | Each row is an array in `columns` order. If rows have different keys (MongoDB documents), rows are objects and `columns` is absent. |
72
+ | `total` | Rows in the stored result. |
73
+ | `next_offset` | Present only when more rows exist. Absent means you have every row. |
74
+ | `alias` | Present only when you named the result (batch `as`). |
75
+ | `warnings` | For example `NON_DETERMINISTIC_PAGINATION`: add `ORDER BY` before paging. |
76
+
77
+ - Exact numbers keep their precision as strings: PostgreSQL `numeric` and
78
+ `bigint`, MySQL `DECIMAL`.
79
+ - A long cell comes back as `{"type":"text","length":20000,"preview":"..."}`.
80
+ Use `--max-cell-characters N` or `export` for the full value.
81
+ - Null fields and false `cached`/`duplicate` flags are omitted.
82
+ - `rows`, `count`, and `columns` do not repeat the handle you passed.
83
+
84
+ ## Placeholders and shell quoting
85
+
86
+ | Database | Placeholders |
87
+ | --- | --- |
88
+ | SQLite, MySQL | `?` |
89
+ | PostgreSQL | `$1`, `$2`, ... |
90
+ | `filter` predicates (all databases) | `?` |
91
+
92
+ - Put SQL in single quotes. In bash and PowerShell, `"$1"` expands to an empty
93
+ string and breaks the query.
94
+ - Use parameters instead of string literals, so you do not need quotes inside
95
+ quotes: `--param 'Ada Lovelace'`.
96
+ - **Windows PowerShell 5.1** removes the double quotes inside JSON arguments, so
97
+ `--params '[1]'` is fine but `stql redis query '{"command":"GET"}'` breaks.
98
+ Send JSON on standard input instead: `'<one JSON command>' | stql pipe` (see
99
+ below), or escape every inner quote as `\"`.
100
+
101
+ ## Several steps in one call
102
+
103
+ `stql pipe` reads one JSON command per line and prints one response per line.
104
+ It stops at the first error unless you pass `--continue-on-error`. Fields use
105
+ snake_case; `as` gives a result a name that later lines can use.
106
+
107
+ ```bash
108
+ printf '%s\n' \
109
+ '{"command":"query","sql":"SELECT id, email FROM users WHERE status = $1 ORDER BY id","params":["active"],"as":"active"}' \
110
+ '{"command":"filter","handle":"active","where":"email LIKE ?","params":["%@example.com"],"as":"example"}' \
111
+ '{"command":"rows","handle":"example","offset":5,"limit":20}' | stql pipe
112
+ ```
113
+
114
+ Command names match the CLI: `query`, `filter`, `rows`, `count`, `columns`,
115
+ `show`, `export`, `exec`, `plan`, `apply`, `objects.list`, `object.describe`,
116
+ `inspect`, `mongo.query`, `redis.query`, `transaction.begin`, and so on.
117
+ `stql batch commands.json` runs a JSON array from a file.
118
+
119
+ ## Errors
120
+
121
+ Errors look like `{"ok":false,"error":{"code":"...","message":"...","retryable":false,"executed":false}}`.
122
+ Retry only when `retryable` is `true`. `executed:false` means nothing ran.
123
+
124
+ | Code | What to do |
125
+ | --- | --- |
126
+ | `INVALID_SQL` | Fix the SQL at the reported line and column. Check the placeholder style. |
127
+ | `QUERY_FAILED` | Read the database message (missing table or column, type error). Retry only if `retryable`. |
128
+ | `READ_ONLY_CONNECTION` | Ask the user before you reconnect with `--read-write`. |
129
+ | `UNBOUNDED_MUTATION` | Add a `WHERE` clause. Use `--allow-unbounded` only with user approval. |
130
+ | `DESTRUCTIVE_OPERATION_BLOCKED` | `DELETE`, `DROP`, `ALTER`, `TRUNCATE`, and `REPLACE` need user approval, then `--allow-destructive`. |
131
+ | `POTENTIAL_DUPLICATE_WRITE` | The same write already ran (`previous_operation_id`). Do not use `--replay` unless the user wants it to run again. |
132
+ | `OUTCOME_UNKNOWN` | The write may or may not have committed. Check the data with a query before anything else. |
133
+ | `OUTPUT_LIMIT_EXCEEDED` | Results are capped at 10,000 rows and 16 MiB. Add `WHERE`/`LIMIT` or select fewer columns; page `rows` in steps of at most 1000. |
134
+ | `RESULT_NOT_FOUND`, `RESULT_EXPIRED` | Wrong session or the result expired (24 h). Run the query again. |
135
+ | `STALE_PLAN` | Data changed after `plan`. Create a new plan. |
136
+ | `TRANSACTION_FAILED` | A staged transaction is open. Reads wait until you commit or roll back. |
137
+ | `DEADLINE_EXCEEDED` | The default timeout is 30 s. Narrow the query or pass `--timeout-ms`. |
138
+ | `CONNECTION_FAILED`, `CONNECTION_NOT_FOUND` | Check `stql status`, the URL variable, and the network. |
139
+
140
+ ## Writes
141
+
142
+ Writes need a read-write connection and the user's request. Read
143
+ [reference/writes.md](reference/writes.md) before `exec`, `plan`/`apply`, or a
144
+ transaction. In short:
145
+
146
+ ```bash
147
+ stql exec 'UPDATE jobs SET claimed = 1 WHERE id = $1' --param 42 --idempotency-key claim-job-42
148
+ ```
149
+
150
+ A successful write returns `affected_rows` and `status` (`committed`, or
151
+ `pending` inside a transaction).
152
+
153
+ ## MongoDB and Redis
154
+
155
+ These use native commands, not SQL. Read [reference/native.md](reference/native.md)
156
+ before you use `stql mongo` or `stql redis`.
157
+
158
+ ## Other commands
159
+
160
+ | Command | Use |
161
+ | --- | --- |
162
+ | `stql inspect columns\|indexes\|constraints <table>` | Column, index, and constraint details |
163
+ | `stql history --limit 10` | Recent commands in this session |
164
+ | `stql receipt <operation-handle>` | Full record of a write |
165
+ | `stql session summary` | Open results and recent writes |
166
+ | `stql help` | Command syntax |
@@ -0,0 +1,61 @@
1
+ # MongoDB and Redis
2
+
3
+ SQL commands (`query`, `exec`, `plan`) are rejected on these connections. Pass
4
+ the native command as one JSON argument. In Windows PowerShell 5.1, send it
5
+ through `stql pipe` instead (field `mongo` or `redis`):
6
+
7
+ ```powershell
8
+ '{"command":"mongo.query","mongo":{"operation":"find","collection":"users","filter":{"active":true},"options":{"limit":20}}}' | stql pipe
9
+ ```
10
+
11
+ ## MongoDB
12
+
13
+ Commands use Extended JSON (EJSON): ObjectIds are `{"$oid":"..."}`, dates are
14
+ `{"$date":"2026-01-01T00:00:00Z"}`.
15
+
16
+ ```bash
17
+ stql objects collection # list collections
18
+ stql inspect columns users # fields seen in sampled documents
19
+ stql mongo query '{"operation":"find","collection":"users","filter":{"active":true},"options":{"projection":{"email":1},"sort":{"_id":1},"limit":50}}'
20
+ stql mongo query '{"operation":"aggregate","collection":"orders","pipeline":[{"$match":{"status":"paid"}},{"$group":{"_id":"$user_id","n":{"$sum":1}}}]}'
21
+ ```
22
+
23
+ | Operation | Keys |
24
+ | --- | --- |
25
+ | `find` | `collection`, `filter`, `options`: `projection`, `sort`, `skip`, `limit`, `hint`, `collation` |
26
+ | `aggregate` | `collection`, `pipeline`, `options`: `allowDiskUse`, `hint`, `collation` |
27
+ | `insertOne` / `insertMany` | `document` / `documents` |
28
+ | `updateOne` / `updateMany` | `filter`, `update`, `options`: `upsert`, `collation`, `hint` |
29
+ | `replaceOne` | `filter`, `replacement` |
30
+ | `deleteOne` / `deleteMany` | `filter` |
31
+
32
+ - Writes: `stql mongo exec '<command>'`; review first with `stql mongo plan`.
33
+ Empty filters need `--allow-unbounded`; deletes and replacements need
34
+ `--allow-destructive`. Both need user approval.
35
+ - `$out`, `$merge`, `$where`, `$function`, `$accumulator`, and server-side
36
+ JavaScript are rejected.
37
+ - Documents with different fields come back as objects, not row arrays.
38
+ - The cache cannot see changes made outside this session. Use
39
+ `--cache bypass` for a fresh read.
40
+
41
+ ## Redis
42
+
43
+ Commands are `{"command":"NAME","args":["..."]}`. All arguments are strings.
44
+
45
+ ```bash
46
+ stql objects key --search session: --limit 50 # SCAN-based; continue with --cursor <next_offset>
47
+ stql object key session:42 # type, TTL, and a bounded value
48
+ stql redis query '{"command":"HGET","args":["user:42","email"]}'
49
+ stql redis exec '{"command":"SET","args":["app:status","ready"]}' --idempotency-key status-ready
50
+ ```
51
+
52
+ | Kind | Allowed commands |
53
+ | --- | --- |
54
+ | Read (`redis query`) | `GET`, `MGET`, `TYPE`, `EXISTS`, `TTL`, `PTTL`, `HGET`, `HMGET`, bounded `LRANGE`, bounded `SCAN`/`HSCAN`/`SSCAN`/`ZSCAN` |
55
+ | Write (`redis exec`, `redis plan`) | one key: `SET`, `DEL`, `HSET`, `HDEL`, `LPUSH`, `RPUSH`, `SADD`, `SREM`, `ZADD`, `ZREM` |
56
+
57
+ - `KEYS`, scripts, pub/sub, blocking commands, and admin commands are rejected.
58
+ - Key pages can be empty or repeat keys while data changes. Keep following
59
+ `next_offset` until it is absent.
60
+ - `redis plan` then `stql apply` fails with `ROW_CONFLICT` if the key changed
61
+ in between. There are no staged transactions.
@@ -0,0 +1,70 @@
1
+ # Writes, plans, and transactions
2
+
3
+ All writes need a read-write connection (`stql connect ... --read-write`) and a
4
+ change the user asked for.
5
+
6
+ ## Safety gates
7
+
8
+ | Statement | Needs |
9
+ | --- | --- |
10
+ | `UPDATE`/`DELETE` without `WHERE`, `TRUNCATE` | `--allow-unbounded` |
11
+ | `DELETE`, `DROP`, `ALTER`, `TRUNCATE`, `REPLACE`, SQLite `INSERT/UPDATE OR REPLACE` | `--allow-destructive` |
12
+ | MongoDB empty update/replace/delete filter | `--allow-unbounded` |
13
+ | MongoDB `deleteOne`, `deleteMany`, `replaceOne` | `--allow-destructive` |
14
+
15
+ The two flags are independent: a `DELETE` without `WHERE` needs both. Add a
16
+ flag only after the user approved that exact operation. When a gate blocks a
17
+ command, the error has `override_flag`; show the user the statement and ask.
18
+
19
+ ## Direct write
20
+
21
+ ```bash
22
+ stql exec 'UPDATE jobs SET claimed = 1 WHERE id = $1' --param 42 --idempotency-key claim-job-42
23
+ ```
24
+
25
+ ```json
26
+ {"ok":true,"handle":"op_...","statement_type":"update","affected_rows":1,"status":"committed","state_version_after":"sv_1"}
27
+ ```
28
+
29
+ - Check `affected_rows` against what you expected.
30
+ - Use `--idempotency-key` for any write you might retry. The same key never
31
+ runs twice.
32
+ - Running the same statement with the same parameters again returns
33
+ `POTENTIAL_DUPLICATE_WRITE` with `previous_operation_id`. Add `--replay` only
34
+ if the user wants it to run again.
35
+ - `OUTCOME_UNKNOWN` (timeout or lost connection during the write) blocks
36
+ automatic replay. Query the data to find out whether the write happened, tell
37
+ the user, and only then decide about `--replay`.
38
+ - `stql receipt <op-handle>` shows the full record of a write.
39
+
40
+ ## Plan, then apply
41
+
42
+ Use a plan when the user should review a write before it runs.
43
+
44
+ ```bash
45
+ stql plan 'DELETE FROM sessions WHERE expires_at < $1' --param 2026-01-01 --allow-destructive
46
+ # show the user statement_type, required_overrides, and expires_at
47
+ stql apply <plan-handle>
48
+ ```
49
+
50
+ - A plan keeps only the approval flags given to `plan`; `apply` never adds any.
51
+ - If data changed after `plan`, `apply` returns `STALE_PLAN`. Create a new plan.
52
+ - Plans expire after 10 minutes.
53
+
54
+ ## Staged transactions
55
+
56
+ ```bash
57
+ stql transaction begin # optional: --isolation 'repeatable read'
58
+ stql exec 'UPDATE accounts SET balance = balance - $1 WHERE id = $2' --params '[50, 1]'
59
+ stql exec 'UPDATE accounts SET balance = balance + $1 WHERE id = $2' --params '[50, 2]'
60
+ stql transaction status
61
+ stql transaction commit # or: stql transaction rollback
62
+ ```
63
+
64
+ - Writes are stored locally (`status: "pending"`) and run atomically at commit.
65
+ - While a transaction is open, reads, plans, and connection changes return
66
+ `TRANSACTION_FAILED`. Query what you need before `begin`.
67
+ - Isolation: SQLite `serializable`; PostgreSQL and MySQL also `repeatable read`,
68
+ `read committed`, `read uncommitted`.
69
+ - MySQL transactions reject DDL. MongoDB transactions need a replica set and use
70
+ `snapshot` isolation. Redis has no staged transactions.
package/docs/agents.md DELETED
@@ -1,72 +0,0 @@
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).