Docs

Start here

Three things share one name. SP is a JavaScript library for the browser. SPP is the wire protocol a host program speaks. LE is a separate server for organisations that reuses the protocol. You can use SP alone; the other two are optional.

How the pieces connect

page (SP)  ---- WebSocket bridge, 127.0.0.1 --->  sharedprotocol.c (SPP host)  <---- SPP, port 5221 ---- SPP peers

any client ---- SPP_RPC on 5221, or HTTP on 5223 --->  LocalEnterprise (LE)
  • SP to the SPP host: the page connects out to the host over the local bridge. The host also listens for SPP peers on its own port.
  • LE only listens. It answers SPP_RPC and HTTP from whoever connects and authenticates, never starts a connection of its own, and never runs SharedProtocol.
  • Today the SPP host and LE do not talk to each other. Neither program makes outbound SPP connections, so SP does not reach LE through the host. Anything that wants LE (a script, a service, curl) is a client of LE directly.
<script src="sharedprotocol.js"></script>
<script>
  await sp.ready();
  await sp.newfile("/notes.txt", "hello");
  console.log(await sp.cat("/notes.txt"));
</script>

Want to poke at it first? The test page loads the real library and lets you call any function by name.

SP in the browser

Version 5.0.0. The library defines window.sp (also global.sp) with 459 top-level functions and 37 namespaces. Everything lives in the visitor's browser storage; nothing goes to a server unless you connect peers.

Paths start with /. A fresh node has the folders /repo, /sp, /Trash, /server and /ai. Errors are thrown as [SP-CODE] message, for example SP-GHOST (not found), SP-ALREADY_EXISTS and SP-OP-DENIED.

Permissions

SP has its own users and capabilities. Page code runs as SPNode (UID 200), which holds the capabilities for users, processes and groups but not CAP_FS. With a stock build, sp.newfile, sp.editfile, sp.cat and anything else that reads or writes the tree fails with [SP-OP-DENIED] CAP_FS required, and sp.kvSet quietly stores nothing, so a following kvGet returns null. Paths under /ai, /server and /__peers need UID 0 even when CAP_FS is held, so SQL table writes are refused too. UID 0 is the core itself; nothing outside it can grant itself more.

The test page has a switch that gives SPNode CAP_FS inside that one tab so you can see file operations work. It is a testing aid, not part of the API.

Highlighted API

Signatures are read from the library itself. Optional arguments show their defaults.

Files and folders

sp.newfile(path, content = "", ...flags)

Create a file. Flags such as --stayforever, --sensitive, --lock, --noexec, --fetch: go after the content. Fails if the file exists.

sp.newfolder(path, ...flags)

Create a folder.

sp.cat(path, _suppliedKey = null)

Read a file's content.

sp.lsfolder(path = "/")

List a folder: [{name, type, path}].

sp.editfile(path, content, _suppliedKey = null)

Replace a file's content.

sp.editfolder(path, newName)

sp.del(path)

Delete a file or a folder.

sp.delfile(path, _suppliedKey = null)

Delete a file.

sp.delfolder(path)

Delete a folder.

sp.cpfile(src, dest)

Copy a file.

sp.cpfolder(src, dest)

Copy a folder.

sp.mv(src, dest)

Move a file or folder.

sp.rename(src, newName)

Rename in place; returns {ok, from, to}.

sp.cd(path)

sp.find(pattern, root = "/")

Find paths whose name matches a regular expression under a folder.

sp.grep(pattern, root = "/")

Search file contents; returns matching lines per file.

sp.du(path = "/")

Size of a path in bytes, KB and MB.

sp.stat(path)

Owner, size, timestamps and flags of a path.

sp.catAsync(path)

sp.lsfolderAsync(path)

sp.writeAsync(path, content, mimeType)

sp.trash(path)

sp.restoreFromTrash(trashPath)

sp.symlink(linkPath, targetPath)

sp.checksum(path)

Short checksum of a file's content.

