@ai-digital-factory/lmt-db-cli
v0.1.1
Published
Agent-friendly read-only SQLite investigation for Live Market Terminal, with scoped maintenance helpers.
Maintainers
Readme
LMT DB CLI — agent guide
Inspect current Live Market Terminal SQLite data with logical environment, owner and Store names. Install from npm; no repository checkout is required.
npm install --global @ai-digital-factory/lmt-db-cli
lmt-db --helpRequires Node 24.11.0 or newer and system OpenSSH. Automatic Dev discovery also requires Python 3 and Docker access on the remote host. No browser or Zerodha login is needed. The CLI never starts or restarts services.
Human setup once, agent reads afterward
A human runs the masked prompt in a terminal:
lmt-db credential provision --environment devEnter an SMS token with read access to infra/ssh: HETZNER_IP, USER_NAME,
PRIVATE_KEY. This installation uses the existing infrastructure SSH credential;
separate DB roles are deferred for this automatic Dev path. The bootstrap is
stored separately from LMT CLI in owner-only ~/.lmt-db/secrets.pem (plaintext
protected by filesystem permissions). Do not put tokens in command arguments,
chat, source control or agent prompts. Automation may use --credential-stdin
with protected stdin. Pin the Dev SSH host key in ~/.ssh/known_hosts after
checking its fingerprint through the server console or another trusted channel.
Host-key verification is never disabled. Connection checks do not add keys.
LMT operator login vs DB CLI bootstrap
~/.lmt (LMT operator / lmt CLI) and ~/.lmt-db (DB CLI) are not interchangeable.
Operator login tokens saved for Market Watch and Zerodha flows do not authorize Dev
Store reads. DB CLI needs a separate SMS bootstrap with read access to scope
infra/ssh so it can retrieve HETZNER_IP, USER_NAME, and PRIVATE_KEY.
Provisioning writes only ~/.lmt-db/secrets.pem and does not read or change
~/.lmt. On SMS or missing-bootstrap failures, the CLI stderr message repeats
this guide and points to lmt-db credential provision --environment dev.
Commands for agents
lmt-db connection check --environment dev
lmt-db tables --environment dev
lmt-db schema --environment dev --owner broker-1 --store candles
lmt-db query --environment dev --owner broker-1 --store candles --sql 'SELECT COUNT(*) AS candle_count FROM candles'Discover before querying: run tables once for every Dev Store and its table/view
names, then call schema only when column detail is needed. Prefer tables
over stores followed by many per-Store schema calls: one SSH session returns
logical owners, availability, build, and {name,type} for each table and view
on available Stores. Unavailable Stores omit tables. Use stores only when you
need the store list without opening SQLite. Dev routes to Hetzner, Broker 1. No container
names, IP addresses, database paths or client config files are required. The
running deployment determines current paths and build provenance. Supported
current Dev Stores are Gate operator-sessions, and Broker 1
authenticated-sessions, candles, minute-prices, volume-checkpoints, capture-reconciliation.
Stores not present in the selected deployed build are reported unavailable. New
deployments use Minute Price Series; Candle History remains a legacy reader.
Current recording files are not included in automatic discovery yet.
Example tables fragment (available Store):
{
"owner": "broker-1",
"store": "candles",
"status": "available",
"schemaVersion": 5,
"tables": [{"name": "candles", "type": "table"}, {"name": "capture_windows", "type": "table"}]
}Queries are read-only and support joins/aggregates within one Store. Output is
JSON by default; use --format table or --format csv. Ordered columns and
array rows retain duplicate column labels. SQLite integers use
{"type":"integer","value":"62564"}, blobs use base64 tags and infinities use
real tags; SQL NULL stays null. Do not interpret empty rows, unavailable
Stores, truncation or errors as evidence of historical absence.
Defaults: 2-second SQLite deadline, 1,000 rows, 1 MiB serialized output. Adjust
--deadline-ms, --rows, --bytes up to 10 seconds, 10,000 rows, 8 MiB.
Check status, truncated, truncation and provenance before using results.
Exit 0 means complete or explicitly truncated output, 1 means failure, 2 means
timeout. SMS, SSH and discovery have separate bounded transport deadlines. On an
error stop and report it; do not fall back to another environment, disable host
verification, retrieve backups or restart an owner. All stored columns are
visible and may contain sensitive values.
Production and maintenance availability
Automatic routing is currently Dev-only. Prod reads require an administrator's
explicit --config and provisioned restricted helper as described below; an
infra/ssh token alone does not configure Prod. No Prod mutations are supported.
The advanced configured-helper path supports deliberate local/Dev maintenance,
with atomic batches and owner coordination. Agents using this investigation
workflow should use tables, schema, query, and connection check.
Source development and releases
From live-market-terminal, pnpm db builds and runs the same executable.
The manual Release LMT DB CLI workflow
runs on main, tests the exact tarball before loading npm credentials, publishes
publicly, checks registry integrity and verifies a fresh registry installation.
Release versions come from npm history. Never publish from a source checkout by
hand or reuse an already-published version.
Standalone local and restricted remote SQLite investigation. Requires Node >=24.11.0 (tested 24.11.0), pnpm 10.33.3 for development. SQLite remains experimental in Node. No Operator/Zerodha login or backups. Stopped-owner local/dev Maintenance is documented below. Remote Investigation uses SMS-scoped credentials and restricted SSH as documented below.
Build: pnpm --filter @ai-digital-factory/lmt-db-cli build. Run typecheck, test, and package:build separately. npm pack apps/db-cli/dist/npm produces a dependency-free package; install that tarball outside the checkout. Tests pack and install into a temporary directory and remove fixtures on exit.
Local use
A trusted administrator provisions a protected JSON config (mode 0600, outside source control):
{"targets":[{"environment":"local","owner":"broker-1","store":"candles","path":"/absolute/current/candles.sqlite","build":"owner-build-if-known"}],"credentials":[{"token":"provisioned-investigation-secret","role":"Investigation","targets":[{"environment":"local","owner":"broker-1","store":"candles"}]}]}Pass the role credential through LMT_DB_CREDENTIAL, never a command-line argument. This local config verifier is a provisioning adapter; it does not grant SMS permissions or retrieve Maintenance credentials. Local OS file permissions remain the administrator's trust boundary: someone who can edit the registry or read the SQLite file already has host access. Do not accept client configuration as a remote helper's trusted registry. Investigation and Maintenance credentials can inspect authorized local Stores; Maintenance may also mutate as documented below. The advanced configured-helper path requires explicit remote routing and trusted host provisioning below.
lmt-db stores --config /protected/store.json
lmt-db schema --config /protected/store.json --environment local --owner broker-1 --store candles
lmt-db query --config /protected/store.json --environment local --owner broker-1 --store candles --sql 'SELECT * FROM candles LIMIT 10' --format jsonCommands: stores, schema, query, mutate. Formats: json (default), csv, table. Stores are configured identities, never client paths. Schema returns ordered SQLite table/view definitions and table_xinfo columns, including hidden/generated columns. Query permits all authorized stored columns, joins and aggregates. Zero rows returns rows: []. Inaccessible/invalid SQL is an error, not zero rows. Errors are deliberately generic and do not echo credentials, SQL or host paths. A result may intentionally contain sensitive stored values.
Public contract for SUK-117
Package export: createExecutor({targets, verify}) returns execute(request, credential): Promise<result>. verify is an async trusted adapter returning {role: 'Investigation'|'Maintenance', targets: [{environment,owner,store}]} or null. Its failures become UNAUTHORIZED. Registry entries contain that identity plus absolute path and optional owner build. No verifier functions, role claims or file paths come from requests. Revocation is checked on each operation. Configure registry and verifier on the executing host; later SSH must carry only the bounded request and credential, without arbitrary commands or paths.
Request: {operation: 'stores'|'schema'|'query'|'mutate', target: {environment,owner,store}, sql?: string, batch?: object, limits?: {deadlineMs,rows,bytes}}. stores lists only configured authorized targets for the trusted host environment without paths. Other operations enforce exact target scope and trusted host environment. Unknown operations fail. Structured mutate uses the batch contract below. No production writes exist. Reuse this boundary for later transports; remote transport is documented below.
SQL is at most 65536 UTF-8 bytes and exactly one statement (optional trailing semicolon). SQLite opens the live file read-only with extensions disabled and trusted_schema off. The authorizer allows SELECT/READ/recursive/builtin functions, denies all other actions, and restricts reads to main. Table-valued pragmas, ATTACH, writes, DDL, connection pragmas and extension/file functions fail. Schema discovery alone permits its fixed table_xinfo pragma. Each operation uses one read transaction, including schema version, against the original file and committed WAL. No live-file copying or immutable mode. Registry paths must be administrator-owned current files, with directory/symlink replacement excluded by host permissions.
JSON results contain {status,columns,rows,truncated,truncation,limits,provenance}. Columns are positional labels (duplicates retained); rows are arrays. Every SQLite integer is {type:'integer',value:'decimal'} including zero, blobs are {type:'blob',base64:'...'}, null remains null, REAL remains a number, TEXT remains string. CSV is RFC-style two-column kind,payload: metadata, columns, then row records, each payload a quoted JSON value using the same types. Table is a human-readable header plus JSON cells. No masking, precision coercion or duplicate-label object conversion.
Provenance: {environment,owner,store,schemaVersion,readTime,query,build}; build is the configured owner build or null (unavailable), schemaVersion is PRAGMA user_version, readTime is UTC transaction inspection time, query is the supplied query (null for discovery). store is the actual registry identity, not a historical snapshot identifier. CLI build identity is included separately when available. Null explicitly means unavailable; a missing historical row does not establish why evidence is absent.
Defaults: deadline 2000 ms, 1000 rows, 1048576 bytes. Maxima: 10000 ms, 10000 rows, 8388608 bytes. Positive integer overrides: --deadline-ms, --rows, --bytes. Deadline includes process startup and database access after credential verification; remote verifier implementations must bound their external I/O separately. Executor uses an isolated child with SIGKILL at deadline: {status:'timeout',truncated:false,limits,provenance} has no rows and unknown readTime/schemaVersion. CLI exits 2 for timeout, 1 for failure, 0 for complete or explicitly truncated results. Limits bound serialized JSON result bytes, including metadata; row/byte exhaustion gives truncated:true and truncation:'rows'|'bytes'. Metadata too large fails explicitly. CLI separately bounds the selected rendered format and refuses output that exceeds the byte budget. SQL can allocate native SQLite memory before producing its first row; the kill deadline bounds execution time, not peak native memory. Host sandbox/cgroup memory policy belongs to helper provisioning.
SUK-117 remote Investigation
Remote reads reuse the executor/result/SQL/limit contract above. The trusted
executor now accepts an administrator-supplied environment (defaults to
local for existing callers); its registry and grants must match it exactly.
SUK-118 adds stopped-owner structured writes below, retaining executor authorization,
Prod refusal and ownership exclusion independently of client flags.
Client configuration contains routing, never host paths or scope grants:
{"remotes":{"dev":{"host":"dev-store.example","port":22,"user":"lmt-db","identityFile":"/protected/store-key","knownHosts":"/protected/store-known-hosts"},"prod":{"host":"prod-store.example","user":"lmt-db","identityFile":"/protected/store-key","knownHosts":"/protected/store-known-hosts"}},"sms":{"command":"/opt/store/bin/sms-read","endpoint":"https://sms.example","scope":"store-investigation","name":"lmt-db-investigation"}}Set LMT_DB_SMS_CREDENTIAL to the protected SMS bootstrap credential.
Alternatively supply the retrieved role value as LMT_DB_CREDENTIAL.
The bootstrap credential never crosses SSH. Select --environment dev or
--environment prod on stores/schema/query; a missing route fails, without
local fallback. JSON/CSV/table and limit flags work identically remotely.
Transport uses system OpenSSH, pinned known_hosts, batch mode, no PTY or
forwarding, no shell interpolation, bounded input/output and a 15-second
transport deadline. SMS failures fail the selected operation, without fallback.
Administrator provisioning (not performed by this change)
Install the packed npm artifact on the Store host using Node >=24.11.0.
Locate its absolute dist/helper.mjs. Run it where the current SQLite file
and its WAL/SHM are accessible together (inside the owning container if needed).
Do not use a copy of a live main file, immutable SQLite mode, Docker socket
access, broad sudo, or developer SSH credentials. The helper account gets
read access only to configured Store files and required WAL directories;
apply host memory/process limits as appropriate.
Create a root-owned, non-writable host config readable only by the helper account. It contains an explicit host environment, absolute current Store paths, and authoritative grants, for example:
{"environment":"prod","targets":[{"environment":"prod","owner":"broker-2","store":"candles","path":"/stores/candles.sqlite","build":"deployed-owner-build"}],"credentials":[{"role":"Investigation","sms":{"command":"/opt/store/bin/sms-read","endpoint":"https://sms.example","scope":"store-investigation","name":"lmt-db-investigation"},"bootstrapFile":"/etc/lmt-db/verifier-sms-token","targets":[{"environment":"prod","owner":"broker-2","store":"candles"}]},{"role":"Maintenance","sms":{"command":"/opt/store/bin/sms-read","endpoint":"https://sms.example","scope":"store-maintenance","name":"lmt-db-maintenance"},"bootstrapFile":"/etc/lmt-db/verifier-sms-token","targets":[{"environment":"prod","owner":"broker-2","store":"candles"}]}]}Provision exactly two independently random shared Store role values in the two
SMS scopes. The agent bootstrap grant can read only the Investigation secret,
never Maintenance, Operator Directory, trading credentials or the verifier
bootstrap. The host verifier bootstrap can read both role secrets, but cannot
change them. SMS ACLs enforce this separation; Store grants in the host registry
independently enforce environment/owner/Store scope. Neither credential carries
client-controlled scope claims. A trusted sms-read executable implements
sms-read read NAME, consuming SMS_ENDPOINT/SMS_SCOPE/SMS_CREDENTIAL and returning
only the raw secret value on stdout. Install a pinned SMS CLI and a root-owned
wrapper for that command; do not dynamically download code on helper execution.
The adapter follows the existing SMS CLI environment protocol, suppresses its
stderr, limits secret size to 64 KiB and bounds each call to 15 seconds.
Host config, verifier bootstrap, SMS wrapper, helper package, Node binary,
Store directories and every parent directory must be protected against client
replacement/symlinks. Only administrators may change grants. The verifier reloads
configuration and retrieves current SMS values on every request, without a cache.
Rotate one SMS role value to revoke its previous value for every client; the
other remains independent. An unavailable verifier fails closed. In-flight
operations already authenticated may complete. A protected static token
record remains available for isolated/local provisioning, with the same grant
shape and reload semantics; it is not the SMS production provisioning path.
Use a dedicated SSH identity/account with no password login, no other keys, no writable shell startup files, no user rc or user environment. Install a root-owned wrapper, replacing paths below with actual installation paths:
#!/bin/sh
exec /usr/bin/env -i PATH=/usr/bin:/bin SSH_ORIGINAL_COMMAND="$SSH_ORIGINAL_COMMAND" SSH_TTY="$SSH_TTY" /absolute/node /opt/lmt-db/dist/helper.mjs /etc/lmt-db/host.jsonThe forced wrapper deliberately discards NODE_OPTIONS and client environment;
the host config path is fixed by the administrator, never environment supplied.
The helper accepts only SSH_ORIGINAL_COMMAND exactly lmt-db-v1, refuses
SSH_TTY and reads one bounded JSON envelope from stdin. Do not authorize direct
arbitrary Node execution.
Put the client's public key in an administrator-owned authorized_keys file:
restrict,command="/opt/lmt-db/helper-wrapper" ssh-ed25519 PUBLIC_KEYConfigure sshd for this account with PasswordAuthentication no,
KbdInteractiveAuthentication no, PermitTTY no, DisableForwarding yes,
PermitTunnel no, PermitUserRC no, PermitUserEnvironment no, and the same
ForceCommand wrapper. Do not AcceptEnv for this account. Check sshd -t and
the effective Match configuration before enabling access through the existing
authorized operational workflow. Pin the host key out of band. Keep the
account's login shell executable for forced commands, but no unrestricted
authentication route. No provisioning, service restart, deployment or real SMS
mutation was performed here.
Local execution also uses hostExecutor(configPath); the local administrator-owned registry is the trust boundary, not the CLI's target selection. Environment variables cannot alter the registry's environment. Local OS users with direct Store/config access are outside this application boundary.
Reusable SUK-118 interfaces: createExecutor({environment,targets,verify}), hostExecutor(fixedConfigPath), the bounded {request,credential} SSH envelope, and the unchanged positional lossless result/provenance contract. Do not expose hostExecutor configuration selection to remote clients. Do not interpret an unreachable owner as stopped or add direct writes without startup exclusion.
SUK-118 stopped-owner Maintenance
lmt-db mutate --config /protected/store.json --environment local --owner broker-1 --store candles --batch /protected/batch.json
uses the same credential, host registry, SMS and restricted SSH boundary. Dev uses
its configured remote route. Only scoped Maintenance on local/dev can mutate;
Investigation and Prod are rejected by the executor before opening the Store.
Provision the helper with write access only to authorized current Store files,
WAL directories and adjacent ownership lock files. Owner and helper must either
share the protected OS uid or use administrator-precreated lock inodes with
explicit shared write permissions; creation mode 0600 is not an automatic grant
to a separate SSH account. Never grant clients directory replacement rights. No such provisioning was
performed here. This package now also requires Linux/util-linux flock on PATH
for owners and helper; missing flock fails closed.
Batch file example:
{"operations":[{"action":"insert","table":"records","values":{"id":{"type":"integer","value":"3"},"value":"repair"}},{"action":"update","table":"records","identity":{"id":{"type":"integer","value":"1"}},"original":{"id":{"type":"integer","value":"1"},"value":"old"},"changes":{"value":"new"}}],"overwrite":false}One batch targets exactly the selected Store, up to 1000 ordered operations.
Actions are insert (values), update (identity, original, changes) and
delete (identity, original). Values use the query wire format: null,
TEXT string, finite JS REAL number, {type:"integer",value:"signed decimal"},
or {type:"blob",base64:"canonical base64"}. JSON numbers bind as SQLite REAL, including large integral doubles; use tagged
integers for SQLite INTEGER values so int64 precision is preserved. SQLite applies affinity and constraints;
there is no additional product/type validation. Foreign keys are enabled before
BEGIN IMMEDIATE. Any failure rolls back the entire batch, including deferred
foreign-key failures at COMMIT. No writable SQL or schema commands are accepted.
Identity is all declared primary-key columns in schema order; if no primary key,
use {"$rowid": taggedInteger} with the first unshadowed rowid/rowid/oid alias.
A target must match exactly one record. Supply all original SELECT * column values
in their lossless wire representation. overwrite:true skips only original-value
comparison, never missing/ambiguous targets, constraints or authorization.
Ownership contract for SUK-119/120: acquireStoreOwnership(path) and
OwnedDatabaseSync are exported by @live-market-terminal/store-maintenance.
The standalone helper implements the identical protocol without a workspace
runtime dependency. Resolve an existing file with realpath, otherwise resolve
its parent; append .lmt-ownership. Open that persistent inode mode 0600 and
acquire shared nonblocking flock for owner connections and exclusive nonblocking
flock for direct maintenance, through inherited fd 3. Shared ownership preserves
normal multi-connection/worker and archive bookkeeping behavior while excluding
maintenance. The TypeScript acquire function defaults to mode "owner"; pass
"maintenance" for exclusive direct ownership. Same-module writable owner connections reference-count ownership so an owner may
use multiple connections; another process remains excluded until all close. Hold the original
open file description before SQLite opens and through SQLite close. Never unlink
or replace lock files, even on crash. Kernel fd closure releases ownership after
SIGKILL; there are no PID files or stale-lock reclamation races. Protect Store
paths, lock inodes and parent directories from replacement; hardlink aliases are
not supported registry identities. All processes must use this protocol, including
owners deployed before enabling Maintenance. An older uncoordinated owner is not
safe for direct writes. Owner startup is bounded and fails/unavailable on lock
conflict using existing opener error behavior. In-memory/read-only connections
do not acquire ownership. Socket absence, refused connections, timeouts and
unreachable owners are never consulted as stopped proof.
The helper requests exclusive direct ownership for stopped non-recording Stores. STORE_OWNED routes to the capability-protected owner batch endpoint after executor authorization. Any owner refusal or transport failure ends the request, without direct fallback. Internal retains its separate validators and protocol. All paths reuse the exact shared executeStoreBatch module.
Successful mutation returns {status:"ok",operations:N} after COMMIT. Timeout or
transport failure has an unknown commit outcome; independently investigate before
retrying, never infer rollback or retry automatically. Batch requests remain
subject to the helper envelope and execution deadline. Running-owner support is supplied by SUK-119/120.
Running local/dev owners (SUK-119) use the separate capability-protected
DB CLI owner protocol documented in packages/store-maintenance/DB-CLI.md.
The helper authorizes the role, environment and target before routing. Configure
optional trusted target ownerSocket when its socket is based on another Store
path. Gate operator-sessions and Broker authenticated-sessions are supported.
A failed/unreachable owner never triggers direct-file fallback. Production has
no owner maintenance listener. Internal retains its existing protocol/validation.
Broker data owners (SUK-120) register candles (including capture_windows), volume-checkpoints, capture-reconciliation and the attached current session-recording writer. Configure each explicit target's ownerSocket to the Broker authenticated session maintenance socket. Set currentOwner:true for session-recording: the helper resolves its current file from the capability-protected runtime inventory after authorization on each request. Discovery omits closed writers; unavailable owners fail explicitly. Do not configure archive/closed-file targets. Recording mutations always route through the worker, never through stopped-file mutation. A selected path is carried to Broker and worker and checked again at execution, so a rotation race refuses rather than editing the replacement. Static path registrations refuse when stale. This inventory protocol is local/dev only.
npm release and helper compatibility (SUK-121)
Administrators dispatch release-lmt-db-cli.yml on main after review/merge.
Other branches cannot publish. Node 24.11.0 and pnpm 10.33.3 build from the frozen
lockfile. The shared release-version helper selects the next stable version from
npm history (first release 0.1.0). The workflow packs once, installs that exact
artifact into disposable directories for the owner/SSH/maintenance paths, then
publishes the same bytes. Confirmation compares registry name, exact version and
SHA-512 integrity, refusing mismatches. A confirmation failure after upload needs
registry investigation before another dispatch; do not assume upload failed.
Release credentials are fetched only after package tests: repository Actions
secret SMS_CREDENTIAL needs SMS read access to infra/NPM_TOKEN at the configured
smsEndpoint in root lmt.config.json. The npm token must permit public publication
of @ai-digital-factory/lmt-db-cli. No release has been executed by this change.
Install npm install -g @ai-digital-factory/lmt-db-cli@VERSION; verify
lmt-db --help. The client and host helper must be pinned to the same tested
package version/build for initial rollout, using protocol lmt-db-v1.
The protocol has no version negotiation: do not assume compatibility across
versions. Upgrade the restricted helper and client together after isolated tests.
Owner images must include the SUK-118 ownership lock protocol and SUK-119/120
owner batch endpoint before enabling Maintenance. A client upgrade alone does
not provision helper accounts, role secrets, registry entries or owner support.
Current SQLite identities supported by these owners are Gate operator-sessions; Broker authenticated-sessions, candles (including capture_windows), volume-checkpoints, capture-reconciliation, and the attached current session-recording writer. Registry entries explicitly bind environment, Broker, Store and current path; configure ownerSocket/currentOwner as described above. Discover schema before incident queries. JSON Market Watch/Price Cross, Retained Quotes, archives/snapshots/backups/R2, schema changes, cross-Store SQL and transactions, Prod writes and Prod Internal access remain excluded.
For SUK-29, provision an Investigation-only route/grant to the current Prod Broker 2 candle/capture Store, pinned SSH host key/identity and version-matched forced helper first. Discover its schema; select IDEA records at 2026-10-27 14:17, 14:28, 14:29 and 14:33 IST (08:47, 08:58, 08:59, 09:03 UTC). Retain SQL, result provenance and build identity. No archive retrieval, restart, auth replacement or mutation is authorized. Missing access cannot establish whether these historical records exist. Motivating evidence remains attached to SUK-114, not duplicated here.
Nonfinite SQLite REALs use {"type":"real","value":"Infinity"} and
{"type":"real","value":"-Infinity"}. JSON, CSV JSON payloads and table cells
preserve these tags separately from SQL NULL. Structured mutation values and
expected originals accept the same tags; NaN is not a SQLite REAL value.
All render options are validated before execution. Mutation byte budgets must
fit both the bounded success and timeout envelopes (41 bytes including newline,
allowing up to 1000 operations). Successful mutations return that small acknowledgement even
for CSV/table format. Within that prevalidated budget,
a mutation timeout returns status: "timeout", outcome: "unknown" and exit 2.
Lost owner/transport acknowledgements also do not establish rollback. Inspect
persisted state before deciding whether to retry.
Session Recorder maintenance sequence edits change stored evidence, not the run's independent arrival sequence allocator. An edited INT64_MAX is retained exactly in subsequent lifecycle/rotation evidence; recording does not increment that edited value. Ordinary future arrival sequences can still collide with maintenance-created rows; SQLite constraints then reject that recording batch.
Protected SMS bootstrap provisioning
From the LMT root, run pnpm db credential provision --environment dev. The
terminal prompt masks input. Automation can use --credential-stdin and protected
stdin instead. Never pass tokens as arguments or paste them into chat.
The token is saved as JSON in ~/.lmt-db/secrets.pem (a plaintext protected file,
not encryption), with directory mode 0700 and file mode 0600. This is separate
from ~/.lmt: Operator login credentials for lmt / lmt web do not work
here. Provision an SMS token with infra/ssh read (not Operator scopes).
Provisioning does not read or alter Operator credentials.
When client configuration selects SMS, LMT_DB_SMS_CREDENTIAL overrides this
saved bootstrap; otherwise the saved value is loaded automatically. Provisioning
only saves the SMS token: it does not verify SMS permissions, obtain SSH keys or
create the Dev helper/routing configuration. Explicit --config remains available for configured-helper operations. Dev
read discovery, schemas and queries support the automatic routing described below.
Existing Dev infrastructure credential (session override)
pnpm db connection check --environment dev reads HETZNER_IP, USER_NAME
and PRIVATE_KEY from SMS scope infra/ssh, using the saved DB bootstrap and
pinned sms-cli 0.1.3. It uses the configured Vault endpoint and Dev's Hetzner host;
LINODE_IP and Prod are not read by this check. SSH uses an owner-only temporary
identity file, removed after the bounded check; fetched connection material is
cached as described below. SSH uses strict host-key
verification against ~/.ssh/known_hosts; it does not add host keys automatically.
The command executes only true, without reading or changing Stores.
The user selected the existing infrastructure SSH credential and deferred role setup for this Dev trial. This connectivity check does not establish restricted helper provisioning or Investigation/Maintenance isolation. Configured-helper operations retain their separate existing executor.
Dev SSH credential cache
Config-free Dev commands (connection check, stores, tables, schema and
query) reuse the host, username and private key fetched from infra/ssh across
CLI invocations. The first fetch reads the three SMS records concurrently.
Connection material is cached without expiry in ~/.lmt-db/dev-ssh-cache.json:
the directory is owner-only (0700), and the file is owner-only (0600). Like the
saved SMS bootstrap, this is protected plaintext, not encrypted storage. It
survives terminal closure and machine restarts; no background service is needed.
The cache is bound to the effective SMS bootstrap (LMT_DB_SMS_CREDENTIAL takes
precedence over the saved token). Changing that token discards the old entry on
the next operation. SSH authentication rejection discards cached credentials,
fetches current values from SMS, and retries once before the remote command runs.
Rejected fresh credentials are not retried. Network errors, host-key failures and
remote-command failures do not trigger refresh or replay. A failed refresh does
not fall back to the discarded entry. Every command still opens a fresh SSH
connection with a temporary identity file, removes that temporary file afterward,
and rediscovers current Store/container metadata.
Remote SMS changes that leave cached SSH credentials working are not detected automatically. After changing the remote host, username or still-valid key, run:
pnpm db connection cache clear --environment dev
# Installed package:
lmt-db connection cache clear --environment devClearing is idempotent and retains the SMS bootstrap and pinned host keys. The next Dev operation fetches fresh connection material. Configured restricted-helper routes, local/prod access and maintenance behavior do not use this cache.
Config-free Dev discovery
After provisioning and verifying SSH, pnpm db tables --environment dev uses the
same saved SMS bootstrap and existing infra/ssh credentials as stores, but
also returns table and view names for every available Store in one command.
pnpm db stores --environment dev uses the
saved SMS bootstrap and existing infra/ssh credentials. It discovers running
Gate/Broker processes from Docker runtime environment/command identity and reads
their deployed lmt.config.json. No container names or database paths are client
inputs. Output uses logical owner/Store IDs, build revision, inspection time and
explicit unavailable Store/owner outcomes. Only configured current SQLite files
are checked; no directory/archive scan is performed. The remote host needs
Python 3 and Docker access; probes use the running application's Node runtime.
This discovery runs no SQL and makes no remote changes. Automatic Session Recording discovery is not implemented in this slice. Explicit configured-helper operations remain supported separately.
Config-free schema inspection is also available:
pnpm db schema --environment dev --owner broker-1 --store candles.
It rediscovers the deployed owner and configured current path, then runs a fixed
schema query on a read-only connection inside that owner's container. Schema
version, read time and build provenance accompany bounded rows. The schema operation supports JSON, CSV and table output with its fixed bounds;
arbitrary SQL is not accepted by this operation. Config-free SQL queries are documented below.
Config-free Dev SQL
pnpm db query --environment dev --owner broker-1 --store candles --sql 'SELECT COUNT(*) AS candle_count FROM candles'
requires no explicit config or container names. It resolves the running owner's
configured current Store through Docker's mount metadata and opens the same live
SQLite file, including WAL, read-only on the host. No database copy is made. The
host Python sqlite3 executor independently authorizes read-only SQL; attachments,
writes, schema/connection changes, file/extension functions and multiple statements
are refused. Owner/Store selection remains explicit. Mounts unavailable to the host
fail without a container-copy or local fallback. This trial uses the existing broad
infrastructure SSH credential per the user's override; role isolation is deferred.
The existing deadline/row/byte flags and JSON/CSV/table output apply to query results. Query deadlines cover SQLite execution, separately from bounded SMS/SSH and discovery. Native SQLite allocation is not peak-memory quota-bound. Large integers, blobs and infinities use the same tags as configured-helper operations. SQL output and all its columns may contain sensitive stored values. Prod automatic routing and config-free mutation are not enabled by this Dev implementation.
