Skip to main content

Advanced Configuration

External tool integration, hash worker settings, network timeouts, and startup optimizations.

External Tools​

External tools generate thumbnails for videos and office documents.

FFmpeg (Video Thumbnails)​

FFmpeg generates thumbnails from video files.

./mahresources -ffmpeg-path=/usr/bin/ffmpeg -db-type=SQLITE -db-dsn=./db.sqlite -file-save-path=./files

Or with environment variables:

FFMPEG_PATH=/usr/bin/ffmpeg

If not specified, FFmpeg is auto-detected from your PATH.

LibreOffice (Office Document Thumbnails)​

LibreOffice generates thumbnails for Word documents, spreadsheets, and presentations.

./mahresources -libreoffice-path=/usr/bin/soffice -db-type=SQLITE -db-dsn=./db.sqlite -file-save-path=./files

Or with environment variables:

LIBREOFFICE_PATH=/usr/bin/soffice

Auto-detected from your PATH (soffice or libreoffice) if not specified.

:::tip macOS On macOS, LibreOffice is typically at:

/Applications/LibreOffice.app/Contents/MacOS/soffice

:::

Hash Worker Configuration​

A background worker calculates perceptual hashes for images, enabling visual similarity search.

Worker Settings​

FlagEnv VariableDefaultDescription
-hash-worker-countHASH_WORKER_COUNT4Number of concurrent workers
-hash-batch-sizeHASH_BATCH_SIZE500Resources processed per batch
-hash-poll-intervalHASH_POLL_INTERVAL1mTime between batch cycles
-hash-similarity-thresholdHASH_SIMILARITY_THRESHOLD10Maximum Hamming distance for similarity
-hash-ahash-thresholdHASH_AHASH_THRESHOLD5Max AHash Hamming distance for the secondary similarity check; 0 disables it
-hash-worker-disabledHASH_WORKER_DISABLED=1falseDisable the hash worker entirely
-hash-cache-sizeHASH_CACHE_SIZE100000Max entries in hash similarity LRU cache

Tuning for Your Hardware​

High-performance server:

./mahresources \
-hash-worker-count=8 \
-hash-batch-size=1000 \
-hash-poll-interval=30s \
...

Resource-constrained environment:

./mahresources \
-hash-worker-count=1 \
-hash-batch-size=100 \
-hash-poll-interval=5m \
...

Disable entirely:

./mahresources -hash-worker-disabled ...

Similarity Threshold​

The -hash-similarity-threshold controls how similar images must be to be considered matches:

  • Lower values (e.g., 5): Stricter matching, finds near-duplicates only
  • Higher values (up to the maximum of 11): Looser matching, finds more variations. Pairs are only stored up to distance 11, so a larger value has no additional effect and the runtime setting refuses it
  • Default (10): Good balance for finding similar images

Thumbnail Worker Configuration​

A background worker generates thumbnails for video files using FFmpeg. It runs in batch cycles, similar to the hash worker.

FlagEnv VariableDefaultDescription
-thumb-worker-countTHUMB_WORKER_COUNT2Concurrent thumbnail workers
-thumb-worker-disabledTHUMB_WORKER_DISABLED=1falseDisable the thumbnail worker entirely
-thumb-batch-sizeTHUMB_BATCH_SIZE10Videos processed per backfill cycle
-thumb-poll-intervalTHUMB_POLL_INTERVAL1mTime between backfill cycles
-thumb-backfillTHUMB_BACKFILL=1falseBackfill thumbnails for existing videos

Enable backfill to generate thumbnails for videos that were uploaded before FFmpeg was configured:

./mahresources \
-thumb-backfill \
-thumb-worker-count=4 \
-thumb-batch-size=50 \
...

Video Thumbnail Settings​

Fine-tune individual video thumbnail generation:

FlagEnv VariableDefaultDescription
-video-thumb-timeoutVIDEO_THUMB_TIMEOUT30sTimeout for a single FFmpeg thumbnail job
-video-thumb-lock-timeoutVIDEO_THUMB_LOCK_TIMEOUT60sTimeout waiting for a thumbnail lock
-video-thumb-concurrencyVIDEO_THUMB_CONCURRENCY4Max concurrent video thumbnail jobs

Network Timeouts​

Configure timeouts for downloading remote resources:

FlagEnv VariableDefaultDescription
-remote-connect-timeoutREMOTE_CONNECT_TIMEOUT30sTimeout for establishing connection
-remote-idle-timeoutREMOTE_IDLE_TIMEOUT60sTimeout when no data is received
-remote-overall-timeoutREMOTE_OVERALL_TIMEOUT30mMaximum total download time
-remote-user-agentREMOTE_USER_AGENTbrowser-likeUser-Agent the server's own fetches send

For Slow Networks​

./mahresources \
-remote-connect-timeout=60s \
-remote-idle-timeout=120s \
-remote-overall-timeout=1h \
...

For Large Files​

./mahresources \
-remote-overall-timeout=2h \
...

MRQL Query Timeout​

Limits the maximum execution time for MRQL (Mahresources Query Language) queries:

FlagEnv VariableDefaultDescription
-mrql-query-timeoutMRQL_QUERY_TIMEOUT10sMaximum execution time for a single MRQL query
# Allow longer-running MRQL queries
./mahresources -mrql-query-timeout=30s ...

Inline MRQL Page Query Budget​

Bounds how many distinct MRQL queries a single page render may execute through inline [mrql] shortcodes:

FlagEnv VariableDefaultDescription
-mrql-page-query-budgetMRQL_PAGE_QUERY_BUDGET200Maximum distinct inline [mrql] queries per page render; 0 disables

Because a category's Custom* templates render once per card, an entity-scoped [mrql] in a CustomSummary runs one query per card -- so a list page of many cards can execute many queries. Identical queries within a render are deduplicated by a per-page cache (free); each cache miss consumes one unit of budget. Once the budget is spent, further distinct queries render the standard MRQL error box ("inline query budget exceeded (N per page)…") instead of executing, and one warning per page is written to the activity log (entity type mrql).

The default of 200 is generous -- a three-query summary on a 20-card page is only 60. Raise it if a legitimately dense page trips the limit, or set 0 to disable entirely (deployments with millions of resources are the motivation for keeping it on).

# Raise the per-page inline-MRQL budget
./mahresources -mrql-page-query-budget=500 ...

MRQL Natural-Language Generation​

MRQL generation is optional. Configure a provider, model and key in the AI generation section at /admin/settings; DeepSeek, OpenRouter, OpenAI and Anthropic are supported. MRQL and templates can select different providers and models. Changes apply without restarting, and the runtime settings reference explains credential replacement, clearing/resetting and advanced call budgets. There are no boot flags for provider credentials.

Env VariableDefaultDescription
DEEPSEEK_API_KEY(disabled)Boot fallback for the DeepSeek generation key
OPENROUTER_API_KEY(disabled)Boot fallback for the OpenRouter generation key; its provider/model must be selected at runtime
OPENAI_API_KEY(disabled)Boot fallback for the OpenAI generation key; its provider/model must be selected at runtime
ANTHROPIC_API_KEY(disabled)Boot fallback for the Anthropic generation key; its provider/model must be selected at runtime
DEEPSEEK_MODELdeepseek-flashDeepSeek model used to draft MRQL
DEEPSEEK_TIMEOUT20sTimeout for one DeepSeek MRQL generation call. Invalid duration values fail startup
DEEPSEEK_API_KEY=sk-...
DEEPSEEK_MODEL=deepseek-flash
DEEPSEEK_TIMEOUT=20s

For the /mrql editor the server sends only the prompt text entered there plus syntax-only MRQL instructions. It does not send local tag lists, categories, saved queries, or database contents to the provider.

Template Generation​

The template provider/model selected at /admin/settings enables generation in the Category, Resource Category and Note Type editors when its key is configured. An existing DEEPSEEK_API_KEY deployment keeps working with DeepSeek by default. Before sending, a dialog shows the provider, models, call budgets and messages, including category identity, layout, current templates, schema, bounded samples and reference documentation as applicable. Drafts stay pending until Apply. See Custom Templates for the data sent, repair and whole-template generation. By default a request runs as a Generation run whose Turn cap, deadline and token budget are runtime settings; see the runtime settings reference.

Each kind of template call can have a runtime model, output-token and timeout override for its selected provider. Other providers use their model's default reasoning. These existing environment settings remain DeepSeek's boot defaults; thinking overrides apply only to DeepSeek. Replace <KIND> below with SLOT (shared CustomCSS), PAIR (one HTML section and its CSS), PLAN (the whole-template design plan), BUNDLE (the single-call bundle profile) or METASCHEMA.

