@fadhilp/stateql 0.13.1 → 0.13.3

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
@@ -85,7 +85,6 @@ See [write safety](docs/usage.md#write-safety),
85
85
  | [Usage](docs/usage.md) | Connections, CLI reference, results, sessions, limits, writes, transactions, batch and pipes |
86
86
  | [Database support](docs/databases.md) | SQL dialects, diagnostics, maintenance, native MongoDB and Redis commands |
87
87
  | [TypeScript library](docs/library.md) | Connection setup, response handling, cleanup, actors, workspaces, and credential resolution |
88
- | [SQL command roadmap](SQL_COMMAND_ROADMAP.md) | Development priorities and requirements for extending SQL support |
89
88
 
90
89
  Run `stql --help` for command syntax or `stql capabilities` for capability details.
91
90
 
@@ -1,8 +1,12 @@
1
1
  import { fork } from "node:child_process";
2
- import { createConnection as createMySqlConnection, } from "mysql2";
3
- import { Client, types as pgTypes } from "pg";
2
+ import { createRequire } from "node:module";
4
3
  import { StateQLError } from "./errors.js";
5
4
  import { isSqlParameters, parseJson, toJsonSafe } from "./util.js";
5
+ const require = createRequire(import.meta.url);
6
+ let mysqlModule;
7
+ let postgresModule;
8
+ const mysql = () => (mysqlModule ??= require("mysql2"));
9
+ const postgres = () => (postgresModule ??= require("pg"));
6
10
  export class AdapterExecutionError extends Error {
7
11
  reason;
8
12
  outcomeUnknown;
@@ -237,11 +241,14 @@ class PostgresAdapter {
237
241
  context;
238
242
  confidence = "ttl_based";
239
243
  client;
244
+ pgTypes;
240
245
  connected = false;
241
246
  ending;
242
247
  constructor(source, readOnly, context) {
243
248
  this.readOnly = readOnly;
244
249
  this.context = context;
250
+ const { Client, types } = postgres();
251
+ this.pgTypes = types;
245
252
  const timeout = Math.min(2_147_483_647, remainingMilliseconds(context));
246
253
  this.client = new Client({
247
254
  connectionString: normalizePostgresConnectionString(source),
@@ -263,7 +270,7 @@ class PostgresAdapter {
263
270
  rows: toJsonSafe(result.rows),
264
271
  columns: result.fields.map((field) => ({
265
272
  name: field.name,
266
- type: pgTypes.getTypeParser(field.dataTypeID).name ||
273
+ type: this.pgTypes.getTypeParser(field.dataTypeID).name ||
267
274
  `oid_${field.dataTypeID}`,
268
275
  })),
269
276
  };
@@ -884,7 +891,7 @@ class MySqlAdapter {
884
891
  throwIfStopped(this.context, false);
885
892
  if (this.closed)
886
893
  throw new Error("MySQL adapter is closed.");
887
- const rawClient = createMySqlConnection({
894
+ const rawClient = mysql().createConnection({
888
895
  uri: this.source,
889
896
  connectTimeout: remainingMilliseconds(this.context),
890
897
  multipleStatements: false,
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" },
@@ -163,6 +164,8 @@ async function dispatch() {
163
164
  return stateql.disconnect();
164
165
  case "status":
165
166
  return stateql.status();
167
+ case "actor":
168
+ return dispatchActor(subcommand, rest);
166
169
  case "profile":
167
170
  return dispatchProfile(subcommand, rest);
168
171
  case "session":
@@ -175,6 +178,9 @@ async function dispatch() {
175
178
  return stateql.query(sql, {
176
179
  params,
177
180
  cache: cacheMode(values.cache),
181
+ ...(values["preview-rows"] === undefined
182
+ ? {}
183
+ : { previewRows: Number(values["preview-rows"]) }),
178
184
  });
179
185
  case "filter":
180
186
  return stateql.filter(requireValue(subcommand, "result handle"), requireValue(rest.join(" ").trim(), "filter predicate"), { params });
@@ -311,6 +317,16 @@ function parseMongoCommand(value) {
311
317
  throw new Error("Invalid MongoDB EJSON command.");
312
318
  }
313
319
  }
320
+ async function dispatchActor(action, args) {
321
+ switch (action) {
322
+ case "show":
323
+ return stateql.showActor();
324
+ case "set-name":
325
+ return stateql.setActorName(requireValue(args.join(" ").trim(), "actor name"));
326
+ default:
327
+ throw new Error(`Unknown actor command "${action ?? ""}".`);
328
+ }
329
+ }
314
330
  async function dispatchSession(action, args) {
315
331
  switch (action) {
316
332
  case "start":
@@ -641,6 +657,7 @@ Usage: stql <command> [arguments] [options]
641
657
  Commands:
642
658
  connect TARGET | --env ENV | --credential-ref REF | --profile NAME
643
659
  disconnect, status
660
+ actor show | set-name NAME
644
661
  profile add|update NAME [TARGET | --env ENV | --credential-ref REF]
645
662
  profile list|show|remove
646
663
  query, filter, exec, show, rows, count, columns, export
@@ -656,6 +673,7 @@ Commands:
656
673
  pipe
657
674
 
658
675
  SQL parameters: --params JSON, repeated --param VALUE, or --params-file FILE.
676
+ Query preview: --preview-rows N (default: 5, maximum: 200).
659
677
  Deadline: --timeout-ms N (default: 30000). Ctrl+C cancels database work.
660
678
  Credential refs require a trusted host CredentialResolver; the standalone CLI cannot resolve them.
661
679
  State: --max-state-bytes N, --cache-ttl-seconds N, --result-ttl-seconds N.
@@ -131,6 +131,26 @@ const MIGRATIONS = [
131
131
  apply: migratePasswordRefs,
132
132
  validate: validatePasswordRefs,
133
133
  },
134
+ {
135
+ name: "actor_display_names_v1",
136
+ apply(db) {
137
+ addColumn(db, "session_members", "actor_name", "TEXT");
138
+ addColumn(db, "history", "actor_name", "TEXT");
139
+ db.exec(`
140
+ UPDATE session_members SET actor_name = actor_id WHERE actor_name IS NULL;
141
+ UPDATE history SET actor_name = actor_id WHERE actor_name IS NULL;
142
+ `);
143
+ },
144
+ validate(db) {
145
+ requireColumns(db, "session_members", ["actor_name"]);
146
+ requireColumns(db, "history", ["actor_name"]);
147
+ for (const table of ["session_members", "history"]) {
148
+ const row = db.prepare(`SELECT COUNT(*) AS count FROM ${table} WHERE actor_name IS NULL OR actor_name = ''`).get();
149
+ if (row.count)
150
+ throw new Error(`State migration left ${table}.actor_name empty.`);
151
+ }
152
+ },
153
+ },
134
154
  ];
135
155
  export function runMigrations(db, now) {
136
156
  db.exec(`
@@ -178,6 +198,7 @@ function createInitialSchema(db) {
178
198
  CREATE TABLE IF NOT EXISTS session_members (
179
199
  session_id TEXT NOT NULL,
180
200
  actor_id TEXT NOT NULL UNIQUE,
201
+ actor_name TEXT NOT NULL,
181
202
  attached_at TEXT NOT NULL,
182
203
  PRIMARY KEY(session_id, actor_id),
183
204
  FOREIGN KEY(session_id) REFERENCES sessions(id)
@@ -294,6 +315,7 @@ function createInitialSchema(db) {
294
315
  timestamp TEXT NOT NULL,
295
316
  session_id TEXT NOT NULL,
296
317
  actor_id TEXT NOT NULL,
318
+ actor_name TEXT NOT NULL,
297
319
  command TEXT NOT NULL,
298
320
  origin TEXT NOT NULL DEFAULT 'legacy',
299
321
  category TEXT NOT NULL DEFAULT 'management',
@@ -313,19 +335,22 @@ function migrateSharedSessionActors(db) {
313
335
  CREATE TABLE IF NOT EXISTS session_members (
314
336
  session_id TEXT NOT NULL,
315
337
  actor_id TEXT NOT NULL UNIQUE,
338
+ actor_name TEXT,
316
339
  attached_at TEXT NOT NULL,
317
340
  PRIMARY KEY(session_id, actor_id),
318
341
  FOREIGN KEY(session_id) REFERENCES sessions(id)
319
342
  )
320
343
  `);
344
+ addColumn(db, "session_members", "actor_name", "TEXT");
321
345
  addColumn(db, "operations", "actor_id", "TEXT");
322
346
  addColumn(db, "transactions", "owner_actor_id", "TEXT");
323
347
  addColumn(db, "plans", "owner_actor_id", "TEXT");
324
348
  addColumn(db, "plans", "claim_token", "TEXT");
325
349
  addColumn(db, "history", "actor_id", "TEXT");
326
350
  db.exec(`
327
- INSERT OR IGNORE INTO session_members(session_id, actor_id, attached_at)
328
- SELECT id, name, created_at FROM sessions;
351
+ INSERT OR IGNORE INTO session_members(session_id, actor_id, actor_name, attached_at)
352
+ SELECT id, name, name, created_at FROM sessions;
353
+ UPDATE session_members SET actor_name = actor_id WHERE actor_name IS NULL;
329
354
  UPDATE operations SET actor_id = (
330
355
  SELECT name FROM sessions WHERE sessions.id = operations.session_id
331
356
  ) WHERE actor_id IS NULL;
@@ -1,5 +1,9 @@
1
- import { BSON, MongoClient, } from "mongodb";
1
+ import { createRequire } from "node:module";
2
+ import { BSON } from "bson";
2
3
  import { AdapterExecutionError, AdapterWriteError, BatchWriteError, } from "./adapters.js";
4
+ const require = createRequire(import.meta.url);
5
+ let mongodbModule;
6
+ const mongodb = () => (mongodbModule ??= require("mongodb"));
3
7
  const MAX_INSPECTION_ITEMS = 1_000;
4
8
  const FIND_OPTIONS = new Set([
5
9
  "projection",
@@ -170,7 +174,7 @@ export class MongoAdapter {
170
174
  this.databaseName = connection.database_name;
171
175
  this.readOnly = Boolean(connection.read_only);
172
176
  const timeout = remainingMilliseconds(context);
173
- this.client = new MongoClient(input.source, {
177
+ this.client = new (mongodb().MongoClient)(input.source, {
174
178
  connectTimeoutMS: timeout,
175
179
  serverSelectionTimeoutMS: timeout,
176
180
  waitQueueTimeoutMS: timeout,
package/dist/src/redis.js CHANGED
@@ -1,6 +1,9 @@
1
- import { createClient, RESP_TYPES, WatchError } from "@redis/client";
1
+ import { createRequire } from "node:module";
2
2
  import { AdapterExecutionError, AdapterWriteError } from "./adapters.js";
3
3
  import { hash, toJsonSafe } from "./util.js";
4
+ const require = createRequire(import.meta.url);
5
+ let redisModule;
6
+ const redis = () => (redisModule ??= require("@redis/client"));
4
7
  const MAX_ARGUMENTS = 100;
5
8
  const MAX_ARGUMENT_BYTES = 256 * 1024;
6
9
  const MAX_RESPONSE_BYTES = 1024 * 1024;
@@ -105,7 +108,7 @@ export class RedisAdapter {
105
108
  constructor(source, readOnly, context) {
106
109
  this.readOnly = readOnly;
107
110
  this.context = context;
108
- this.client = createClient({
111
+ this.client = redis().createClient({
109
112
  url: source,
110
113
  socket: {
111
114
  connectTimeout: remainingMilliseconds(context),
@@ -183,7 +186,7 @@ export class RedisAdapter {
183
186
  catch (error) {
184
187
  if (error instanceof AdapterWriteError)
185
188
  throw error;
186
- if (error instanceof WatchError)
189
+ if (error instanceof redis().WatchError)
187
190
  throw new AdapterWriteError("ROW_CONFLICT: The Redis key changed. Reload before editing.", false);
188
191
  if (error instanceof AdapterExecutionError)
189
192
  throw error;
@@ -274,7 +277,7 @@ export class RedisAdapter {
274
277
  }
275
278
  const [type, dump] = await Promise.all([
276
279
  this.execute(["TYPE", key], false),
277
- withDeadline(this.client.sendCommand(["DUMP", key], { typeMapping: { [RESP_TYPES.BLOB_STRING]: Buffer } }), this.context, false, () => this.stop()),
280
+ withDeadline(this.client.sendCommand(["DUMP", key], { typeMapping: { [redis().RESP_TYPES.BLOB_STRING]: Buffer } }), this.context, false, () => this.stop()),
278
281
  ]);
279
282
  const encoded = Buffer.isBuffer(dump) ? dump.toString("base64") : dump;
280
283
  if (Buffer.byteLength(JSON.stringify(encoded), "utf8") > MAX_RESPONSE_BYTES * 2) {
package/dist/src/sql.js CHANGED
@@ -1,7 +1,14 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { StateQLError } from "./errors.js";
3
- const { Parser } = createRequire(import.meta.url)("node-sql-parser");
4
- const parser = new Parser();
3
+ const require = createRequire(import.meta.url);
4
+ let parser;
5
+ function sqlParser() {
6
+ if (!parser) {
7
+ const { Parser } = require("node-sql-parser");
8
+ parser = new Parser();
9
+ }
10
+ return parser;
11
+ }
5
12
  const SUPPORTED_STATEMENTS = new Set([
6
13
  "select",
7
14
  "insert",
@@ -44,6 +51,7 @@ export function analyzeSql(sql, driver) {
44
51
  }
45
52
  }
46
53
  function parseSqlStatement(sql, driver) {
54
+ const parser = sqlParser();
47
55
  const database = driver === "postgres"
48
56
  ? "Postgresql"
49
57
  : driver === "mysql"
@@ -1,5 +1,5 @@
1
1
  import { type TableChange } from "./table-editor.js";
2
- import type { ActorLinkData, ActorResolutionData, ActorsData, ActorUnlinkData, AliasData, ApplyData, BatchCommand, CommandExecutionContext, CommandOrigin, BatchOptions, CapabilitiesData, CatalogObject, DescribeObjectData, ListObjectsData, ListObjectsFilter, CloseSessionData, ColumnsData, CommitTransactionData, ConnectOptions, ConnectionData, CountData, DisconnectData, DoctorData, ExecData, ExecOptions, ExecutionOptions, ExportData, FilterOptions, HistoryData, HistoryOptions, OperationData, PlanData, PlanOptions, ProfileData, ProfilesData, ProfileOptions, ProfileUpdateOptions, MongoExecOptions, MongoPlanOptions, MongoQueryOptions, MongoReadCommand, MongoWriteCommand, RedisCommand, RedisExecOptions, RedisPlanOptions, RedisQueryOptions, PurgeData, QueryOptions, RemovedProfileData, Response, ResultData, RollbackTransactionData, RowsData, RowsOptions, Column, StateQLActorOptions, StateQLOptions, StateQLWorkspaceOptions, StateQLSnapshot, StateQLSnapshotOptions, StatusData, SessionData, SessionsData, SessionSummaryData, TransactionData } from "./types.js";
2
+ import type { ActorData, ActorLinkData, ActorResolutionData, ActorsData, ActorUnlinkData, AliasData, ApplyData, BatchCommand, CommandExecutionContext, CommandOrigin, BatchOptions, CapabilitiesData, CatalogObject, DescribeObjectData, ListObjectsData, ListObjectsFilter, CloseSessionData, ColumnsData, CommitTransactionData, ConnectOptions, ConnectionData, CountData, DisconnectData, DoctorData, ExecData, ExecOptions, ExecutionOptions, ExportData, FilterOptions, HistoryData, HistoryOptions, OperationData, PlanData, PlanOptions, ProfileData, ProfilesData, ProfileOptions, ProfileUpdateOptions, MongoExecOptions, MongoPlanOptions, MongoQueryOptions, MongoReadCommand, MongoWriteCommand, RedisCommand, RedisExecOptions, RedisPlanOptions, RedisQueryOptions, PurgeData, QueryOptions, RemovedProfileData, Response, ResultData, RollbackTransactionData, RowsData, RowsOptions, Column, StateQLActorOptions, StateQLOptions, StateQLWorkspaceOptions, StateQLSnapshot, StateQLSnapshotOptions, StatusData, SessionData, SessionsData, SessionSummaryData, TransactionData } from "./types.js";
3
3
  export declare class StateQL {
4
4
  /** Runtime contract marker for passwordRef/password_ref support. */
5
5
  static readonly passwordReferenceVersion: 1;
@@ -39,6 +39,8 @@ export declare class StateQL {
39
39
  status(): Promise<Response<StatusData>>;
40
40
  linkActor(session: string, actorId: string): Promise<Response<ActorLinkData>>;
41
41
  unlinkActor(session: string, actorId: string): Promise<Response<ActorUnlinkData>>;
42
+ showActor(): Promise<Response<ActorData>>;
43
+ setActorName(name: string): Promise<Response<ActorData>>;
42
44
  listActors(session: string): Promise<Response<ActorsData>>;
43
45
  resolveActor(actorId: string): Promise<Response<ActorResolutionData>>;
44
46
  startSession(name: string): Promise<Response<SessionData>>;
@@ -132,6 +134,7 @@ export declare class StateQL {
132
134
  private requireActiveTransaction;
133
135
  private requireSelectedSession;
134
136
  private validateActorId;
137
+ private validateActorName;
135
138
  private throwMembershipDenied;
136
139
  private resolveConnectionSource;
137
140
  private resolveCredential;
@@ -411,6 +411,7 @@ export class StateQL {
411
411
  if (!this.store.isSessionMember(session.id, this.actorId)) {
412
412
  throw new StateQLError("PERMISSION_DENIED", `Actor "${this.actorId}" is not attached to session "${session.name}".`);
413
413
  }
414
+ const actor = this.store.getActor(session.id, this.actorId);
414
415
  const connection = this.store.activeConnection(session);
415
416
  const transaction = session.active_transaction_id
416
417
  ? this.store.getTransaction(session.active_transaction_id)
@@ -433,6 +434,7 @@ export class StateQL {
433
434
  status: session.status,
434
435
  },
435
436
  actor_id: this.actorId,
437
+ actor_name: actor.actor_name,
436
438
  connection: connection
437
439
  ? {
438
440
  connection_id: connection.id,
@@ -479,11 +481,13 @@ export class StateQL {
479
481
  const transaction = session.active_transaction_id
480
482
  ? this.store.getTransaction(session.active_transaction_id)
481
483
  : undefined;
484
+ const actor = this.store.getActor(session.id, this.actorId);
482
485
  return {
483
486
  data: {
484
487
  session_id: session.id,
485
488
  session_name: session.name,
486
489
  actor_id: this.actorId,
490
+ actor_name: actor.actor_name,
487
491
  connection: connection
488
492
  ? {
489
493
  connection_id: connection.id,
@@ -547,6 +551,42 @@ export class StateQL {
547
551
  };
548
552
  });
549
553
  }
554
+ async showActor() {
555
+ return this.run("actor.show", async (current) => {
556
+ const actor = this.store.getActor(current.id, this.actorId);
557
+ return {
558
+ data: {
559
+ actor_id: actor.actor_id,
560
+ actor_name: actor.actor_name,
561
+ attached_at: actor.attached_at,
562
+ },
563
+ };
564
+ });
565
+ }
566
+ async setActorName(name) {
567
+ return this.run("actor.set-name", async (current) => {
568
+ const actorName = this.validateActorName(name);
569
+ const existing = this.store.getActor(current.id, this.actorId);
570
+ if (existing.actor_name === actorName) {
571
+ return {
572
+ data: {
573
+ actor_id: existing.actor_id,
574
+ actor_name: existing.actor_name,
575
+ attached_at: existing.attached_at,
576
+ },
577
+ };
578
+ }
579
+ const actor = this.store.setActorName(current.id, this.actorId, actorName);
580
+ return {
581
+ data: {
582
+ actor_id: actor.actor_id,
583
+ actor_name: actor.actor_name,
584
+ attached_at: actor.attached_at,
585
+ },
586
+ executed: true,
587
+ };
588
+ }, undefined, actorNameHistoryTarget(name));
589
+ }
550
590
  async listActors(session) {
551
591
  return this.run("actor.list", async (current) => {
552
592
  this.requireSelectedSession(current, session);
@@ -555,6 +595,7 @@ export class StateQL {
555
595
  session_id: current.id,
556
596
  actors: this.store.listActors(current.id).map((member) => ({
557
597
  actor_id: member.actor_id,
598
+ actor_name: member.actor_name,
558
599
  attached_at: member.attached_at,
559
600
  })),
560
601
  },
@@ -665,6 +706,9 @@ export class StateQL {
665
706
  }
666
707
  async query(sql, options = {}) {
667
708
  return this.run("query", async (session) => {
709
+ const previewRows = options.previewRows === undefined
710
+ ? this.previewRows
711
+ : queryPreviewRows(options.previewRows);
668
712
  const connection = this.requireConnection(session);
669
713
  this.rejectMongoSql(connection, "mongoQuery");
670
714
  this.rejectDuringStagedTransaction(session, "Queries");
@@ -705,7 +749,7 @@ export class StateQL {
705
749
  cached.row_count <= this.maxResultRows &&
706
750
  this.cacheValid(cached, stateVersion, stateSignature)) {
707
751
  return {
708
- data: this.resultData(cached, true),
752
+ data: this.resultData(cached, true, previewRows),
709
753
  handle: cached.id,
710
754
  cached: true,
711
755
  warnings: paginationWarnings(analysis.ordered),
@@ -752,7 +796,7 @@ export class StateQL {
752
796
  expiresAt,
753
797
  });
754
798
  return {
755
- data: this.resultData(saved, false),
799
+ data: this.resultData(saved, false, previewRows),
756
800
  handle: saved.id,
757
801
  executed: true,
758
802
  warnings: paginationWarnings(analysis.ordered),
@@ -1940,6 +1984,7 @@ export class StateQL {
1940
1984
  generated_aliases: true,
1941
1985
  multi_row_table_plans: true,
1942
1986
  history_classification: true,
1987
+ actor_display_names: true,
1943
1988
  },
1944
1989
  driver_features: {
1945
1990
  mongodb: {
@@ -1992,6 +2037,10 @@ export class StateQL {
1992
2037
  return this.disconnect();
1993
2038
  case "status":
1994
2039
  return this.status();
2040
+ case "actor.show":
2041
+ return this.showActor();
2042
+ case "actor.set-name":
2043
+ return this.setActorName(batchString(command.name, "name"));
1995
2044
  case "profile.add":
1996
2045
  return this.addProfile(batchString(command.name, "name"), command.target, {
1997
2046
  readOnly: command.read_only ?? true,
@@ -2027,6 +2076,7 @@ export class StateQL {
2027
2076
  const response = await this.query(batchString(command.sql, "sql"), {
2028
2077
  params: command.params ?? [],
2029
2078
  cache: command.cache ?? "auto",
2079
+ previewRows: command.preview_rows,
2030
2080
  timeoutMs: command.timeout_ms,
2031
2081
  });
2032
2082
  if (!response.ok || !command.as)
@@ -2813,6 +2863,21 @@ export class StateQL {
2813
2863
  throw new StateQLError("INVALID_COMMAND", "Actor ID is required.");
2814
2864
  }
2815
2865
  }
2866
+ validateActorName(value) {
2867
+ if (typeof value !== "string") {
2868
+ throw new StateQLError("INVALID_COMMAND", "Actor name must be a string.");
2869
+ }
2870
+ const name = value.trim();
2871
+ if (!name)
2872
+ throw new StateQLError("INVALID_COMMAND", "Actor name is required.");
2873
+ if ([...name].length > 80) {
2874
+ throw new StateQLError("INVALID_COMMAND", "Actor name cannot exceed 80 characters.");
2875
+ }
2876
+ if (/[\u0000-\u001f\u007f]/u.test(name)) {
2877
+ throw new StateQLError("INVALID_COMMAND", "Actor name cannot contain control characters.");
2878
+ }
2879
+ return name;
2880
+ }
2816
2881
  throwMembershipDenied(session) {
2817
2882
  throw new StateQLError("PERMISSION_DENIED", `Actor "${this.actorId}" is not attached to session "${session.name}".`);
2818
2883
  }
@@ -2931,9 +2996,9 @@ export class StateQL {
2931
2996
  executionContext(options) {
2932
2997
  return createAdapterContext(executionTimeout(options.timeoutMs ?? this.timeoutMs), combineAbortSignals(options.signal, this.commandContexts.getStore()?.signal, this.signal));
2933
2998
  }
2934
- resultData(result, cached) {
2999
+ resultData(result, cached, previewRows = this.previewRows) {
2935
3000
  const rows = this.store.resultRows(result);
2936
- const preview = compactRows(rows.slice(0, this.previewRows), this.maxCellCharacters);
3001
+ const preview = compactRows(rows.slice(0, previewRows), this.maxCellCharacters);
2937
3002
  return {
2938
3003
  result_id: result.id,
2939
3004
  alias: result.alias ?? this.store.generatedAlias(result.id),
@@ -2980,6 +3045,7 @@ export class StateQL {
2980
3045
  },
2981
3046
  };
2982
3047
  }
3048
+ const actorName = this.store.getActor(session.id, this.actorId).actor_name;
2983
3049
  try {
2984
3050
  const result = await action(session);
2985
3051
  const responseSession = result.session ?? session;
@@ -2987,6 +3053,7 @@ export class StateQL {
2987
3053
  const history = this.store.addHistory({
2988
3054
  sessionId: session.id,
2989
3055
  actorId: this.actorId,
3056
+ actorName,
2990
3057
  origin,
2991
3058
  category,
2992
3059
  internal,
@@ -3021,6 +3088,7 @@ export class StateQL {
3021
3088
  const history = this.store.addHistory({
3022
3089
  sessionId: session.id,
3023
3090
  actorId: this.actorId,
3091
+ actorName,
3024
3092
  origin,
3025
3093
  category,
3026
3094
  internal,
@@ -3053,6 +3121,7 @@ function historyEntry(item) {
3053
3121
  timestamp: item.timestamp,
3054
3122
  session_id: item.session_id,
3055
3123
  actor_id: item.actor_id,
3124
+ actor_name: item.actor_name,
3056
3125
  origin: item.origin,
3057
3126
  category: item.category,
3058
3127
  internal: Boolean(item.internal),
@@ -3066,6 +3135,12 @@ function historyEntry(item) {
3066
3135
  error_code: item.error_code,
3067
3136
  };
3068
3137
  }
3138
+ function actorNameHistoryTarget(value) {
3139
+ if (typeof value !== "string" || /[\u0000-\u001f\u007f]/u.test(value))
3140
+ return undefined;
3141
+ const name = value.trim();
3142
+ return name ? [...name].slice(0, 80).join("") : undefined;
3143
+ }
3069
3144
  const COMMAND_ORIGINS = new Set([
3070
3145
  "legacy",
3071
3146
  "user",
@@ -3286,6 +3361,12 @@ function nonNegativeInteger(value, name) {
3286
3361
  return value;
3287
3362
  throw new StateQLError("INVALID_COMMAND", `${name} must be a non-negative integer.`);
3288
3363
  }
3364
+ function queryPreviewRows(value) {
3365
+ const previewRows = nonNegativeInteger(value, "previewRows");
3366
+ if (previewRows <= 200)
3367
+ return previewRows;
3368
+ throw new StateQLError("OUTPUT_LIMIT_EXCEEDED", "previewRows cannot exceed 200 rows.");
3369
+ }
3289
3370
  function positiveInteger(value, name) {
3290
3371
  if (Number.isInteger(value) && value > 0)
3291
3372
  return value;
@@ -104,6 +104,7 @@ export interface HistoryRecord {
104
104
  timestamp: string;
105
105
  session_id: string;
106
106
  actor_id: string;
107
+ actor_name: string;
107
108
  origin: CommandOrigin;
108
109
  category: HistoryCategory;
109
110
  internal: number;
@@ -119,6 +120,7 @@ export interface HistoryRecord {
119
120
  export interface SessionMemberRecord {
120
121
  session_id: string;
121
122
  actor_id: string;
123
+ actor_name: string;
122
124
  attached_at: string;
123
125
  }
124
126
  export declare class StateStore {
@@ -137,6 +139,8 @@ export declare class StateStore {
137
139
  isSessionMember(sessionId: string, actorId: string): boolean;
138
140
  linkActor(sessionId: string, requestingActorId: string, actorId: string): "linked" | "already_linked" | "actor_conflict" | "denied";
139
141
  unlinkActor(sessionId: string, requestingActorId: string, actorId: string): "unlinked" | "not_linked" | "owns_transaction" | "denied";
142
+ getActor(sessionId: string, actorId: string): SessionMemberRecord | undefined;
143
+ setActorName(sessionId: string, actorId: string, actorName: string): SessionMemberRecord | undefined;
140
144
  listActors(sessionId: string): SessionMemberRecord[];
141
145
  resolveActor(actorId: string): SessionRecord | undefined;
142
146
  getSession(idOrName: string): SessionRecord | undefined;
@@ -299,6 +303,7 @@ export declare class StateStore {
299
303
  addHistory(input: {
300
304
  sessionId: string;
301
305
  actorId: string;
306
+ actorName?: string;
302
307
  origin?: CommandOrigin;
303
308
  category?: HistoryCategory;
304
309
  internal?: boolean;
package/dist/src/store.js CHANGED
@@ -113,16 +113,16 @@ export class StateStore {
113
113
  }
114
114
  if (created) {
115
115
  this.db
116
- .prepare(`INSERT INTO session_members(session_id, actor_id, attached_at)
117
- VALUES (?, ?, ?)`)
118
- .run(row.id, actorId, timestamp);
116
+ .prepare(`INSERT INTO session_members(session_id, actor_id, actor_name, attached_at)
117
+ VALUES (?, ?, ?, ?)`)
118
+ .run(row.id, actorId, actorId, timestamp);
119
119
  }
120
120
  else if (ensureLegacyMembership) {
121
121
  this.db
122
122
  .prepare(`INSERT OR IGNORE INTO session_members
123
- (session_id, actor_id, attached_at)
124
- VALUES (?, ?, ?)`)
125
- .run(row.id, actorId, timestamp);
123
+ (session_id, actor_id, actor_name, attached_at)
124
+ VALUES (?, ?, ?, ?)`)
125
+ .run(row.id, actorId, actorId, timestamp);
126
126
  }
127
127
  this.db.exec("COMMIT");
128
128
  return this.getSession(row.id);
@@ -167,9 +167,9 @@ export class StateStore {
167
167
  if (this.isSessionMember(row.id, identity))
168
168
  continue;
169
169
  this.db
170
- .prepare(`INSERT INTO session_members(session_id, actor_id, attached_at)
171
- VALUES (?, ?, ?)`)
172
- .run(row.id, identity, timestamp);
170
+ .prepare(`INSERT INTO session_members(session_id, actor_id, actor_name, attached_at)
171
+ VALUES (?, ?, ?, ?)`)
172
+ .run(row.id, identity, identity, timestamp);
173
173
  }
174
174
  const session = this.getSessionByName(name);
175
175
  if (!session)
@@ -204,9 +204,9 @@ export class StateStore {
204
204
  return existing.id === sessionId ? "already_linked" : "actor_conflict";
205
205
  }
206
206
  this.db
207
- .prepare(`INSERT INTO session_members(session_id, actor_id, attached_at)
208
- VALUES (?, ?, ?)`)
209
- .run(sessionId, actorId, this.now().toISOString());
207
+ .prepare(`INSERT INTO session_members(session_id, actor_id, actor_name, attached_at)
208
+ VALUES (?, ?, ?, ?)`)
209
+ .run(sessionId, actorId, actorId, this.now().toISOString());
210
210
  this.db.exec("COMMIT");
211
211
  return "linked";
212
212
  }
@@ -243,6 +243,19 @@ export class StateStore {
243
243
  throw error;
244
244
  }
245
245
  }
246
+ getActor(sessionId, actorId) {
247
+ return this.db
248
+ .prepare(`SELECT * FROM session_members
249
+ WHERE session_id = ? AND actor_id = ?`)
250
+ .get(sessionId, actorId);
251
+ }
252
+ setActorName(sessionId, actorId, actorName) {
253
+ return this.db
254
+ .prepare(`UPDATE session_members SET actor_name = ?
255
+ WHERE session_id = ? AND actor_id = ?
256
+ RETURNING *`)
257
+ .get(actorName, sessionId, actorId);
258
+ }
246
259
  listActors(sessionId) {
247
260
  return this.db
248
261
  .prepare(`SELECT * FROM session_members
@@ -943,10 +956,10 @@ export class StateStore {
943
956
  const insert = (id) => {
944
957
  this.db
945
958
  .prepare(`INSERT INTO history
946
- (id, timestamp, session_id, actor_id, origin, category, internal, command, sql, target, handle,
959
+ (id, timestamp, session_id, actor_id, actor_name, origin, category, internal, command, sql, target, handle,
947
960
  executed, cached, success, error_code)
948
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
949
- .run(id, this.now().toISOString(), input.sessionId, input.actorId, input.origin ?? "legacy", input.category ?? "management", input.internal ? 1 : 0, input.command, boundedHistorySql(input.sql), input.target?.slice(0, 1024) ?? null, input.handle ?? null, input.executed ? 1 : 0, input.cached ? 1 : 0, input.success ? 1 : 0, input.errorCode ?? null);
961
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
962
+ .run(id, this.now().toISOString(), input.sessionId, input.actorId, input.actorName ?? this.getActor(input.sessionId, input.actorId)?.actor_name ?? input.actorId, input.origin ?? "legacy", input.category ?? "management", input.internal ? 1 : 0, input.command, boundedHistorySql(input.sql), input.target?.slice(0, 1024) ?? null, input.handle ?? null, input.executed ? 1 : 0, input.cached ? 1 : 0, input.success ? 1 : 0, input.errorCode ?? null);
950
963
  };
951
964
  const id = input.id ?? this.insertWithRandomId("cmd", "history", insert);
952
965
  if (input.id !== undefined)
@@ -1,4 +1,4 @@
1
- import { BSON } from "mongodb";
1
+ import { BSON } from "bson";
2
2
  import { StateQLError } from "./errors.js";
3
3
  export function quoteIdentifier(name, driver) {
4
4
  if (!name || name.length > 500 || name.includes("\0"))
@@ -83,6 +83,7 @@ export interface HistoryEntry {
83
83
  timestamp: string;
84
84
  session_id: string;
85
85
  actor_id: string;
86
+ actor_name: string;
86
87
  origin: CommandOrigin;
87
88
  category: HistoryCategory;
88
89
  internal: boolean;
@@ -107,6 +108,7 @@ export interface StateQLSnapshot {
107
108
  status: string;
108
109
  };
109
110
  actor_id: string;
111
+ actor_name: string;
110
112
  connection: {
111
113
  connection_id: string;
112
114
  /** Generated display identity; optional for older snapshot producers. */
@@ -281,6 +283,7 @@ export type StateQLWorkspaceOptions = StateQLActorOptions & {
281
283
  export interface QueryOptions extends ExecutionOptions {
282
284
  params?: SqlParameters;
283
285
  cache?: "auto" | "bypass" | "require";
286
+ previewRows?: number;
284
287
  }
285
288
  export interface MongoQueryOptions extends ExecutionOptions {
286
289
  cache?: "auto" | "bypass" | "require";
@@ -344,7 +347,7 @@ export interface MongoPlanOptions extends ExecutionOptions {
344
347
  allowUnbounded?: boolean;
345
348
  allowDestructive?: boolean;
346
349
  }
347
- export type BatchCommandName = "connect" | "disconnect" | "status" | "profile.add" | "profile.list" | "profile.show" | "profile.remove" | "profile.update" | "session.start" | "session.list" | "session.show" | "session.summary" | "session.close" | "query" | "filter" | "exec" | "show" | "rows" | "count" | "columns" | "alias.set" | "inspect" | "transaction.begin" | "transaction.status" | "transaction.commit" | "transaction.rollback" | "plan" | "mongo.query" | "mongo.exec" | "mongo.plan" | "redis.query" | "redis.exec" | "redis.plan" | "objects.list" | "object.describe" | "apply" | "history" | "receipt" | "doctor" | "purge" | "capabilities";
350
+ export type BatchCommandName = "connect" | "disconnect" | "status" | "actor.show" | "actor.set-name" | "profile.add" | "profile.list" | "profile.show" | "profile.remove" | "profile.update" | "session.start" | "session.list" | "session.show" | "session.summary" | "session.close" | "query" | "filter" | "exec" | "show" | "rows" | "count" | "columns" | "alias.set" | "inspect" | "transaction.begin" | "transaction.status" | "transaction.commit" | "transaction.rollback" | "plan" | "mongo.query" | "mongo.exec" | "mongo.plan" | "redis.query" | "redis.exec" | "redis.plan" | "objects.list" | "object.describe" | "apply" | "history" | "receipt" | "doctor" | "purge" | "capabilities";
348
351
  export interface BatchCommand {
349
352
  command: BatchCommandName;
350
353
  target?: string;
@@ -360,6 +363,7 @@ export interface BatchCommand {
360
363
  redis?: RedisCommand;
361
364
  object?: CatalogObject;
362
365
  cache?: "auto" | "bypass" | "require";
366
+ preview_rows?: number;
363
367
  read_only?: boolean;
364
368
  secret_env?: string;
365
369
  credential_ref?: string;
@@ -431,6 +435,7 @@ export interface StatusData {
431
435
  session_id: string;
432
436
  session_name: string;
433
437
  actor_id: string;
438
+ actor_name: string;
434
439
  connection: StatusConnectionData | null;
435
440
  transaction: TransactionReferenceData | null;
436
441
  state_version: string | null;
@@ -447,6 +452,7 @@ export interface ActorUnlinkData {
447
452
  }
448
453
  export interface ActorData {
449
454
  actor_id: string;
455
+ actor_name: string;
450
456
  attached_at: string;
451
457
  }
452
458
  export interface ActorsData {
package/docs/databases.md CHANGED
@@ -40,9 +40,7 @@ transaction-control SQL is unsupported: use
40
40
  [staged transactions](usage.md#transactions), not `BEGIN` or `COMMIT` statements.
41
41
  MongoDB and Redis use separate native command APIs.
42
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.
43
+ Unrecognized or parser-unsupported forms remain blocked.
46
44
 
47
45
  ## Dialect upserts
48
46
 
package/docs/library.md CHANGED
@@ -29,7 +29,7 @@ try {
29
29
 
30
30
  const result = await stateql.query(
31
31
  "SELECT id, email FROM users WHERE status = ? ORDER BY id LIMIT 50",
32
- { params: ["active"], timeoutMs: 5_000 },
32
+ { params: ["active"], timeoutMs: 5_000, previewRows: 20 },
33
33
  );
34
34
  if (!result.ok) throw new Error(result.error.message);
35
35
 
@@ -62,6 +62,10 @@ output mode. Check `response.ok` before reading `response.data`; failures expose
62
62
  `response.error`. Queries return typed `ResultData` with `result_id`, `preview`,
63
63
  and result metadata. Reuse `result_id` with methods such as `filter`, `rows`,
64
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.
65
69
 
66
70
  The following snippets assume an open client and an appropriate connection.
67
71
 
@@ -126,6 +130,14 @@ available through `linkActor(session, actorId)`, `unlinkActor(session, actorId)`
126
130
  user confirmation before changing membership or the shared connection; a host
127
131
  calling `forWorkspace` is responsible for authorizing that workspace access.
128
132
 
133
+ An actor can inspect itself with `showActor()` and set its own contextual display
134
+ name with `setActorName(name)`. The display name is trimmed, limited to 80
135
+ characters, and rejects control characters. It never replaces `actor_id` in
136
+ membership, authorization, plan ownership, or transaction ownership. History
137
+ snapshots the display name at command start, so later renames do not alter prior
138
+ audit entries; the corresponding batch commands are `actor.show` and
139
+ `actor.set-name` (using the `name` field).
140
+
129
141
  ## Credential resolution
130
142
 
131
143
  Library integrations can resolve environment-variable names, opaque full-URL
package/docs/usage.md CHANGED
@@ -93,18 +93,21 @@ for source-replacement and downgrade restrictions.
93
93
 
94
94
  ## CLI reference
95
95
 
96
- ```text
96
+ ```bash
97
97
  stql connect <target> [--name NAME] [--read-only|--read-write]
98
98
  stql connect --env ENV [--name NAME] [--read-only|--read-write]
99
99
  stql connect --credential-ref REF [--name NAME] [--read-only|--read-write]
100
100
  stql connect --profile NAME
101
101
  stql disconnect
102
102
  stql status
103
+ stql actor show
104
+ stql actor set-name <display-name>
103
105
  stql profile add|update NAME [TARGET | --env ENV | --credential-ref REF]
104
106
  [--read-only|--read-write]
105
107
  stql profile list|show|remove
106
108
  stql session start|list|show|summary|close
107
109
  stql query <sql> [--params JSON | --param VALUE...] [--cache auto|bypass|require]
110
+ [--preview-rows 0..200]
108
111
  stql filter <result-handle> <predicate> [--params JSON | --param VALUE...]
109
112
  stql exec <sql> [--params JSON | --param VALUE...] [--idempotency-key KEY] [--replay]
110
113
  [--allow-unbounded] [--allow-destructive]
@@ -138,7 +141,7 @@ stql pipe [--continue-on-error]
138
141
  For shell-safe positional parameters, repeat `--param`. JSON scalars become
139
142
  their native types; other values remain strings.
140
143
 
141
- ```powershell
144
+ ```bash
142
145
  stql exec "INSERT INTO users (name, status) VALUES (?, ?)" `
143
146
  --param Ada --param trial
144
147
  ```
@@ -226,6 +229,17 @@ transactions remain owned by the actor that created them.
226
229
  Callers that omit `actor` keep the legacy behavior where the actor ID is the
227
230
  session name.
228
231
 
232
+ Actor IDs are immutable authorization and ownership identities. Each actor also
233
+ has a mutable display name, initially equal to its ID. The selected actor may
234
+ change only its own display name with `stql actor set-name <display-name>`;
235
+ names are trimmed, limited to 80 characters, and cannot contain control
236
+ characters. Display names are contextual metadata and must not be used for
237
+ authorization.
238
+
239
+ History records both the stable `actor_id` and the `actor_name` in effect when
240
+ the command began. Renaming therefore does not rewrite earlier attribution; the
241
+ rename is itself recorded as an `actor.set-name` management command.
242
+
229
243
  ### Result lifetime and limits
230
244
 
231
245
  Result rows are materialized locally for durable access. By default, read cache
@@ -238,6 +252,10 @@ columns. These caps bound persisted materialization; the independent deadline
238
252
  bounds execution time. Native commands may impose stricter
239
253
  [database-specific limits](databases.md).
240
254
 
255
+ Query responses preview five rows by default. Use `--preview-rows N` to return
256
+ between 0 and 200 preview rows without rerunning or changing the stored result.
257
+ Additional rows remain available through `stql rows <result-handle>`.
258
+
241
259
  Command history keeps the latest 10,000 entries per session. SQLite cache reuse
242
260
  also checks the database file signature. PostgreSQL, MySQL, and MongoDB cache
243
261
  reuse is labeled `ttl_based` and is never authoritative.
@@ -345,8 +363,10 @@ stql batch commands.json
345
363
  ```
346
364
 
347
365
  Batch fields use snake case. Supported command names match CLI paths, such as
348
- `filter`, `transaction.begin`, `session.summary`, `alias.set`, `plan`, and
349
- `apply`. Native MongoDB batches use `mongo.query`, `mongo.exec`, or `mongo.plan`
350
- with the command object in `mongo`; the same cache, replay, idempotency, safety,
351
- and timeout fields apply. Database commands may set `timeout_ms`; otherwise they
352
- use the 30-second default.
366
+ `actor.show`, `actor.set-name`, `filter`, `transaction.begin`, `session.summary`,
367
+ `alias.set`, `plan`, and `apply`. `actor.set-name` takes the display name in the
368
+ `name` field. Query commands may set `preview_rows` from 0 to 200. Native MongoDB
369
+ batches use `mongo.query`, `mongo.exec`, or `mongo.plan` with the command object
370
+ in `mongo`; the same cache, replay, idempotency, safety, and timeout fields
371
+ apply. Database commands may set `timeout_ms`; otherwise they use the 30-second
372
+ default.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fadhilp/stateql",
3
- "version": "0.13.1",
3
+ "version": "0.13.3",
4
4
  "description": "Stateful, agent-oriented database CLI for safe result reuse",
5
5
  "repository": {
6
6
  "type": "git",
@@ -22,12 +22,11 @@
22
22
  "dist/src",
23
23
  "README.md",
24
24
  "docs",
25
- "SQL_COMMAND_ROADMAP.md",
26
25
  "LICENSE"
27
26
  ],
28
27
  "scripts": {
29
28
  "build": "tsc -p tsconfig.json",
30
- "test": "npm run build && node --test dist/test/cli.test.js dist/test/credential.test.js dist/test/mongodb.test.js dist/test/mysql.test.js dist/test/postgres.test.js dist/test/query.test.js dist/test/redis.test.js dist/test/sqlite.test.js dist/test/store.test.js dist/test/terminal.test.js dist/test/transaction.test.js dist/test/write.test.js dist/test/panel.test.js",
29
+ "test": "npm run build && node --test dist/test/cli.test.js dist/test/credential.test.js dist/test/import.test.js dist/test/mongodb.test.js dist/test/mysql.test.js dist/test/postgres.test.js dist/test/query.test.js dist/test/redis.test.js dist/test/sqlite.test.js dist/test/store.test.js dist/test/terminal.test.js dist/test/transaction.test.js dist/test/write.test.js dist/test/panel.test.js",
31
30
  "release": "npm version",
32
31
  "version": "npm install",
33
32
  "prepack": "npm test"
@@ -48,6 +47,7 @@
48
47
  },
49
48
  "dependencies": {
50
49
  "@redis/client": "^5.12.1",
50
+ "bson": "^6.10.4",
51
51
  "mongodb": "^6.21.0",
52
52
  "mysql2": "^3.23.1",
53
53
  "node-sql-parser": "^5.4.0",