sp.share(data = {})

Tags and metadata

sp.tag(path, ...tags)

Add a tag to a path.

sp.untag(path, ...tags)

sp.findByTag(...tags)

Paths carrying a tag.

sp.meta(path)

sp.getxattr(path, key)

sp.setxattr(path, key, value)

Big files

sp.bigWrite(name, blob)

Store a large Blob outside the normal tree; returns an SPbig:// address.

sp.bigRead(name)

Read it back as a Blob.

Key-value store

sp.kvSet(key, value, opts = {})

Store a value under a key.

sp.kvGet(key, opts = {})

Read a key; null if missing.

sp.kvList(prefix = '', opts = {})

List keys by prefix.

sp.kvRange(start, end, opts = {})

sp.kvDel(key, opts = {})

Delete a key.

sp.kvWatch(key, cb, opts = {})

Messaging and RPC

sp.publish(channel, message)

Publish a message to a topic.

sp.subscribe(channel, cb)

Call a function for every message on a topic. The message is {channel, payload, from, ts}.

sp.unsubscribe(channel, cb)

sp.emit(event, data)

sp.on(event, cb)

sp.off(event, cb)

sp.rpcExport(name, fn, opts = {})

sp.rpcCall(peerId, fnName, args = [], opts = {})

sp.rpcList()

SQL

sp.(q) => sp._sharedSQL.sql(q)

Run one SQL statement. Table changes are written under /server, which needs UID 0.

sp.(qs) => sp._sharedSQL.sqlBatch(qs)

sp.() => sp.db.tables()

List tables.

Memory

sp.memAlloc(name, byteLength = 1024, ...memflags)

Allocate a named block of shared memory; returns {name, byteLength}.

sp.memRead(name, offset = 0, length = null)

Read bytes from a block.

sp.memWrite(name, offset = 0, data)

Write bytes into a block.

sp.memFree(name)

sp.memList()

sp.heapAlloc(handle, value)

sp.heapWrite(handle, value)

sp.heapRead(handle)

Snapshots, versions and watching

sp.snapshot(label, opts = {})

sp.restoreSnapshot(name)

sp.listSnapshots()

Snapshots that exist.

sp.versionList(path)

sp.versionRestore(path, version)

sp.watch(path, callback)

Search

sp.search(query, opts = {})

sp.searchIndex(url, html, opts = {})

sp.searchQuery(query, opts = {})

Network and peers

sp.netInit(opts = {})

sp.netConnect(peerId)

sp.netSend(peerId, data)

sp.netPeers()

Currently connected peers.

sp.netBroadcast(data)

sp.netLeave()

sp.peerList()

Known peers.

sp.peerPing(peerId)

sp.identity()

This node's address, e.g. SharedProtocol://5221_…

HTTP-style server

sp.(opts) => sp._server.serve(opts)

sp.(method, path, handler) => sp._server.route(method, path, handler)

sp.(fn) => sp._server.use(fn)

sp.(url, opts) => sp._server.fetch(url, opts)

Scheduling, state and sessions

sp.cron(id, interval, fn)

sp.cronList()

sp.cronRemove(id)

sp.lock(path, cb)

sp.stateDelete(key)

sp.getState(key)

sp.sessionStart(sessionId, meta = {})

sp.sessionGet(sessionId)

Logging and helpers

sp.ready()

Resolves when the filesystem, identity and subsystems have started. Await it first.

sp.log(name, entry = {}, opts = {})

sp.logTail(name, cb)

sp.metrics(prefix)

sp.() => sp._ai.message()

sp.(path) => sp._ai.loadSpai(path)

sp.ts(code, opts = {})

sp.hex(path)

sp.now()

Current time, ISO 8601.

Everything else

Namespaces, each an object of functions (sp.git.status() style). The members shown are the ones present in v5.0.0.