Env VariableDefaultDescription
DEEPSEEK_TEMPLATE_<KIND>_MODELDEEPSEEK_MODELModel for this kind of template call. MRQL generation keeps its own model.
DEEPSEEK_TEMPLATE_<KIND>_THINKINGoffAccepts on/off, true/false or 1/0. Thinking tokens count against the output budget.
DEEPSEEK_TEMPLATE_<KIND>_TIMEOUTDEEPSEEK_TIMEOUTPositive Go duration for one provider call, including time waiting for a provider slot. With thinking on, the default is 60s, or 120s for BUNDLE.
DEEPSEEK_TEMPLATE_REPAIRonOne repair attempt for lint errors or incomplete pairs, when time permits. Accepts the same switch values as thinking.

Invalid environment settings fail startup. With DeepSeek thinking off, the output budget is 4,000 tokens for SLOT, PAIR and METASCHEMA, 1,200 for PLAN, and 8,000 for BUNDLE. With thinking on it is 8,192 tokens, or 16,384 for BUNDLE. OpenRouter, OpenAI and Anthropic default to 8,192 tokens and 60s per call, or 16,384 tokens and 120s for BUNDLE, to leave room for model-default reasoning before visible output. Advanced runtime overrides can tune token caps and call timeouts.

A whole-template request uses a planning call followed by section pairs whenever it includes multiple sections or shared CSS. Its deadline is 55s for DeepSeek and 120s for other providers, independent of per-call overrides. At most five section calls run at once per request and eight template provider calls across the server. Repairs share the request's budget and use no extra rate-limit slot.

Deferred Render Signing Key​

The [lazy], [details], [reload] and [autorefresh] shortcodes hand the browser a sealed token to render part of a template with later. The key that seals those tokens is configured with an environment variable only.

Env VariableDefaultDescription
TEMPLATE_SIGNING_KEY(per-boot random)Secret used to seal the [lazy], [details], [reload] and [autorefresh] deferred-render tokens

When it is unset, each process generates a random key at boot, so a deferred region rendered by one process cannot be opened by another. Set it to a shared value across every process in a multi-process or load-balanced deployment. See Shortcodes.

Job Replay Key​

The Job control plane stores the input a background Job was accepted with as an encrypted replay envelope, so a Retry can re-run the same work under current authorization and policy. The key that seals those envelopes is configured with an environment variable only -- there is no flag and no runtime setting, because a key an administrator could change from /admin/settings is a key that can render every stored envelope unreadable in one click.

Env VariableDefaultDescription
JOB_REPLAY_KEY(a private key file, or per-boot when the database is in-memory)One or more comma-separated base64-encoded 32-byte keys. The first is active; the rest are decrypt-only, so a rotation keeps history readable
DeploymentWhat happens without JOB_REPLAY_KEY
PostgreSQLStartup refuses. Several processes or hosts may write one database, so a key generated by one of them is a key the others will not have
Persistent SQLite, with a data root (-file-save-path)A private 0600 file <file-save-path>/_job_replay_key is created on first start and read on every later one
Persistent SQLite, no data rootStartup refuses: there is nowhere to keep a key the next process can find
In-memory database (-memory-db, -ephemeral)A per-boot key is generated. The Jobs and their envelopes die with the process, so nothing outlives it

Rotate by listing the new key first and the old one after it:

JOB_REPLAY_KEY="$(new-key-base64),$(old-key-base64)"

Envelopes record a non-secret SHA-256 fingerprint of the key that sealed them, so rotation reads older envelopes with their own key and always writes with the active one. A key the process does not hold is reported as exactly that, which is a different failure from a tampered envelope.

The generated key file holds the same base64 form this variable accepts, so an operator moving a single-process deployment to PostgreSQL can copy it into JOB_REPLAY_KEY verbatim. How long a finished Job's envelope stays readable is the runtime setting job_replay_retention; the window always starts when the Job finishes, never when it was accepted, and nonterminal work is never purged.

The generated file is created with owner-only 0600 permissions. Keep the key material protected like the database backup: without it, encrypted accepted inputs cannot be replayed. During rotation, deploy the same ordered keyring to every server process, with the new key first and prior keys after it. Remove an old decrypt-only key only after no retained replay envelope refers to its key ID; checking that all affected envelopes have expired or been explicitly forgotten is part of the rotation.

