Warm Daemon & Service Layer
sem eliminates repeated cold-start latency for SQLite index loading, FastEmbed ONNX inference, and local GGUF models by running an auto-managed, user-private Unix-domain socket daemon (sempropos.daemon) backed by the UI-agnostic SemService query engine (sempropos.service).
When the daemon is disabled (daemon.enabled = false), unreachable, or bypassed (--no-daemon), the CLI instantiates SemService in-process and executes the exact same code path.
Request Lifecycle & Fast Path#
sequenceDiagram
participant Shell as Shell / User
participant CLI as sempropos.cli
participant Client as DaemonClient (stdlib-only)
participant Server as SemDaemonServer (AF_UNIX)
participant Svc as SemService
Shell->>CLI: sem --porcelain -- "show disk usage"
CLI->>Client: _try_porcelain_fast_path()
alt Daemon already listening
Client->>Server: JSON-RPC ask (skip Typer/Rich/NumPy)
Server->>Svc: ask(query)
Svc-->>Server: verified command
Server-->>Client: {"ok": true, "result": ...}
Client-->>CLI: stdout command (exit 0)
else Cold start or full CLI
CLI->>Client: request(method, params, auto_start=true)
Client->>Client: ensure_started() -> python -m sempropos.daemon
Client->>Server: JSON-RPC request
Server->>Svc: ask / search / show / doctor
Svc-->>Server: response dict
Server-->>Client: response frame
end
SemService Application Layer#
SemService (src/sempropos/service.py) owns all read-only query execution and diagnostics without importing typer or rich:
- Hot connection & automatic reload:
_get_conn()caches a read-only SQLite connection (open_connection(read_only=True)) and tracks theindex.metamodification timestamp and database path. Wheneversem installorsem updatereplacesindex.meta,SemServiceautomatically closes the stale handle, callsreload_embeddings(), and reopens fresh state on the next request. - Tri-modal operations:
search(query, limit, category)— Instantaproposreplacement usinganalyze_query+ weighted Porter BM25; invokes semantic recall only when embeddings are already warm in memory or BM25 returns zero hits.show(tool_name, subcommand, flag_filter)— Instantman/--helpcard lookup viarepository.get_tool(), with optional subcommand focus and case-insensitive flag filtering.ask(query, tool_filter, backend, alternatives)— Full retrieval,build_prompt(680-word budget), provider synthesis, one_repair_onceretry on non-empty unusable output, andverify_commandgrounding/safety classification.doctor()— Reports index completeness, revision, parse coverage percentages, source breakdown, unindexed$PATHbinaries, provider status, and local GGUF runtime readiness.
- Clean teardown:
close()closes the SQLite connection, clears mmap vectors, and callsshutdown_providers()to unload ONNX/GGUF models and terminate any managedllama-serverchild process.
SemDaemonServer & Lifecycle#
SemDaemonServer (src/sempropos/daemon/server.py) binds a private Unix stream socket (AF_UNIX, SOCK_STREAM) at $XDG_RUNTIME_DIR/sempropos/sem.sock (falling back to <data_dir>/run/sem.sock when XDG_RUNTIME_DIR is absent or SEMPROPOS_DATA_DIR / SEMPROPOS_RUNTIME_DIR is set):
- Single-instance locking & permissions: Runtime directory permissions are tightened to
0700, the socket file ischmod 0600, andfcntl.flock(LOCK_EX | LOCK_NB)onsem.lockguarantees at most one active daemon per runtime directory. Stale sockets from ungraceful exits are unlinked before binding. - Supported RPC methods:
ping,status,reload,shutdown,list_names,doctor,search,show, andask. - Idle auto-shutdown: The accept loop polls every
0.5sand exits cleanly afterdaemon.idle_timeout_seconds(default900s/ 15 minutes) of inactivity, releasing all held RAM/VRAM and unlinkingsem.sockandsem.pid.SIGINTandSIGTERMtrigger the same clean teardown.
DaemonClient & --porcelain Fast Path#
DaemonClient (src/sempropos/daemon/client.py) and protocol.py import only Python standard-library modules (socket, json, os, subprocess, time, pathlib) using newline-delimited JSON frames (PROTOCOL_VERSION = 1, MAX_MESSAGE_BYTES = 2 MiB):
try_fast_porcelain_ask(): Invoked bysempropos.cli:mainbefore importing Typer, Rich, NumPy, or FastEmbed. When--porcelainis passed (as inCtrl+Sshell widgets) and a warm daemon is already listening, the CLI sends theaskRPC directly and prints the command in milliseconds.- Lazy auto-start:
DaemonClient.request(..., auto_start=True)spawns detachedsys.executable -m sempropos.daemon --socket <path>(start_new_session=True,close_fds=True) if the socket is absent and pollspingfor up to3.0sbefore retrying the RPC.
Configuration & Management#
daemon.enabled(defaulttrue): Enables daemon dispatch for CLI queries.daemon.auto_start(defaulttrue): Allows queries to spawn the daemon on demand.daemon.idle_timeout_seconds(default900, minimum30): Inactivity window before automatic shutdown.- CLI controls:
sem daemon status [--json],sem daemon start,sem daemon stop, andsem daemon restart.