NamespaceMembers
sp.aliasall clear mine resolve set subscribe
sp.audioplay record recv recvStop stat stop
sp.benchauto clear report results run suite
sp.bootboot serve stat
sp.callanswer call on reject sessions
sp.codecompile exec run setTimeout
sp.compresscompress compressFile compressStr decompress decompressFile decompressStr ratio
sp.displaydisable enable getContext rgbToYpb ypbToRgb
sp.dockbuild compose images inspect logs ps pull push rm rmi run stop
sp.driverscall install list load remove stat unload
sp.exitPeerbest probe table
sp.gitadd branch branches checkout clone commit diff init log pull push status
sp.irirList protocols replay send
sp.jobdefine dispatch dispatchOne list
sp.maillist onIncoming send stat
sp.mockisActive peers start stop
sp.operationcall capGrant capRevoke clearance kevtEmit kevtOn list memMap memUnmap netns netnsDestroy register sandbox sched schedStop setClearance setUid unregister vserver vserverStop vservers
sp.partitionclearTmp enforce flagsFor list mkpart rmpart stat
sp.peerscount get leave list subscribe
sp.policyallow check deny enforce reset rules
sp.presenceclear destroy get list set setTTL subscribe
sp.proxydestroy on open sessions
sp.ratelimit middleware mutexLog resetLog stats
sp.registrycap clear delete dump get grantCap has list revokeCap set
sp.remoteinit listSites pushConfig resetConfig stat stop
sp.repban get isBanned list pardon penalize reward score tier
sp.reportallow allowed checkPath checkSymlink checkWipe clear denied deny log onViolation stat violations watch wrap
sp.styledefine draw drawn has list photo remove resolve setStyleGlobal stopVideo undraw update video
sp.templateclearPartials compile registerPartial render renderFile
sp.terminalcall disconnect on send
sp.timefromUTC now sync toUTC watch
sp.torrentdownload onAnnounce seed seeds
sp.trafficlist send shape stat unshape
sp.translateactiveLang keys langs load t unload use
sp.tunnelclose list onRecv open recv send serveRoutes
sp.vpnconnect disconnect fetch stat

Other top-level functions not listed above:

abortable accelerometer aiAttach aiStat aidownload aistore aistoreStat ambientLight animate animateAll animationGroup apiCall apiRoute atomicAdd atomicCAS atomicLoad atomicStore audioDecoder audioEncoder auditLog barcodeDetect barcodeFormats battery binList blob blobFromBase64 blobRevoke blobToArrayBuffer blobToBase64 blobToText blobUrl bucket bucketDelete bucketList build buildIndex buildURL bundle bundleList cacheDel cacheGet cacheMatch cachePut canShare captureScreen castDetach castInjectKey castInjectMouse castStart castStop castView catPeer cdfile cdfolder checkPermission clipboardRead clipboardReadImage clipboardWrite clone compressFile cookieDel cookieGet cookieSet cookieWatch copy cronStatus cut dateDiff decompressFile delfileAsync derefOrRun deviceMemory diff disableAudit dragSource dropZone emitLocal emptyTrash enableAudit enableSharedAudit envDel envGet envList envSet eventClear eventReplay exec expose fadesRead fadesWrite finder fsObserve fsOpenDir fsOpenFile fsSaveFile gamepadPoll gamepadWatch gamepads getQuota gpu gpuBuffer gpuCompute grantPermission guiNewfile gyroscope heapFree heapList hidDevices hidOpen hidSend hidWatch hmr hmrStop idleWatch inkPresenter inkRender install invokeServerFunction journalAppend journalCheckpoint journalList journalRead journalWatch keyboardLock keyboardUnlock launchQueue listxattr loadLocalFont loadReact localFonts lockStat logClear logExport logList logQuery longTasksWatch lsPeer lsTrash magnetometer mediaSession memFlush memFlushAll memLock memPreempt memPreemptClear memPreemptWatch memPressure memStat memWatch meshSnapshot meshViz metric metricReset metricResetAll metricSummary midi midiSend midiWatch mkdirAsync motionWatch mount mountList mvAsync navigate navigationBack navigationForward navigationWatch offAll onFileOpen onNavigate onShareTarget open opfsObserve opfsSyncRead opfsSyncWrite orientationWatch paintWorklet paintWorkletUrl parseURL paste permedit pip pipClose pipeClose pipeCreate pipeList pipeRead pipeWrite pointerLock pointerLockWatch pointerUnlock postTask presentationAvailable presentationRequest proximityWatch pubsubList pushState queryPermission queueDrain queuePush queueStatus queueWorker rateLimitCheck rateLimitReset readableStream registerPSTNHandler releaseWakeLock replaceState reportingObserver resolveSymlink resourceTimingClear resourceTimingWatch resourceTimings restore restrict revokePermission rpcTrustPeer rpcTrusted rpcUntrustPeer sab sanitize searchCrawl searchExpire searchPeers serverFunction serverStat serverStop sessionEnd sessionList setQuota shareTargetParams sharedClipboardRead sharedClipboardWatch sharedClipboardWrite sharedConfig sharedConfigGet sharedConfigSet sharedEmit sharedGC sharedLock sharedLockList sharedOff sharedOn sharedOnce snapshotDelete snapshotDiff snapshotList spAllocatemem spFetch spGatewayConnect spGatewayDisconnect spGwFetch spMemedit spServe spStoragesize spVer sparse sparseRead speechRecognize speechSpeak speechVoices ssgHydrate ssgManifest ssgRouter ssgServe ssgWatch stackDepth stackDump stackPeek stackPop stackPush statAsync state stateList storageFetch storagePointer storageWatch streamRecv streamShare streamStop switchToAdmin syncCheckpoint syncDoc syncEdit syncList syncMerge t taskController taskYield threadFades threadKill threadLink threadManager threadMemRead threadMemShare threadMemWrite threadPool threadPoolSend threadSend threadSpawn threadSpawnFile threadSync tip toPlainDate transformStream trustedHTML trustedPolicy trustedScript types unbundle undoList undoPop undoPush unmount usbDevices usbOpen usbTransfer usbWatch useState vibrate vibrateStop videoDecoder videoEncoder viewTransition viewTransitionNamed wakeLock wasiClose wasiFdTable wasiInit wasiOnEof wasiOpen wasiRead wasiReaddir wasiSeek wasiShutdown wasiStat wasiStderr wasiStdin wasiStdout wasiUnlink wasiWrite wasmMem watCache watCompile watExec watchObject weakRef writableStream wtClose wtDatagram wtDcOpen wtInit wtRecv wtSend wtStatus wtSwInit wtWS xrRenderLoop xrSession xrSupported

SPP and the host

SPP connects a host program to SP. The host is sharedprotocol.c, a terminal app that listens for SPP peers (default port 5221), can launch a headless browser, and runs a WebSocket bridge on 127.0.0.1 so a page can call it. It started as the SPTerminal bridge and grew from there.

Wire format (v1.1)

header   26 bytes, little-endian  magic "SPP\x01" | type u16 | payload_len u32 | seq u64 | timestamp_ms u64
payload  payload_len bytes
trailer  CRC32 (4 bytes)
TypeValueMeaning
CONNECT1Open a connection
ACK2Acknowledgement: the frame arrived. Not an error.
DATA3Application data
CLOSE4Close the connection
PING5Keep-alive request
PONG6Keep-alive reply
ERROR9Something went wrong
RPC0x10Call a method on the host
RPC_RESULT0x11The answer to an RPC; a failed call carries its error text here

spp in JavaScript

window.spp (also sp.spp) is live only while the page is connected to the host through the bridge. Otherwise every call rejects with SPP not connected. Check spp.connected.