Job Writer Epoch and Safe Rollout​

Every server checks the database's minimum Job writer epoch immediately after opening the database and before schema migration, cleanup, plugin activation, or dispatch. A binary that does not support the recorded minimum refuses to start. This is the downgrade fence: an older process must not write rows or legacy replay fields after a newer release advances the database.

For an epoch-advancing rollout:

  1. Deploy a release that understands the new epoch to every database writer.
  2. Drain and stop all older processes, including scheduled or standby hosts.
  3. Run the migration/retirement step that verifies the retained inputs and advances the minimum epoch.
  4. Confirm every instance starts with the advanced database before restoring normal traffic.

The Job Center release requires this barrier at startup. After draining every older writer, start the new release with JOB_MIGRATION_WRITERS_DRAINED=1 (or -job-migration-writers-drained) until the migration reaches complete and the minimum writer epoch is 2. Do not set the attestation while an older writer is still connected. Later starts can read the completed barrier from the database.

During rollout, an administrator can inspect the current barrier through GET /v1/admin/jobs/migration-readiness. The response's ready field is true only when the migration barrier is satisfied; writerEpoch reports the database minimum, phase reports the current migration phase, sourceCounts reports per-source counts, blockers lists remaining conditions, and reviewCandidates lists unfinished Jobs to review (see the next section). The endpoint is read-only and requires an administrator role. Check readiness before admitting traffic after an epoch advance, and investigate every blocker before proceeding.

Rollback after epoch advancement uses a compatible release that understands the canonical schema. Do not roll back to a plaintext writer. Keep the release that advanced the epoch available until the rollback window closes.

Two behaviours of paused downloads matter while processes of this release and an earlier one run against one database. An earlier release recorded a person's pause of a download as blocked. Each start of this release records those Jobs as paused, and every process of this release looks for more every five minutes, so ones an older process records later are moved too. And a download paused through the Job Center while an earlier-release process is running its transfer is not paused there: that process does not act on pause requests, so the Job reads Pausing until the transfer ends. Cancel still stops it.

Legacy download and Job compatibility routes remain supported for at least one documented release and six months after canonical cutover.

Unfinished Jobs of accounts deleted before this release​

A Job whose execution_principal column is empty was written before the Job recorded which account it runs as, and that account is worked out from its actor and owner. Deleting an account clears both references and, from this release on, marks them (actor_deleted, owner_deleted), so such a Job ends failed as principal-missing instead of running. A Job whose account was deleted before this release carries no mark: with both references empty it reads as work the server does for itself, and it would run with no account check. Before admitting traffic after the upgrade, list the unfinished ones:

SELECT id, kind, title, state, accepted_at FROM jobs
WHERE state IN ('scheduled', 'queued', 'running', 'paused', 'blocked')
AND execution_principal = ''
AND owner_user_id IS NULL AND actor_user_id IS NULL
AND owner_deleted = false AND actor_deleted = false;

The server finds the same rows itself. The readiness check reports them as reviewCandidates (their count, and the oldest 100 by id, Kind, state and acceptance time), and each start logs a warning naming them while any remain. They do not make ready false and do not stop the server from starting, because the row cannot tell them apart from legitimate work, and cancelling one needs a running server.

A row here either belongs to an account deleted before this release or was started with no account at all, such as plugin work that no request started; the row does not record which. Judge each by its Kind, title and time, and cancel the ones a person submitted, or any you cannot place, since cancelled work can be submitted again. Cancel as an administrator with mr job command <id> cancel --confirm, which reads the Job's current version and sends an idempotency key for you. Through the API it is POST /v1/jobs/{id}/commands/cancel with a JSON body carrying the Job's current version from GET /v1/jobs/{id} as expectedVersion and a unique idempotencyKey (see the Job Center API).

Cancel works only where the Job offers it (jobs get lists its commands). Two Kinds offer none while unfinished. For a plugin-action Job, disable the plugin it belongs to until the Job has ended: a disabled plugin's waiting work does not run. A job-summary-export Job summarizes Job history under the scope sealed when it was accepted, and what it writes can be opened only by an administrator, so it can be left to finish.

Restoring a Pre-Retirement Backup​