spp.call(method, params, timeoutMs)            call any host method (the bridge's capabilities apply)
spp.log.tail({n, level, since}) | spp.log.print(n) | spp.log.clear()
spp.browser.status() | restart() | reload()
spp.cron.add(name, schedule, script, caps) | list() | remove(name) | run(name)
spp.config.get(key) | set(key, value)
spp.token.rotate() | status()
spp.send(conn, data)  spp.broadcast(data)
spp.relay.subscribe(topic, fn) | publish(topic, data, {echo}) | topics()
spp.trace.tail({n}) | stats() | clear() | enable(on)

The bridge starts with no capabilities (config.get reports bridge_caps), so calls that need one fail with denied: needs cap … until the host grants it.

spp never exposes filesystem or SPMemory calls; those only go from the host to the page. Members of sp.spp at the top level: broadcast call send.

To connect, start the host with --site-used and it opens the site with the bridge settings in the URL fragment (#spp_port=…&spp_token=…&spp_mention=…). A fragment is never sent to a server. Only the origin you named may use the bridge, and the token is checked on every connection.

sharedprotocol.c

v1.1.0. gcc -O2 -o sharedprotocol sharedprotocol.c -lpthread, Linux. Options:

--port <n>            SPP listen port (default 5221)
--bridge <n>          Bridge WebSocket port
--no-browser          Do not launch a headless browser
--spc <file>          Run a .spc file on the host and exit
--max-peers <n>       Peer table size (needs ulimit -n above n)
--default-caps <mask> Capabilities new peers start with (default 0)
--bridge-origin <o>   Extra web origin allowed to use the bridge
--bridge-token <t>    Fixed bridge token, 16-32 chars [A-Za-z0-9_-]; needed with --no-browser
--chromium-no-sandbox Pass --no-sandbox to Chromium (added automatically as root)
--drivers-dir <dir>   Where SPP drivers are installed (default ./sp_drivers)
--browser-used <b>    chromium (default), chrome, firefox or brave
--site-used <site>    Open this site instead of the built-in page; only it may use the bridge
--verbose  --help

Plain http:// sites work but the host warns you: anything on the path can read the bridge token. Use https.

LocalEnterprise

LE is for organisations that need an audit trail and rules about who may do what. It is not tied to banks, and it is not meant for hospitals. It serves only SPP_RPC, never dials out, and never runs SharedProtocol. The reference below is the same text as LOCALENTERPRISE.md.

LocalEnterprise (LE) 1.0.0

Spin-off of sharedprotocol.c. One C file, Linux only: gcc -O2 -Wall -Wextra -o localenterprise localenterprise.c -lpthread

Kept from SP: the SPP v1.1 epoll engine (128k-peer design), SPP_RPC, the capability byte. Removed: browser + bridge, SPCode, daemons, drivers, cron, relay, trace, SPMemory, JS forwarding.

Quick start

./localenterprise --fse-root /srv/enterprise --state-dir /var/lib/le
localenterprise> rpc server.token.add {"name":"alice","caps":"fsr,fsw","role":"dev"}     # secret shown once
localenterprise> rpc policy.rule.add {"effect":"allow","who":"role:dev","action":"fse.*","resource":"/projects/**"}
curl -H "Authorization: Bearer le_..." http://127.0.0.1:5223/files/projects/readme.txt

Default is deny: with no rules, no token or peer can do anything except identity / auth / own caps. The terminal is the administrator and is never policy-checked. Use --no-terminal to run as a daemon.

Capabilities (one byte, per token / SPP peer)

srv 0x01 routes+settings · kick 0x02 peers · tok 0x04 tokens · exec 0x08 fse.exec (+fsr) · logr 0x10 audit log + metrics · policy 0x20 rules/roles/grant · fsw 0x40 write ops · fsr 0x80 read ops. Caps say which kinds of calls are possible; policy rules say which concrete calls are allowed. Both must pass.

SPPLogE

<state-dir>/audit.log, mode 0600, one JSON line per action, hash-chained (prev, hash = SHA-256). Logged: connection open/handshake/close, every non-ping SPP frame, every RPC (caller, method, redacted params, ok/error, duration), every policy decision, auth ok/fail, token/rule/route/config changes, every HTTP request, FSE operations (as RPC / http entries), start/stop. Params with token/secret/pass/key/content/data/auth/cookie/cred keys are replaced with ***; file contents are never logged. Rotation at --log-max-mb keeps the chain across files. If the log cannot be written, all non-terminal calls are denied (fail-closed; --log-fail-open to disable) and /health returns 503. Verify: rpc log.verify, terminal logverify, or offline localenterprise --verify-log f [--expect-head <hash>]. Editing, deleting or reordering lines is detected. Truncating the END is only detected against a head hash you saved elsewhere (loghead / rpc log.head).

SPPPolicyE

Rule = effect · who · action · resource · hours · days. who: *, kind:peer|http|script, name:, role:, mention:, ip:a.b.c.d/n, conn:N joined with &. action globs over rpc.<method>, fse.<op>, http.<METHOD>; resource globs over the FSE or HTTP path (* = one segment, = anything, /dir/ also covers /dir). Deny overrides allow; no match = --policy-default (deny). hours like 09:00-18:00 (wraps midnight), days like mon-fri. Modes: enforce / audit (log would-be denials, allow). policy.set {"lockdown":true} denies all non-terminal calls. Roles per connection: policy.role.set. policy.eval simulates a decision. Rules persist in policy.db.

FSE (jailed to --fse-root)

fse.stat ls read hash · write touch mkdir rm mv cp chmod · exec · info. Paths are walked with openat(O_NOFOLLOW): no symlink is ever followed, .. is rejected, no existence is revealed before the policy check passes. The FSE root must not contain (or be inside) the state/log directory. Reads ≤ 32 KB and writes ≤ 48 KB per SPP call (use offset / append / patch; HTTP streams whole files). chmod refuses setuid/setgid/sticky. fse.exec is OFF unless --fse-exec: runs a regular, executable file from the jail via fexecve with a clean env, cwd = root, no stdin, merged output capped at 32 KB, timeout (default 10 s, max 60 s), rlimits (CPU, memory, file size, fds), no_new_privs, own process group killed at the end, max 8 at once. It is NOT a sandbox: the program runs as the LE user and can touch anything that user can. Run LE as an unprivileged user.

SPPServer (HTTP/1.1, default 127.0.0.1:5223, no TLS: put a TLS proxy in front)

Pipeline: request id → conn/IP limits → rate limit → CORS → Bearer auth → route → policy → handler → audit log. Built in: GET /health (public) · GET /metrics (logr) · POST /rpc {"method","params"} · GET|HEAD|PUT|DELETE /files/<path> (Range, directory listing with a trailing /, ?mode=append|create, ?parents=1, ?recursive=1). User routes: server.route.add {method,pattern,type:text|json|file|rpc|spce,target,public?,status?,content_type?}; patterns support :param and a trailing /*; file routes can mount a directory. Non-public routes need a token and pass policy as http.<METHOD>. server.config {rate,max_body,cors}. Request smuggling guards: chunked bodies, duplicate Content-Length, obsolete folding, oversized headers are rejected.

SPP

Same framing as SP (26-byte header, CRC32). Only SPP_RPC is served. auth.login {token} gives the connection the token's caps/name/role (five failures drop it); revoking or expiring a token cuts live sessions.

SPCodeE (.spce scripts, v1.1)

A small language for rules and workflows. A script can only reach three things: RPC (every fse.* call included), SPPServer (server.respond, the server.* RPCs) and the audit log. Scripts live in <state>/spce/<name>.spce (0600, loaded at start). Manage them with spce.load {name,source,enable?} · spce.source · spce.list · spce.enable {name,enabled} · spce.remove (need the policy cap) and spce.run {name,workflow?,args?} (policy action spce.run, resource name/workflow). Names: lowercase letters, digits, - _, up to 34. Source up to 256 KB.

caps fsr, fsw                      # what the script may ask for: fsr fsw exec srv logr (never policy, tok, kick)
rule big_write on "fse.write" when len(rpc.params.content) > 1000 do
  log "large write", rpc.params.path, "by", rpc.caller.name
  deny "too large"                 # refuses the call that fired the rule
end
workflow main do
  let data = fse.read({path: "/report.json"})      # same as rpc("fse.read", {...})
  let doc = parse(data.data)
  if doc.total > 100 do
    server.respond(200, {big: true})               # only inside an HTTP route
  end
  return doc.total
end

Values: null, true/false, numbers, strings, lists, maps (lists and maps are shared by reference). Statements: let set x = / x.f = / x[i] = if … do … else … end for x in list|map do … end while … do … end log a, b deny msg (rules only) return. Operators: + - * / %, == != < <= > >=, and or not. Comparing </> across types is an error (rule errors fail closed: the call that fired the rule is refused), so test with has(m, "k") or type(x) first. Builtins: len str num type keys has contains starts ends upper lower trim substr split join replace push range json parse abs floor round min max now date iso hash · rpc(method, params) (aborts the run on failure) · try_rpc (returns {ok, result|error}) · run(workflow, args) · server.respond(status, body[, content_type]). Any RPC method also works as a.b({params}). Scripts cannot call spce.* or auth.*.

Run a script directly. No server needed:

localenterprise --spce-run report.spce [workflow] [--spce-args '{"n":3}']   # runs once, prints the result, exits (0 ok, 1 error)
localenterprise --spce-check report.spce                                     # compile only: caps, rules, workflows
localenterprise> spce run report.spce [workflow] [json-args]                 # same, from the running terminal
localenterprise> spce check report.spce

The workflow defaults to main; the script's name is the file name (lowercased, .spce removed). The file is run once and not installed, saved or enabled, so its rules do not become active (use spce.load for that). Nothing else changes: it acts as spce:<name> with its declared caps, policy decides each call it makes (default deny, so give name:spce:<name> a rule or start with --policy-default allow for a test), rules of already-installed scripts still guard its calls, and spce.load (source run, with the SHA-256 and path), spce.run.start|end and every RPC it makes go to the audit log. --spce-run opens no ports and uses the same --state-dir, --fse-root and --log-file options as a normal start.

Rules fire before the RPC they match runs (SPP, HTTP /rpc and HTTP /files, which looks like fse.read|write|rm with path, mode, size, content); never for the terminal. Variables: rpc.method, rpc.params, rpc.caller{kind,name,role,ip}. Rules fired by an SPP peer run on the network thread, so they get 100 ms, 20000 steps and 5 RPC calls and cannot use fse.exec / fse.cp. Workflows get args and caller. HTTP routes: server.route.add {type:"spce",target:"script/workflow"}; the workflow gets req{method,path,query,body,json,caller}. No server.respond and a return value → 200 JSON; no value → 204.

Identity and policy: a script acts as principal spce:<name> (kind script, role script) with the caps it declared. Caps AND policy must both allow every call (default deny: add rules for name:spce:<name>). A loader cannot give a script caps it does not hold. Forced logging: every RPC a script makes is an rpc event under its principal, plus spce.load (source SHA-256), spce.run.start|end, spce.rule, spce.log (secrets redacted), spce.respond, spce.kill, spce.enable, spce.remove. A script cannot switch this off; it cannot act while the audit log is failing. Limits per run: 200000 steps, 5 s, 100 RPC calls, 16 MB, workflow depth 8, 500 log lines. The kill rule: a rule that fires because of a script's own action is an *automatic* run. The 5th automatic run of the same script in an unbroken chain (no outside request or manual run in between) is refused and the script is stopped (disabled; stays disabled across restarts until spce.enable). The request that started the chain is refused too. Manual runs and separate outside requests never count. --spce-no-limit removes only this kill; the chain depth cap (16) and all per-run limits stay, and the startup event records that the limit is off.