A database backup taken before plaintext retirement may contain old replay payloads and URLs. Restore it into an isolated environment with the matching file storage and JOB_REPLAY_KEY, then run the current migration and retirement verification barrier again. Do not expose the restored instance or allow an old writer to connect until the barrier verifies every retained source and the writer epoch. Then inspect GET /v1/admin/jobs/migration-readiness as an administrator and confirm ready is true and blockers is empty. A previous completion marker is not proof for the restored copy.

Every start compares each scrubbed source row with the projection recorded when it was scrubbed. A row that no longer matches is treated as restored: every such row is re-examined in the same start, one whose input matches its canonical Job is scrubbed again, and one that does not is quarantined and reported as a source-quarantined blocker until it is resolved. A deferred download records the Job it started on its row when it comes due, which can be after it was scrubbed; that change alone is not a restored source. A deferred-download source that was quarantined for it, and whose row still matches its scrubbed projection, is returned to scrubbed at the next start.

A source row can outlive its Job: Job history retention deletes an ended Job and keeps the source row and its mapping. Readiness does not ask for the replay input of a Job that no longer exists, because retention deletes only Jobs that have ended. Before the sources are retired, the migration treats such a source as one whose replay input expired: it is not quarantined, and its plaintext is scrubbed like any other expired source.

Plugin Command Runtime Ownership​

Plugin command runs and command imports use an exclusive staging-root lease and a database runtime fence. The supported deployment has one fenced command runtime owner per database and staging namespace. Other Job Kinds and the Job Service may run on multiple processes, but independent command runtimes with different staging roots must not share one database. A replacement owner must prove the prior process and its child process groups are quiescent before it dispatches or cleans up work.

Upload and Request Size Limits​

Bound the size of request bodies the server accepts:

FlagEnv VariableDefaultDescription
-max-upload-sizeMAX_UPLOAD_SIZE2147483648 (2 GiB)Maximum per-upload body size in bytes for resource and version uploads; 0 = unlimited
-max-import-sizeMAX_IMPORT_SIZE10737418240 (10 GiB)Maximum group-import tar upload size in bytes
-max-json-bodyMAX_JSON_BODY0 (unlimited)Maximum application/json request body size in bytes; 0 disables the limit
-max-user-tokensMAX_USER_TOKENS100Maximum API tokens a single user may hold; 0 disables the cap

:::tip Harden JSON limits under -auth -max-json-body defaults to 0 (unlimited) to preserve the historical unbounded behaviour. When -auth is enabled, any authenticated user can POST JSON, so setting an explicit limit is recommended. The limit keys on Content-Type, so multipart uploads (bounded by -max-upload-size) are unaffected. The login endpoints are always capped at a fixed 64 KiB, whatever this is set to. :::

Background Jobs and Exports​

FlagEnv VariableDefaultDescription
-max-job-concurrencyMAX_JOB_CONCURRENCY6Concurrency budget for the shared background job manager
-export-retentionEXPORT_RETENTION24hHow long completed group-export tars stay on disk before cleanup

Server Binding​

Configure the server address and port:

# Listen on all interfaces, port 8181
./mahresources -bind-address=:8181 ...

# Listen on localhost only
./mahresources -bind-address=127.0.0.1:8181 ...

# Custom port
./mahresources -bind-address=:3000 ...

Startup Optimizations​

On large databases, certain startup operations can be slow. These flags reduce startup time:

Disables full-text search index initialization:

./mahresources -skip-fts ...

Use this if you do not need text search functionality.

Skip Version Migration​

Skips the resource version migration at startup:

./mahresources -skip-version-migration ...

Useful after the initial migration has completed on a large database.

Limit Database Connections​

For SQLite under concurrent load (like E2E tests):

./mahresources -max-db-connections=2 ...

Reduces lock contention at the cost of throughput under heavy load.

Share Server​

A separate share server can expose notes publicly. It is disabled by default and only starts when a port is configured.

:::warning Default Bind Address The share server binds to 0.0.0.0 (all interfaces) by default. If you only want the share server accessible locally, set -share-bind-address=127.0.0.1. :::

FlagEnv VariableDefaultDescription
-share-portSHARE_PORT(disabled)Port for the share server. Must be set to enable sharing.
-share-bind-addressSHARE_BIND_ADDRESS0.0.0.0Bind address for the share server
-share-public-urlSHARE_PUBLIC_URL(unset)Externally-routable base URL for shared notes (e.g. https://share.example.com). When unset, the share UI shows a warning and the relative /s/<token> path instead of a bind-address fallback.

Example​

# Enable share server on port 8282 (accessible on all interfaces)
./mahresources -share-port=8282 ...

# Enable share server on localhost only
./mahresources -share-port=8282 -share-bind-address=127.0.0.1 ...

Contextual links in the app point to the published documentation site. These are runtime-editable via /admin/settings.

FlagEnv VariableDefaultDescription
-docs-site-base-urlDOCS_SITE_BASE_URLhttps://egeozcan.github.io/mahresourcesBase URL used for contextual documentation links.
-docs-links-disabledDOCS_LINKS_DISABLED=1falseHide all contextual external documentation links in the app.

MCP Endpoint​

Serve the Model Context Protocol at /mcp for AI agents.

FlagEnv VariableDefaultDescription
-mcpMCP_ENABLED=1falseServe the MCP endpoint at /mcp. With authentication enabled it requires an API token
-mcp-allowed-originsMCP_ALLOWED_ORIGINS(empty)Comma-separated browser origins /mcp accepts. Empty refuses every browser request

Log Cleanup​

Automatically delete old log entries on startup:

FlagEnv VariableDefaultDescription
-cleanup-logs-daysCLEANUP_LOGS_DAYS0 (disabled)Delete log entries older than N days on startup

Example​

# Delete logs older than 90 days on each startup
./mahresources -cleanup-logs-days=90 ...

Plugin Command Configuration​

Declared plugin commands are trusted host processes, not sandboxed Lua. They run as the Mahresources service account with unrestricted process networking and the OS account's filesystem reach. Pin the executable path to the smallest trusted set of absolute directories; the inherited startup PATH default is a trust boundary, not convenience isolation.

FlagEnvironmentDefaultDescription
-plugin-command-pathPLUGIN_COMMAND_PATHstartup PATH snapshotPath-list of nonempty absolute trusted executable directories
-plugin-command-staging-pathPLUGIN_COMMAND_STAGING_PATH<file-save-path>/_plugin_commands, or private process temp with MemoryFSOS-backed exchange and import root; relative values resolve once at startup; one active server process may own a root
-plugin-command-run-quotaPLUGIN_COMMAND_RUN_QUOTA8589934592 (8 GiB)Sampled bytes for one run's exchange folder plus import temps
-plugin-command-staging-quotaPLUGIN_COMMAND_STAGING_QUOTA53687091200 (50 GiB)Sampled bytes across the complete staging root
-plugin-command-exchange-retentionPLUGIN_COMMAND_EXCHANGE_RETENTION168hAge from terminal completion before an unleased exchange folder is swept
-plugin-command-output-retentionPLUGIN_COMMAND_OUTPUT_RETENTION720hAge before output-tail rows are pruned; run, claim and import-map rows survive

A server holds an exclusive advisory lease on the staging root from before recovery until command shutdown. A second process configured with the same root puts this process's command runtime into quarantine rather than interrupting or sweeping the first process's live work; the rest of Mahresources continues to serve. Lease acquisition retries after 1s, 2s, 5s, 10s, 30s and 1m, then at the five-minute sweep interval. A durable command database and its staging root are one runtime domain; do not run multiple command-enabled server processes against one such domain.

The database records which staging root it is bound to. A root chosen by the flag, or <file-save-path>/_plugin_commands, keeps the database's retained command outputs and import sources, so that binding survives every restart: a server started with a different root keeps plugin commands unavailable without retrying, and /logs names its own root and the bound root to restart with. The private temporary root used with MemoryFS is deleted when its process exits, so its binding ends with that process: the next server takes the database over with its own private root once the previous one has stopped cleanly, or can be shown to have exited because it ran in this process table (same hostname, boot and PID namespace) and its process no longer exists. A previous server on another host, or one from before a reboot that skipped the clean stop, cannot be shown to have exited, since another machine can share a hostname. Releasing its binding is then an operator decision: once you know that server is not running (a reboot of its host ended it, or you stopped it), start one server with -plugin-command-staging-path set to the root /logs names (it is recreated if missing). That server takes the fence over on the root's own lease, which excludes only processes on its own host, and once it stops cleanly the next MemoryFS server takes the database over as usual. Doing this while the previous server still runs on another host puts two command runtimes on one database. Files a crashed MemoryFS server left in its private root are not carried over; like the MemoryFS library, they lived as long as that process. A binding recorded by a release that did not mark private roots is kept as durable; keep that root pinned with the flag.

The path is used both to resolve a declaration's executable basename and as the child's PATH, so include required helpers too. A yt-dlp command using a separate-video/audio format needs trusted ffmpeg on that path. Child processes receive an allowlisted environment (PATH, HOME, private TMPDIR, LANG, TZ, and MAHR_* run context), have stdin connected to the null device, and do not inherit the server's proxy or plugin egress policy as confinement.

Quotas are sampled, so a fast writer can briefly overshoot. Size the per-run quota for merge peak, not final output: separate video and audio plus muxed output can consume roughly twice the final file. An import streams the admitted source into AddResource's one immutable scratch copy, so its staging peak is approximately twice the source size. The global sample is refreshed at startup and after retention sweeps; command admission reads that cache without walking the staging tree. The global quota refuses new commands but permits imports that drain existing staging bytes. MemoryFS still uses an OS staging root and imported resource copies consume RAM.

A run persists its positive process-group ID together with a host-unique boot-session UUID. The UUID is private host state: it is not shown in plugin Lua, JSON, or administrator command history. Recovery never inspects or signals a PGID proven to come from another boot. Otherwise it must verify ownership before signaling. Linux and Darwin process inspection treats an all-zombie group as dead because zombies cannot write; a successful signal-zero probe is only conservative evidence that a process-table entry still holds the PGID. Other supported Unix targets use probe-only inspection in this release and cannot prove a zombie-only group dead, so quarantine there may require the parent to reap the group or a restart.

Lease contention and a live or uninspectable recovery group quarantine only the command runtime. Command and exchange calls return an unavailable error, administrator cancellation is disabled and returns HTTP 503 without setting the durable cancellation latch, and recovery continues automatically. Lease contention follows the short capped schedule above. A recovery blocker retains the staging lease and retries every five minutes; a blocker waiting for a process group that is alive or could not be inspected is also checked every five seconds, and recovery runs again as soon as that group has exited, so an orphan that dies with its crashed server's pipes holds commands back for seconds rather than minutes. A blocker with no recorded group, or a group from another boot, is changed by no exit and waits for the five-minute scan. Recovery-blocker warnings in /logs enumerate every blocked run ID, PGID, and reason. Lease warnings name the staging root. Retry failures record their failure reason. Healing is also logged. If an operator has independently decided that the named group is abandoned, the immediate recovery action is to terminate it, for example kill -KILL -- -<pgid>. -plugins-disabled is the restart-time escape hatch.

Recovery makes at most one verified signal attempt per run in one server process. A live worker has creation-time authority over its own group and can make at most two signal attempts, with the second allowed only after observing the group alive. It then polls no faster than once per second, keeps the run nonterminal and its global command slot occupied, and emits one /logs capacity warning after a minute. Successful imports persist the resource first, then unlink the source. Cleanup trouble is exposed as source_delete_pending, not as an import error.

On startup, recovery resolves every queued/running run and pending/running import before publishing command surfaces. A blocker leaves those surfaces quarantined until an automatic healing scan succeeds; plugins do not need to be reloaded when the runtime activates. Sweeps skip nonterminal work and active leases, process bounded batches, and stamp successfully removed or already absent exchange directories so historical rows are not rescanned. Only output tails and expired exchange bytes are pruned; durable run/import/map rows remain for replay idempotency and administrator history.

Plugin Configuration​

Plugins extend Mahresources through sandboxed Lua scripts. A declared external command is outside that sandbox; see Plugin System for the distinction.

FlagEnv VariableDefaultDescription
-plugin-pathPLUGIN_PATH./pluginsDirectory to scan for plugin subdirectories
-plugins-disabledPLUGINS_DISABLED=1falseDisable the plugin system entirely

Each plugin lives in a subdirectory of the plugin path and must contain a plugin.lua file. Plugins are discovered at startup but must be explicitly enabled through the management UI or API.

# Custom plugin directory
./mahresources -plugin-path=/opt/mahresources/plugins ...

# Disable all plugins
./mahresources -plugins-disabled ...

Configuration Reference​

FlagEnv VariableDefaultDescription
-bind-addressBIND_ADDRESS-Server address:port
-ffmpeg-pathFFMPEG_PATHauto-detectPath to FFmpeg binary
-libreoffice-pathLIBREOFFICE_PATHauto-detectPath to LibreOffice binary
-hash-worker-countHASH_WORKER_COUNT4Concurrent hash workers
-hash-batch-sizeHASH_BATCH_SIZE500Resources per batch
-hash-poll-intervalHASH_POLL_INTERVAL1mTime between batches
-hash-similarity-thresholdHASH_SIMILARITY_THRESHOLD10Max Hamming distance
-hash-ahash-thresholdHASH_AHASH_THRESHOLD5Secondary AHash Hamming distance check; 0 disables
-hash-worker-disabledHASH_WORKER_DISABLED=1falseDisable hash worker
-hash-cache-sizeHASH_CACHE_SIZE100000Hash similarity LRU cache size
-thumb-worker-countTHUMB_WORKER_COUNT2Concurrent thumbnail workers
-thumb-worker-disabledTHUMB_WORKER_DISABLED=1falseDisable thumbnail worker
-thumb-batch-sizeTHUMB_BATCH_SIZE10Videos per backfill cycle
-thumb-poll-intervalTHUMB_POLL_INTERVAL1mTime between backfill cycles
-thumb-backfillTHUMB_BACKFILL=1falseBackfill thumbnails for existing videos
-video-thumb-timeoutVIDEO_THUMB_TIMEOUT30sTimeout per FFmpeg thumbnail job
-video-thumb-lock-timeoutVIDEO_THUMB_LOCK_TIMEOUT60sThumbnail lock timeout
-video-thumb-concurrencyVIDEO_THUMB_CONCURRENCY4Max concurrent video thumbnail jobs
-remote-connect-timeoutREMOTE_CONNECT_TIMEOUT30sConnection timeout
-remote-idle-timeoutREMOTE_IDLE_TIMEOUT60sIdle timeout
-remote-overall-timeoutREMOTE_OVERALL_TIMEOUT30mTotal download timeout
-remote-user-agentREMOTE_USER_AGENTbrowser-likeUser-Agent for the server's own fetches
-mrql-query-timeoutMRQL_QUERY_TIMEOUT10sMaximum MRQL query execution time
-skip-ftsSKIP_FTS=1falseSkip full-text search initialization
-skip-version-migrationSKIP_VERSION_MIGRATION=1falseSkip version migration
-max-db-connectionsMAX_DB_CONNECTIONS0 (no limit)Connection pool limit
-share-portSHARE_PORT(disabled)Share server port
-share-bind-addressSHARE_BIND_ADDRESS0.0.0.0Share server bind address
-share-public-urlSHARE_PUBLIC_URL(unset)Externally-routable base URL for shared notes
-docs-site-base-urlDOCS_SITE_BASE_URLhttps://egeozcan.github.io/mahresourcesBase URL for contextual documentation links
-docs-links-disabledDOCS_LINKS_DISABLED=1falseHide contextual documentation links
-mcpMCP_ENABLED=1falseServe the MCP endpoint at /mcp
-mcp-allowed-originsMCP_ALLOWED_ORIGINS(empty)Browser origins /mcp accepts
-cleanup-logs-daysCLEANUP_LOGS_DAYS0 (disabled)Delete old logs on startup
-plugin-pathPLUGIN_PATH./pluginsPlugin directory
-plugins-disabledPLUGINS_DISABLED=1falseDisable plugin system
-plugin-command-pathPLUGIN_COMMAND_PATHstartup PATHTrusted command executable directories
-plugin-command-staging-pathPLUGIN_COMMAND_STAGING_PATHdata/temp derivedCommand staging root
-plugin-command-run-quotaPLUGIN_COMMAND_RUN_QUOTA8 GiBSampled per-run staging quota
-plugin-command-staging-quotaPLUGIN_COMMAND_STAGING_QUOTA50 GiBSampled global staging quota
-plugin-command-exchange-retentionPLUGIN_COMMAND_EXCHANGE_RETENTION168hTerminal exchange retention
-plugin-command-output-retentionPLUGIN_COMMAND_OUTPUT_RETENTION720hOutput-tail retention