Files
core/.trellis/spec/backend/toolchain-and-library.md

112 KiB
Raw Permalink Blame History

Toolchain And Official Library Contracts

1. Scope / Trigger

Application deployment targets belong to toolchain::BuildTarget, independently of the compiler host. Public build --target linux-aarch64 may run on Linux x86_64; omitted targets and run/test stay native. Propagate the selected target through Lib preparation, CompileRequest, runtime pack selection, signature closure verification and both caches. Verify ELF machine/type for archive members and ordinary objects; a matching manifest label/hash alone does not prove architecture. A warm shared cache must still validate the selected target pack. Do not globally replace platform_identity or require an ARM compiler core for cross builds.

Target runtime/interpreter/extension/exec/process-runtime assets must match the deployment target. Go build tools explicitly declare build.host, while Go output and stdlib headers match build.goos/goarch and version. Their managed process uses host assets; emitted Workers use target assets. Product processes clear non-allowlisted environments; author-only cross linker settings or Go overlays must not become application configuration/environment knobs. Python sdist/npm hook execution requires a matching execution environment or a previously prepared complete target receipt; never relabel host native output.

Executable modes are also part of the cross-target resource contract. Process runtime packaging and application embedding share asset_executable; classify both supported target loaders independently of the author's host, while retaining target ELF validation. Regressions must check actual packaged modes from non-executable source inputs and execute the embedded Worker. Host-only loader assertions and successful linking cannot establish target bootstrap behavior.

Applies to formatter/CLI, reference execution, native ownership and clause optimization, concurrent sequence actions and official source packages. JSON algorithms belong to .dever; HTTP reuses Hyper in the runtime, with source-owned public types and static business handlers. intrinsic.rs remains the exhaustive bridge for checker, native emission and reference evaluation.

The compiler author workspace requires Rust 1.95 or newer. SQLite is pinned to deadpool-sqlite 0.14.0 and its locked bundled SQLite dependency chain, which removes the observed WAL-close/replacement-open VFS lock inversion. Do not lower this requirement by reverting to the defective 3.51.1 engine, changing global toolchains or mutating Cargo registry sources. Initial developer dependency preparation may fetch explicitly; product run/build still consume prepared artifacts offline. See database-guidelines §9 for the root/connection lifecycle and regression evidence.

Compiler bridge exception (explicitly authorized 2026-09-30): workspace Rust remains unsafe_code = forbid. Only dever-backend-bridge may override this with deny, and only its private ffi.rs may allow necessary foreign calls, runtime C exports and their raw-memory operations. The rest of that crate, its build script, core, runtime, CLI and tests remain safe Rust; no public unsafe Rust API escapes the private boundary. Each foreign call and output transfer documents pointer lifetime, buffer length, allocation ownership and serialized LLD state. This is not a Dever-language FFI feature. LLVM/LLD object/link tests do not establish complete HIR semantic equivalence or a shipped runtime pack.

Keep embedded (LLVM/LLD compiler bridge) and runtime-abi (application staticlib) independently buildable. Runtime-only builds never link the LLVM/C++ SDK. Versioned signatures belong to include/runtime.h: fixed-width scalars/status, explicit output pointers, borrowed slices and matching owner releases. Decimal uses explicit little-endian low/high u64 words, not aggregate-by-value or Rust layout. Numeric success leaves Buffer null/0; errors preserve the original diagnostic and use only dever_rt_v1_buffer_free; compiler Reply has its separate C++ allocator. Reuse existing runtime numeric/collection/resource/protocol/system implementations. Application slices include CMD/wire/Dever/external Adapter, Model/SQL/transactions, HTTP/REST/auth/tenant/permission/Cookie/Upload/log and Job/Test. runtime-api adds owned application resources independently of embedded; runtime-sqlite and runtime-postgres select real drivers; runtime-external adds verified Worker resources. Private and managed Linux compilation use LLVM; formal six-target packs remain unfinished.

Each task root owns a component Session and its prepared bundle, propagated into child Tasks, blocking work and API requests. Copy external metadata into owned strings/vectors; never leak C name arrays or reset a process-global registry between entries. Register a Worker before awaiting startup and attach its supervisor to the root Scope. Explicit shutdown can be followed by a new start; terminal close permanently rejects admission. Retain task ownership while awaiting shutdown so cancellation can resume cleanup. Close Workers before cancelling/draining descendants, then close databases and other application owners in the same runtime. Generated typed roots use run_entry_with_typed_resource_cleanup to append resource failure to an existing typed fault; the original Rust backend preserves its explicit shutdown/error-cause path.

Private task constructors without suspension remain ordinary functions. Scope adapters should directly return the existing Tokio scoped future when no additional await is needed. An extra async wrapper can store both its input future and the child future, multiplying debug-build stack usage through nested callers; do not compensate by increasing thread stacks or boxing individual test phases.

Private dever run/build/test uses checked HIR → LLVM → object → in-process LLD, without Rust/Cargo/cc lookup or fallback. Keep LLVM calls binary-private; shared toolchain/runtime_pack validates compiler-relative runtime/<platform>/manifest.json, normalized paths, version/v1 ABI/target, four profiles and exact CRT/archive digests. Shared code must not reference bridge target methods: actual linkage pulls LLVM into launcher/daemon even when the call appears to be metadata only. Reject symlinks, scripts, thin archives and incomplete references; snapshot/recheck selected inputs before linking. Private compilation reuses native::compile_artifact; managed compilation requires authenticated daemon IPC and never falls back. Ephemeral signed Linux fixtures do not establish trimmed or formal six-target release assets.

Native authoring uses the independent four-profile runtime-pack build; the old all-features debug archive remains a test fixture only. Signing prepared inputs and compiling source are separate operations. Do not move Cargo/tool discovery into the maker or application run/build.

Linux first installation reuses the release signature and machine version owner. Author bootstrap inputs provide launcher/daemon and their own complete private ELF library closure. The independently authenticated installer reads only its absolute root-owned config/setting.json; its public key must be supplied outside the downloaded release, then pinned atomically without key replacement. A bounded journal may name only the five fixed bootstrap destinations: launcher/daemon bin, system service, command entry, enable link and active version. Persist final file modes and child directories before publication; recover uncommitted changes, but never roll back a committed publication because cleanup failed. Stop a newly started service before removing its unit; restore previous service state after restoring files. Offline image installation never invokes systemctl. Incoming packages must match the supported service template; existing signed versions retain their original template and remain usable by pinned projects. Actual global activation and public release require separate operational authorization and evidence.

Process main is separate from callable roots. Initialize Unix SIGPIPE policy before application threads, preserving stdout EPIPE as the existing located runtime error. Do not change an embedding host's signals from callable roots. Reuse typed fault render, indexed Test fault size/render/release, output cleanup and logger flush; Test main accepts exactly one nonempty unsigned decimal index below case count. Verify actual env-cleared CLI execution, relocated embedded Worker, selected-pack tampering on cache hits, broken stdout, and launcher/daemon dynamic dependencies. Six-target objects do not establish cross-platform execution.

2. Signatures

  • First installation: root install is the sole installer source and supports bash install and curl -fsSL https://git.dever.cc/shemic/dever/raw/branch/main/install | bash. Its Bash entry forwards --version, --release, --trusted-key, --system-root, and --no-start to its embedded Python implementation. Maintain this file directly; skills provide guidance, not another installer, and there is no generation step.

  • Project creation: dever new <new-directory> [--markdown]; project::create(&Path, bool) consumes the single template source under the ordinary skills/assets/template directory in the same repository revision. The machine launcher selects the active core without reading nonexistent target configuration.

  • AI guidance: dever skill path [project-root] resolves and verifies the active or project-pinned release's skills/dever-language. dever skill install takes no arguments: from a project root, select its compiler version and merge that signed skill's assets/template/AGENTS.md into the project's AGENTS.md. Reuse the same template as dever new; do not copy a full skill or create a second binding command. Create a missing file, append a missing managed block, or replace one complete <!-- dever-language:start --> / <!-- dever-language:end --> block while preserving all other content. Repeated installs are idempotent. Reject a non-project directory, symbolic links, nonregular/invalid UTF-8 AGENTS, malformed/duplicate markers and missing signed templates before mutation; publish through an owned atomic staging file. The old skill-directory argument is removed without an alias. Skill resolution is a public read-only operation and must not open the root-only install lock; machine installation/update does not scan or rewrite user projects.

  • Application target: dever build <root> --output <new-file> [--target linux-x86_64|linux-aarch64]; explicit dependency preparation accepts the same target on dever lib add/install/update/doctor. Omission selects BuildTarget::host(). CompileRequest.target: BuildTarget is required and serialized canonically; test requests must use the host.

  • Private author entry: native-release <author-root> --output <new-dir> calls toolchain::packaging::create(&Path, &Path) -> Result<ReleaseManifest, String>. It reads only <author-root>/config/setting.json; this is not an application configuration section or another public dever command.

  • Runtime ABI examples: uint32_t dever_rt_v1_int_add(int64_t left, int64_t right, int64_t *out, DeverRtBuffer *buffer) and void dever_rt_v1_buffer_free(uint8_t *ptr, uint64_t len). Buffer is {uint8_t *ptr; uint64_t len;}; Decimal output is {uint64_t low; uint64_t high;} and input words are separate scalar parameters. Full declarations live in the canonical C header, not independently handwritten per consumer.

  • Managed ABI: Text/Bytes/List/Map use opaque owner pointers and paired retain/release; Id shares Text representation. A process-static immutable DeverRtType holds size/align and clone/drop/equal/hash callbacks for the actual compiled type. _take consumes the non-null receiver on success, value error or invalid output; other inputs are borrowed. List/Map cursors consume their receiver and release unvisited rows on early release. Optional output uses a separate u8 presence flag, and the value slot holds the complete element/value type, including its own Nullable flag when applicable.

  • Application wire ABI uses the same process-static DeverRtType and synchronous typed encode/decode callbacks. Borrowed runtime wire Nodes and CMD Inputs never escape a callback or survive suspension. Validate aligned writable slots before parsing, consuming a field, selecting an Adapter or calling user callbacks. A successful decode initializes a complete typed row; if subsequent CMD Inputs.finish() or error-buffer validation fails, drop that row once. Partial failed rows remain the compiled callback's guarded responsibility. Keep CMD top-level Inputs policy distinct from nested checked wire parsing; required/unknown field wording and field-error precedence must match the Rust backend. Runtime wire feature supplies these owners without enabling a second protocol engine or LLVM SDK.

  • Adapter settings ABI reuses Settings::load_adapter_settings, name validation and selection. Runtime owns only the temporary opaque config handle; generated concrete Setting slots retain decoded fields after that handle is released. Decode errors never render Secret content. Scope drain precedes typed Setting release and the module-local entry gate reset; repeated success, partial init failure and child Task execution must preserve allocation balance.

  • API ABI: dever_rt_v1_api_serve(session, routes, count, tenant_components, component_count, error) -> DeverRtAsyncOp*; process-static DeverRtApiRoute references concrete callable/input/failure/auth/permission metadata. Claims pack borrows subject/session/optional tenant/site Text handles and initializes one concrete input row. Identity unpack borrows the returned concrete row, retains one id Text, and writes separate i64/u8 user/tenant value/presence slots. Release both unpacked id and the original output once. Runtime dispatches checked callbacks; source App is never looked up by string or called through dynamic business Value.

  • Resource ABI: File retain/release shares the runtime File; open/create/read/write/close/chunks borrow inputs, and create uses create_new. File read has an independent presence byte. DeverRtReadEvent supplies a concrete descriptor and Chunk/Failed callbacks, retaining borrowed Bytes/Text into the full original Choice. Stream retain/close/pull shares the runtime cursor; internal pull has typed row/presence outputs, emits a terminal Failed once and then End, and validates writable outputs before advancing the cursor or doing I/O.

  • Async owned ABI: DeverRtOwnedType {size, align, move_init, drop, transferable} has process-static callbacks; move initializes matching aligned storage and deinitializes the source owner. DeverRtAsyncFunction carries output/fault descriptors and create/resume/destroy/done/send_safe; create clones borrowed input before initial suspend. DeverRtSyncFunction carries input/output/fault descriptors and invoke/send_safe; invoke borrows runtime-owned input, returns 0 initializing output or 1 initializing fault, and never drops the input itself. Internal Unit rows are transferable, and internal Outputs rows derive transferability from fields; the source type properties are unchanged.

  • Async polling ABI: dever_rt_v1_async_root(function, input, output, fault, error) -> u32 starts one task Scope; dever_rt_v1_async_op_poll(state, operation, output, present, fault, error) -> u32 polls under only the current Context; async_op_release cancels/drops one operation. Statuses are Pending=0, ReadyOK=1, ReadyTypedFault=2, RuntimeError=3, InvalidInput=4, distinct from regular ABI 0/1/2 and kernel 0/1. Pending initializes no result, presence or fault. Ready moves only the appropriate typed owner; numeric faults and owned RuntimeAbi buffers remain typed faults, not business failures. Initial/pending/final coroutine destruction uses paired frame_alloc/free and does not retain poll Context.

  • Async concurrency ABI: task/group run accepts checked async descriptors or checked sync descriptors routed through the bounded blocking pool. Task/Group retain clones a wrapper owner, not the affine task/group; wait/stop consumes one wrapper and takes its inner value once. Group run and Channel operations borrow handles. Successful non-null blocking/parallel/sync-run/send operation creation consumes its typed input even if later pending, failed or cancelled; null leaves the input caller-owned. Channel receive's separate presence flag distinguishes End from Some(null) before language-level flattening. SendForeignFuture is constructed only after checked transitive frame/output/fault transferability; local root/call polling never gains Send by blanket unsafe implementation.

  • AsyncStream/TCP ABI: constructors borrow source handles and return a shared opaque producer. Rows use concrete managed clone or OwnedType move callbacks, never padding copies; separate presence distinguishes End from a nullable row. A consumption scope closes aliases on drop. Socket/Listener retain/release preserves runtime identity; async operations clone borrowed handles into their operation owner. TCP standard choices retain original value errors. Timeout returns a complete Task row plus presence, race validates matching canonical output descriptors before consuming its task wrappers, and both reuse structured runtime drain. ParallelFunction packs an element/context into one checked input row for the existing runtime dispatch owner, validating frame/input/output/fault transferability.

  • List::into_values() consumes unique elements and lazily clones shared elements. Emit consuming loops only for ordinary movable values; resource-containing lists retain lexical ownership.

  • List::into_first(), Map::into_get() and Map::into_entries() transfer uniquely owned values and clone only through a live alias. Bytes::from_string()/into_text() transfer compatible Text/Bytes storage.

  • Render::render_to(&mut String) recursively appends composite values into one caller-owned buffer; render() remains the allocating convenience boundary.

  • concurrent::each_slice(&[T], workers, apply) batches memory sequences; each(iterator, workers, apply) retains producer-owned Stream pulls. Both share cancellation/join logic.

  • dever.http.serve(handler, Listener, Limits) -> () owns bounded HTTP/1 or HTTP/2 connections; send(address, port, Request, Limits) -> Response owns a single request and driver without a client pool. result(send(...)) captures ResponseResult. Handler suspension is inferred. Limits.http2: Http2Limits? selects HTTP/2 explicitly; null selects HTTP/1.

  • http.serve_live(handler(Request, HttpReply) -> (), Listener, Limits, LiveLimits) owns streaming/SSE/WebSocket handlers. respond/start/write/finish share checked headers and a one-slot body channel. SSE Event has Text event/data and nullable Text id/Int retry_ms. WebSocket accept/connect/send/receive/messages/close reuse tokio-tungstenite; public source owns records/results/Message.

  • http.client(origin, ClientTls, Limits, PoolLimits) -> HttpClient creates a fixed-origin shared resource in the caller's task scope. request -> Response buffers; open and open_stream return StreamResponse with AsyncStream<dever.io.ReadEvent>. StreamRequest uses the same stream body. close_client -> () closes aliases and drains its driver. Result choices describe explicit captures, not ordinary output signatures.

  • tls.system/client/server own public roots, explicit custom CA and server PEM configuration. http.serve_tls/serve_live_tls and websocket.open(ws/wss URL, ClientTls, Limits) reuse the same verified TCP/TLS transport. All four system http_serve intrinsics accept an optional final transferable Context, appended to the static handler signature.

  • native::compile_with_cache(..., cache_directory) -> NativeProgram; cache_hit() reports reuse. This explicit development/test path uses the workspace target/native-artifacts; a released dever must request the protected machine deverd service and must not expose that directory as a fallback.

  • native::compile_test_suite(&Program, &SourceMap, rustc) -> NativeProgram; every suite entry must come from successful checking and remains private. The suite selects one stable checked case index per process.

  • toolchain::artifact_put(&Layout, &[u8]) -> ArtifactReceipt and artifact_get(&Layout, sha256, bytes) -> Vec<u8> use authenticated daemon IPC. artifact_get_optional reports genuine absence as None and retains corruption/permission/IPC errors; never string-match errors or convert every failure into a download. Receipts carry lowercase 64-hex SHA-256 and exact length, not a client-selected path. CacheStore::summary() returns metadata only with verified:false; administrator status() verifies bytes and returns verified:true.

  • toolchain::compile(&Layout, &CompileRequest) -> Result<Vec<u8>, String> submits canonical JSON {version, kind, target, sources, bindings, resources}. Sources are logical path/test origin/text; bindings contain only database names/drivers, provider verify names and site paths/auth keys. Resources are normalized paths, base64 bytes, digests and executable flags. No project root, secret Settings, IR, output path or client cache key is accepted. SourceMap::from_compilation_sources forces strict layout and compiler-owned standard sources; check_with_bindings and validate_database_bindings share the ordinary configuration rules.

  • format::format(&SourceFile) -> Result<String, Vec<Diagnostic>>; dever fmt <project-root> [--check] prepares both module/ and optional test/ before committing either source set.

  • SourceMap::load(root) accepts .dever and .dever.md; plain .md is not program source. It derives package identity from the relative filename, and both source formats use the same parse/check/api/run/build contracts.

  • SourceMap::load_project(module_root, test_root) preserves separate display/logical paths and assigns Test origin internally. A missing test root is empty; an existing non-directory or unreadable root is an explicit load error.

  • dever test <root> [--filter <component[.domain[.case]]>] [--timeout-ms <positive-ms>] checks all sources and compiles one complete indexed suite. Filter matches complete dot-separated identity or a segment prefix, never a substring/glob. Preserve slash-separated report names and original indices. Default case deadline is 60000 ms, starting at process launch, not compilation; unselected cases count as not run and no match is a command error. Linux runner uses an owned process group, NOWAIT leader observation and temporary subreaper ownership: terminate the group before releasing the leader PID, then reap only that group and restore prior state. File output capture avoids pipe backpressure/descendant EOF hangs. Timeout fails that case and later selected cases continue; production config and real Lib remain outside ordinary Test graphs.

  • Static API declarations are generated into the async application entry; application source does not call dever.api.serve(). Runtime api::Inputs binds GET/DELETE query parameters, POST/PUT JSON objects or a statically selected POST multipart shape, and runtime response helpers build the fixed JSON envelope. config/setting.json alone supplies HTTP, site/auth and upload limits; application config never uses environment variables.

  • Optional feature reference: reference::evaluate(&Program, entry) -> Result<Evaluation, String>, with captured stdout and structured source-span fault. No interpreter production CLI path.

  • parallel_each(handler, List|Bytes|Stream, workers[, context]) -> (); zero-output synchronous handler, 1–256 workers, no recursively nested Stream in worker input/context. In async code the handler must be a named function with no transitive concurrency effect.

  • Synchronous and asynchronous parallel dispatch use typed failure paths. Generated handlers keep AppError and business-error identity across worker boundaries; String-only runtime helpers delegate to the same generic implementation and are not a compiler fallback.

  • List/Bytes accept both non-suspending and inferred-suspending handlers. Sequential collection operations await internally when required; suspending parallel_each reuses the AsyncStream Group path with capacity 1–65536 and the global task cap. Synchronous Stream remains synchronous.

  • AsyncStream<T> shares one Send producer/cursor and close signal. Traversal accepts effect-checked handlers and infers suspension; stream parallel_each requires a zero-output handler and a Group limit of 1–65536. Both AsyncStream<T> and Channel<T> require transferable T in every declaration position.

  • TCP connect/listen/accept/read/write infer suspension; metadata, close and stream construction do not suspend. net.chunks returns AsyncStream; file chunks return Stream. Explicit captures use their respective ReadStreamResult choices. No synchronous TCP backend or compatibility aliases.

  • run/wait/stop, bounded Group and bounded Channel are structured under one task-local Scope. Direct calls complete sequentially; run is the only call-level explicit concurrency operation and accepts both suspending and non-suspending static calls. receive(Channel<T>) -> T?.

  • Source code cannot start a runtime. A fully non-suspending entry executes directly; an inferred-suspending entry starts the single bounded runtime. timeout(Task, millis, zero-input fallback) and race(Task, Task, ...) consume affine tasks with identical output signatures. stream(Channel|List|Bytes) and task.ticks(millis) are pull-driven AsyncStreams.

  • text.at(Text, Int) -> Text?, slice(Text, start, end) -> Text?, codepoint(Text) -> Int?, from_codepoint(Int) -> Text?; positions count Unicode scalars, slice is half-open. Empty-separator split yields scalars without synthetic empty edges.

  • int.parse, decimal.parse, float.parse return nullable values. Decimal remains finite/exact at parse; Float supports its rendered IEEE special spellings. to_text uses runtime rendering.

  • dever.process.arguments -> List<Text> excludes argv[0] and rejects non-UTF-8 arguments. There is no application environment-reading capability. Application and benchmark configuration uses config/setting.json only.

  • dever.time owns UTC now, strict DateTime/Date/Time parse/format, millisecond Duration construction and checked DateTime add/subtract/difference. Deterministic operations are pure; now has a time effect. Result choices expose Read(value)/Failed(message). Existing Int clocks and zero-output sleep remain. Chrono 0.4.45 (std only) validates calendars without a local timezone dependency. dever.net.connect_timeout(address, port, milliseconds) requires a numeric IP and positive timeout.

  • JSON: dever.json.parse(Text) -> dever.json.value.Document, stringify(Document) -> Text; ParseResult/WriteResult apply to explicit result captures. node/property/element access returns nullable values or node IDs.

  • HTTP: source-defined Header/Request/Response/Limits. Headers are a List of Text names and Bytes values; preserve duplicate values. Bodies are bounded Bytes. Incoming names normalize to lowercase; no promise of ordering across distinct names.

3. Contracts

Developer onboarding uses one official source repository, ssh://git@git.dever.cc:2222/shemic/dever.git. Its ordinary skills/ directory is committed and versioned with the compiler, without a submodule or separate skill repository; it distinguishes this language from Go Dever. Author skill is a required list of {source,path,sha256} entries published as signed skills/dever-language/<path> artifacts, including SKILL.md; at most 256 files, 1 MiB each and 8 MiB total. New-project source bytes come from the same skill templates; Markdown documentation wraps them without a second semantic copy. Keep the generated configuration CMD-only and free of database/auth prerequisites.

Official install, update and extension preparation resolve https://git.dever.cc/api/v1/repos/shemic/dever/releases/latest or /tags/v<major.minor.patch> anonymously. Neither project setting.json nor environment variables choose that origin. Resolve once per operation; the selected stable tag must match the signed manifest even for latest. Metadata is bounded to 2 MiB and 1–512 unique attachments with positive bounded sizes. Download the exact attachment name through its validated browser_download_url, enforcing the declared length and HTTPS same-origin redirects. Reject draft/prerelease, malformed tags, duplicate names, missing assets, foreign URLs, truncation and tag/signature mismatch before publication. dever-release-v2 binds base artifacts and optional extensions in one signature. Each release publishes dever-<platform>.manifest.json, .manifest.sig, .tar.zst, plus .ext-<kind>-<target>.tar.zst. Kind is runtime-pip/npm/go, build-pip/npm, or target; target holds nonhost native runtime/CRT and process runtime libraries. Validate closed IDs, path namespaces, duplicate/overlapping paths, digests and size/count limits in the shared catalog owner. Base retains all four host database profiles, compiler closure, bootstrap, host process runtime libraries and skill. Extensions cannot override base files. Do not fabricate an unsigned merged manifest.

Authenticate the catalog before extraction. Zstandard is a single checksummed frame with window_log_max=27; verify complete compressed EOF/trailer and bounded expansion even after TAR EOF. USTAR contains only its signed ordinary artifact files, with no duplicate, escaping or extra entries; require complete terminator/padding and reject trailing content. Redirects remain on fixed official HTTPS hosts. Publication never replaces another writer's directory. First-install raw .blob-<sha256> assets include the launcher and every bootstrap/lib dependency, independently digest-checked before execution. The launcher owns extraction; Python must not implement a second TAR/Zstd parser or require system zstd.

Shared extensions live in service-writable cache/extensions/<version>/<catalog-sha>/<id>, outside native cache eviction and immutable core directories. IPC accepts only version and typed ID for an already authenticated installed catalog, never caller URLs/paths/keys. Prepare under the persistent install lock in private staging, verify complete bytes then publish readonly with NOREPLACE; corrupted reuse is an error. SignedResources owns verified read/list/root selection for Lib, daemon runtime verification and the actual compile worker. dever target add linux-aarch64 and explicit dependency preparation may ensure resources; ordinary run/build/read cannot. Update prepares precisely the old active version's installed extension selection before switching the one core/skill active journal; any failure preserves the old selection. Stable launcher/daemon protocol changes require matching trusted bootstrap provisioning. Do not rewrite users' skill directories or add an independently switched skill pointer.

Client Lib reads select immutable base artifacts locally and obtain extension bytes through the authenticated daemon; they never probe or mount its private cache. Resource requests bind the installed version, signed catalog digest, typed extension ID and exact signed byte receipt, not filesystem paths or URLs. The daemon verifies the declared local resource and the client verifies the response receipt and payload digest. Catalog-only enumeration must be followed by a verified read of every consumed artifact; daemon compilation keeps full local pack validation. Reading never installs a missing extension or falls back to another source.

The root first-install script embeds its independently provisioned public key, verifies the full package before executing bootstrap, and generates only an owned temporary installer config. Its Bash entry passes the embedded Python source through a quoted heredoc to /usr/bin/python3 -I -; parse the complete function before invoking it. Non-root installation uses /usr/bin/sudo; help must neither elevate nor download. Missing Python 3.9/OpenSSL, unsupported OS/ABI, unavailable package or invalid signature is an explicit failure. Current x86_64 host packages require glibc 2.39; ARM application support does not establish an ARM compiler-host release. The installer never reads business configuration. Real-root installation explicitly starts the machine service unless --no-start is selected; image-root verification must not touch host services. Python/OpenSSL are installer prerequisites, not application runtime dependencies. sdk/release-assets.py uses an explicitly supplied author zstd executable and publishes deterministic base/extension/raw assets with Linux NOREPLACE directory rename; it cannot clean another writer's public output.

The root script is served at /shemic/dever/raw/branch/main/install; Release metadata and attachments must also allow anonymous HTTPS reads. Redirects are restricted to HTTPS git.dever.cc with no credentials, non-443 port or fragment. Complete all assets before publishing a release. Source pushes and local transport tests do not prove public download readiness. Changing the download protocol requires rebuilding the stable launcher/daemon and provisioning them once through the new installer; ordinary update activates version payloads but does not replace that bootstrap pair. Never relabel old binaries as a new release. Focused Rust/Python tests assert latest/exact selection, signature and length rejection, missing attachments and preservation of active versions. Correct: reuse one resolved release snapshot for the base and installed extensions. Wrong: reopen latest between those downloads or guess an attachment path from its name.

Native author settings use dever-native-release-input-v1: version/target/signing_key, core and core_libraries inputs, required base/sqlite/postgres/both archive inputs, and ordered start/libraries/end. Input source is a normalized author-relative path and sha256 is the exact lowercase digest; link inputs also specify the destination path. Core libraries use plain SONAME filenames and publish below lib/; runtime link inputs remain runtime-relative. Reuse the runtime v1 manifest types and validator. Copy into exclusively owned private staging, verify both source and copied digest, sort manifest artifacts, and sign those exact bytes with the supplied owner-private Ed25519 PKCS#8 key. Reject key content as payload, symlinks, path escape and reserved/duplicate destinations. Keep source paths, key material and timestamps out of release metadata. Linux publication uses atomic NOREPLACE; failures clean only owned staging. No tool invocation, environment configuration, downloads, input hard links or implicit trust-key installation belongs to this owner.

toolchain::core_libraries validates the same complete ELF closure during authoring and verification of signed native releases (identified by the signed native runtime manifest). Require matching GNU target/class/endian, exact SONAMEs and core DT_RPATH=$ORIGIN/lib, with no core RUNPATH. Libraries may resolve only their own private directory; every non-OS dependency must be declared and every supplied library used. Reject loader audit/filter hooks, host /etc/ld.so.preload, unsigned flat leaves, symlinks and subdirectories including glibc-hwcaps. The installed directory must exactly match the signed regular files. GNU libc-family/loader are the explicitly declared OS ABI exception; LLVM and its transitive non-OS dependencies are not host prerequisites. Generic signed payload fixtures without a native manifest do not become compilable releases. Verify a real signed compiler can check/build in an owned root containing only declared OS ABI libraries, then run the output after deleting its source.

Build archives with the root runtime-pack profile, one shared Cargo target, and independent features: runtime-api/runtime-external for every profile, then runtime-sqlite/runtime-postgres for the selected drivers. Never enable embedded or strip linkable symbols. Deterministic packaging of fixed inputs does not establish cross-host reproducible source builds. Assert actual driver separation and run the produced programs; a file named base.a is not evidence of trimming.

Runtime ABI status is u32: 0 success, 1 original runtime value error, 2 invalid ABI input. Output slots must be live, writable, aligned and disjoint; borrowed inputs stay live and immutable for the whole call. Null input is valid only at zero length; reject lengths outside usize/isize range before constructing a slice. Caller releases any previous Buffer allocation before reuse, and releases each returned non-null allocation once through the matching runtime ABI. Error paths do not initialize numeric output. These are compiler-owned internal interfaces, not a language-level unsafe capability; application configuration gains no environment variables.

Managed element storage is checked size/alignment with 8-byte-aligned MaybeUninit<u64> backing; descriptors and callbacks stay valid for the entire collection lifetime. Clone/drop/equality/hash act only through the concrete typed callbacks, never by reading/copying raw bytes or padding. Reuse runtime List<Element> and Map<MapKey, Element> COW/cursors. Element implements PartialEq, preserving NaN semantics in List and Map values; only MapKey wraps an eligible key with Eq/Hash. A non-null receiver passed to _take is owned by the call even if output validation fails. Successful optional output with presence=0 leaves its row untouched: never read it. Presence=1 initializes the entire row; its own Nullable flag remains authoritative. Text split receives the same Text descriptor used by ordinary List construction, not an independent runtime type identity.

The runtime C ABI's value-error status does not by itself define a recoverable language failure. LLVM BytesToText/BytesFromInts/BytesSlice explicitly map status 1 to their checked standard Failed(Text), then use ordinary library fail/result propagation; other value faults (such as duplicate Map keys) remain RuntimeAbi. Status 2 always propagates as an ABI fault. Convert the original error Buffer to an owned Text handle, free the Buffer exactly once, and read value output only on status 0. LLVM business payloads belong to its typed fault tail and reuse compiler capture/drop owners, not a new C runtime error registry; details live in compiler-contracts.md.

Protocol async operations validate output shape/alignment and required presence before polling, including operations whose successful output is Unit. Invalid metadata returns async ABI status 4 without changing the operation or output/fault sentinels; a corrected call may retry. Do not perform network I/O and only then reject the result destination. Protocol getters validate destination slots before allocating owned Text/Bytes/stream fields. Their fixed records and handles live in runtime.h; this is not a generic serializer ABI.

Nominal type properties are computed once after cycle validation. Contract analyses reuse a shared dependency graph; monotone summaries enqueue only affected callers. Bundled AST is cached in process; each thread retains only its preceding exact path/text checked Program or diagnostics. Separate CLI processes still check all source and the API baseline.

Native optimization works on a cloned checked clause: coalesce record aliases only while old fields remain equivalent; snapshot only ordinary scalar future reads with no intervening host writes; move only the final overlapping read of a replaced field. Direct split consumers reuse runtime text::pieces Unicode/empty-separator semantics. Fuse only non-resource stages with structurally proven total, synchronous, effect-free handlers; pure alone never proves totality. Preserve argument evaluation, numerical faults and left-to-right Float sums.

Native argument bindings are disposable owned temporaries: a final movable read transfers the source, while a still-live or resource-containing source first clones according to value/resource semantics. Collection lookup/extraction and compatible Text/Bytes conversions consume that temporary so uniquely owned payloads are not copied. Composite rendering recursively writes into one String, including generated records/choices and named entry outputs; numeric to_text keeps its direct to_string() hot path.

Memory parallel batches are capped at 256 elements and check the shared cancellation state between elements. Stream dispatch remains item-by-item. HTTP uses Hyper's incremental protocol state. Bytes shares engine buffers and slices; multi-frame body collection merges incrementally instead of retaining metadata per tiny frame. Empty concat reuses storage without altering aliases.

Native cache keys use SHA-256 and include emitted input, compiler/toolchain identity, exact runtime/dependency bytes, options/platform/environment. A compiler-owned path/size/mtime memo avoids rehashing unchanged runtime files on every cache hit; any metadata change recomputes the exact content identity, and a cache miss verifies copied runtime bytes against that identity before compilation. Publish complete private entries atomically; restore verifies identity and executable integrity, copies into per-call temp ownership, and never skips CLI API checking. Generated Rust is not persisted. Cache digests are content identities, not publisher signatures.

The machine toolchain has one stable dever launcher and a signed version store. A project may select one exact major.minor.patch only through config/setting.json at dever.version; otherwise the machine active version is used. The launcher verifies the signed manifest and selected core before reading project source, then preserves arguments and exit status. Version publication uses staging and an atomic directory rename. Active-version state is a checksum-valid append journal so an interrupted write leaves the preceding complete record selectable on Unix and Windows. Cargo's default dever binary is the development compiler and becomes dever-core in a release. Cargo's dever-launcher binary is the machine entry installed as dever; it must stay independent of LLVM. This is one public command name, with no legacy command alias. Builds do not replace global commands.

dever clean <project-root> is a version-core project command. It removes only current-user Dever temporary build directories and legacy .dever-run-* files that pass exact name/type/owner/age checks and whose recorded process is no longer active, then reports directory, file and byte counts. It never touches explicit build outputs, project data, Lib artifacts, Cargo caches or the machine store. dever cache clean remains an authenticated deverd machine-cache operation with no local fallback; compiler contributors use cargo clean for the repository target/.

deverd is the only writer of released cross-user cache entries. Its storage engine uses complete length-delimited build inputs, SHA-256 identities, immutable atomic entries, integrity checks, active-operation/read leases and maintenance locking. Released clients require platform-authenticated IPC; service unavailability fails without a private or uncached fallback. OS service installation and remaining platform peer adapters belong to distribution, not a caller-writable cache directory.

Linux cross-user IPC uses kernel SO_PEERCRED, verifies endpoint/server UID against the machine state owner and keeps the administrator token owner-only. Foreign users may transfer Lib artifacts and query metadata, never clean or trigger whole-cache hashing. Eight slots admit at most two foreign connections per UID and six total. Artifact transfer accepts at most 64 MiB and stores at most 2 GiB/4096 entries. Compiled entries have separate equal quotas and are inaccessible through ArtifactGet/Put: retrieving a program requires its complete canonical compilation request.

Compilation admission is two requests, with 384 MiB wire input, 4096/16 MiB sources and 4096/256 MiB resources (128 MiB each). The service verifies the installed release and complete runtime reference closure, including its native manifest and LLVM library, on every request before cache lookup. Identity binds canonical input and signed manifest; a persistent private install lock is shared while validating/compiling and exclusive for install/uninstall, never unlinked. Release that installation lease after the verified output is restored into owned memory, before returning the response, on both cache-hit and fresh-compile paths. Temporary staging cleanup must not leave a completed caller unable to switch versions. The whole request holds a cache operation; transmission retains its read lease. Only the signed core's hidden compile worker may produce a publishable program. It reads a service-owned 0600 request inside 0700 staging; trusted state/cache ancestors remain traversable and non-writable by other users. The worker reconstructs/checks sources and links, without loading deployment Settings, preparing Libs, executing App/Test or writing shared cache. Caller retains dependency preparation, baseline checks, program execution and per-case Test settings. Worker CPU/address-space/file/FD/core limits do not constitute an OS sandbox.

Compilation has a 180-second absolute service deadline, including output transfer, and a 190-second client download deadline. EOF or any byte following the exact request body cancels it. Every failure kills/waits for the owned child and removes staging; diagnostics are capped at 64 KiB and output at 320 MiB. This output budget applies only to trusted compilation receipts, never opaque ArtifactGet/Put. Apply remaining time before each write/read; a per-call socket timeout alone permits slow peers to retain version and cache locks indefinitely.

Binary resources cross the compiler bridge separately from bounded textual LLVM IR (8 MiB). The shared resource index verifies digests and binds path, length and executable status into IR/cache identity; declarations are initialized from borrowed bytes before LLVM verification and optimization. Reject duplicate, unused, defined or incorrectly typed/sized attachment symbols; six targets preserve the same byte order. Do not hex-escape interpreter payloads into IR or duplicate large byte buffers merely to sort canonical requests. Attachment limits match the managed resource count/byte budgets, and bridge object output is bounded at 320 MiB.

Signed ecosystem pack contract

Scope / trigger

Native release authoring also packages Python/Node interpreters and Go build tools; Worker preparation consumes the same runtime descriptor validator.

Signatures

packaging::create(author_root: &Path, output: &Path) -> Result<ReleaseManifest, String> and the private native-release <author-root> --output <new-directory> command retain their signatures. workers::runtime::validate(files, ecosystem, target) owns descriptor/file-closure validation for both maker and consumer.

Contracts

Author config/setting.json.runtimes optionally contains pip, npm, go; each has name, version, files[{source,path,sha256}], with Python python_markers and python_wheel_tags. Configuration is bounded at 1 MiB. Sources are explicit regular files below the author root, never env/PATH lookup. The deterministic archive and registry manifest are both signed artifacts; neither an upload nor a filename can substitute for their verified identity. Prepared trees have their own 256 MiB/65,536 file bound; final embedded applications must also fit the stricter compilation limits above.

Validation and error matrix

Input Result
Missing interpreter, Go tool or importcfg archive Reject incomplete pack before publication
Wrong ecosystem/target, Python flags or registry metadata Reject runtime identity/descriptor
Duplicate/escaping paths, file/directory conflict, symlink, wrong digest or signing-key alias Reject author input; remove owned staging
Existing output or concurrent second publisher Preserve published output; reject replacement

Good / base / bad cases

Good: complete relocatable interpreter plus stdlib, or Go tools plus every referenced stdlib archive. Base: omit runtimes for an otherwise complete native-only release. Bad: copy only host Python and assume its host stdlib will exist on the destination; a descriptor alone cannot prove portability.

Tests required

native_release verifies deterministic archive/signature bytes, computed runtime identities, bad inputs and rollback. Explicit ecosystem acceptance must lock from a signed install, execute all three managed check/run/build paths, then run programs after removing source and machine stores inside a root with no system language installations. OS baseline libraries, test key, target and untested third-party registry behavior remain explicit.

Linux no-host acceptance uses an explicitly prepared, test-only namespace fixture (DEVER_TEST_ISOLATOR) to prove standalone packaging without changing the host. This test harness is not a product dependency or Worker boundary. Source-free deployment and non-root execution remain separate checks; a managed run alone proves neither.

Managed Go compilation removes the invocation-owned stage prefix from recorded source paths with compile -trimpath. This applies to the SDK, Adapter and dependency packages through their single Builder::compile path. Preserve logical filenames/line numbers; do not strip diagnostics to hide path drift. The real external_workers Go fixture must prepare twice in fresh stages and compare every emitted resource identity, then execute after source removal. The signed three-ecosystem run/build test must publish exactly three compiled entries. A single successful Go execution does not prove reusable cache identity.

Wrong versus correct

Wrong: encode a 118 MiB Node binary as LLVM text, raise the IR cap, or relax opaque artifact upload limits. Correct: pass checked bytes through emit_object_with_resources(ir, target, resources), keep the IR cap, and apply the separate trusted compile/output budgets. Test author compression deadlines do not change the service's compile deadline.

Formatting is syntax-only, stable and idempotent. It preserves comments, literal values, explicit groups and source record-expression order. Prepare every source before rewriting any; snapshot changes, syntax errors, symlinks and staging failures do not modify originals. Each final replacement is atomic, not a multi-file OS transaction.

Application-test execution reuses checked HIR, specialization, runtime feature trimming and native cache; it does not link the reference evaluator or add an interpreter. Each case owns its temporary executable/project directory. Production check/api/run/build source sets and cache inputs exclude test/; fmt intentionally includes it.

Port native dispatch is a direct call for one implementation or a closed match for several. adapter.<port identity>.use in setting.json selects an immutable startup binding; unknown choices/fields, duplicate keys and missing required settings fail before user code. A selected Adapter's contextual setting is a private record decoded with shared SettingInput wire helpers into a OnceLock; only that implementation requires values. Secret errors never include input values. Port-only binaries enable the wire feature without API/database runtime; a no-setting single implementation may omit setting.json. Runtime configuration uses the bounded duplicate-aware wire parser before typed config parsing.

External exec and managed dispatch remain behind the same selected Port binding. All executions require a verified embedded launch manifest, selected Worker tree and signed process runtime assets; no adjacent-file or bare-process fallback exists. CLI preparation reads process runtime leaves from the authenticated installed release, including for exec. Runtime clears the environment, maps only verified launch arguments, and uses length-framed stdio. Native and LLVM dispatch reuse one invocation settings snapshot for Adapter selection, business settings and command limits. Component tasks reuse the structured application Scope and bounded queues. hello/ready/health must finish before admission; request ids are sequential and exact; timeout/cancellation sends cancel and drains one matching result or error; application cleanup sends shutdown, joins, then uses a bounded kill only when the child misses the deadline.

Python SDK input uses an owned asyncio pipe transport and bounded message queue. Cancel and join its reader on normal shutdown and protocol failure, then close the transport. A daemon thread blocked on sys.stdin.buffer can abort CPython finalization even after a successful reply. The SDK regression must wait for successful process exit after the shutdown reply while the parent's stdin writer remains open; closing it before waiting masks this lifecycle defect. SDK source changes require re-embedding the source through the host compiler before deployed application verification.

dever-process owns direct Linux child execution and process groups, not an OS sandbox. Signed process-runtime/<target>/lib contains loader/OS ABI libraries only; no bwrap, guard, seccomp filter, mount grants or host AppArmor policy is shipped. Preserve authenticated resources, explicit paths, protocol validation, bounded queues, deadlines and cancellation. Pin the group leader with pidfd; terminate its group before reaping the leader, including normal exit and failure. Detached sessions are outside this lifecycle guarantee; trusted Workers must not daemonize. Never weaken the existing container/node security policy to run a Worker.

Managed children clear ambient application environment and inherit only the allocated GPU visibility/driver variables and LD_LIBRARY_PATH. No process discovers language runtimes or compiler tools through host PATH. allow remains static effect/handshake metadata, not a file/network/device enforcement mechanism. Only trusted Workers and dependency build hooks may execute; Pod UID, mounts, network and device policies own the real permission boundary.

Adapter files and gpu grant fields are removed and rejected, not silently ignored. Pass real model/input/output paths as business setting; GPU devices and drivers come from the parent container without nested mounts. Managed C ABI remains the separate exec Worker SDK in sdk/c, never arbitrary dlopen in the Dever process or Dever raw pointers. A successful CPU invocation is not GPU/model validation.

Go tools consume a private input tree, including parent-generated import/embed configuration, and a separate writable output tree. Parent reads of generated programs must use nofollow, regular-file and single-link checks with a byte limit; never follow a tool-created output symlink on the host. Runtime/SDK/build assets and source remain explicit, without host compiler discovery or implicit networking.

When a build carries compiler-owned external resources, the native entry may include a deterministic resource table. dever-runtime::external releases it only below the executable's private data/cache/lib/<digest> directory, rejects symlinks/path escape and digest mismatches, and publishes a complete staging directory atomically. Existing entries are reverified; a concurrent publisher is reusable only after the same manifest verifies. This extraction path never downloads, consults PATH, or accepts runtime paths from environment variables.

Resource SHA-256 must match its bytes before native cache lookup. The bootstrap emitter references private, fixed-name binary compiler inputs with include_bytes!, not decimal arrays; identical checked digests share one static payload/input while each resource retains its own path and executable bit. Emitter and build staging reuse one input-index owner so they cannot diverge. The build owner stages each unique input exclusively and removes it with the owned build directory. Runtime integrity checks compare exact length, every 64 KiB chunk and digest against embedded bytes without allocating another whole interpreter image.

Markdown Port function metadata adds - 允许失败: after outputs, exactly matching the fails type. Qualified Adapter/fake names remain complete in their function sections and private in public-method lists. The setting declaration uses a Type section named Setting with its ordered field metadata.

Markdown selects only top-level fenced blocks with literal info dever or typescript dever, using pulldown-cmark offset events rather than scanning fence-like lines. Quotes/lists/raw HTML/outer showcase blocks are presentation. Fences use backticks or tildes with CommonMark 0–3-space indentation and require explicit closure. Both formats own one package each; duplicates are C002, never merged or selected by priority.

Every .dever.md has exactly one natural-language H1 source section. Its ordered metadata is path-derived source identity, role-derived public types/functions and logical App call examples; H1 has no executable program block. Every type or logical (function name, arity) group has one natural-language H2 section and one program block. All clauses in a logical function share that block and input names. Type fields/variants and checked function parameter/output names, types, counts and order must equal their documented inline-code values. Empty collections use explicit 无; per-field/variant/input/output descriptions are nonempty. H3 and deeper supplemental content may follow the section's program block.

Closing-fence trailing whitespace is spaces only; a tab is rejected as an unclosed program fence (M002). The Markdown parser receives a same-byte-length view with bare CR changed to LF because it does not recognize bare CR itself; source text, code lexing and diagnostic positions still use original bytes. CRLF is kept intact. Do not normalize entire files or introduce an offset-changing source transformation.

SourceFile text, cache keys and CLI snapshots retain original Markdown. Lex each block in its original byte range so Text/comment scanning cannot enter prose. Parsing and formatting share extraction, structural documentation parsing and block validation. After function signature resolution, semantic checking compares documentation with syntax/HIR before checking bodies. Formatting reuses the AST emitter per block, keeps comments in their block, preserves external/fence bytes and the opening fence's newline style. Runtime faults keep original positions through HIR. The Markdown dependency belongs only to the compiler.

Native last-use analysis walks actual HIR read order backwards, kills full assignments, retains field hosts and outputs, and identifies concrete expression nodes. It may move only ordinary values: resource aliases have observable lexical scope. Share recursive type-property traversal for comparability, transferability and movability. Full-domain Int/finite Decimal guards need no runtime comparison; actual clause bounds must remain.

native::OPTIMIZATION_ARGS owns production and baseline optimization flags: level 3, one codegen unit, fat LTO and stripped symbols. The workspace release profile applies matching fat LTO/one-unit settings so the runtime rlib retains bitcode for the final native link. Multiple units caused larger generated programs to miss the same generic hash-table inlining performed in a small equivalent baseline. These settings preserve that optimization without weakening overflow, hashing or panic semantics, at the cost of compilation parallelism and higher compile time/memory. Stripping removes release-only debug/symbol payload without removing source-location strings used by Dever failures.

Application test suites use level 1, 16 codegen units and stripped symbols without LTO. Tests validate observable semantics and source locations rather than production optimization quality; run, build, performance fixtures and baselines continue using OPTIMIZATION_ARGS.

Concurrent actions use a caller-owned producer, bounded queue and joined workers. Exact-size finite iterators create at most one worker per item/batch; unknown-length Stream iterators retain the explicitly requested limit. Faults stop further dispatch at cooperative pull boundaries and already-running work drains. Pending blocking operations require explicit OS timeouts; there is no forced cancellation or detached task. The reference evaluator chooses a documented sequential valid schedule; concurrent stdout ordering is not a differential invariant.

Inferred-suspending entry points own one bounded Tokio runtime. Child Scopes share task and blocking semaphores but keep independent work registries; body cancellation cannot cancel the supervisor responsible for recursively draining descendants and started blocking jobs. Transitive effect checks, including concrete handler substitution at wrapper calls, keep blocking system operations, stdout and hidden collection-handler concurrency off Tokio scheduling workers unless they use an explicit bounded boundary.

Async stream consumers reserve capacity before pulling and observe child failures while the producer is idle. Close releases the producer's resource alias, not independently held Socket/Listener aliases. TCP has independent direction locks and a shared close signal. Read buffers allocate after readiness. Operation deadlines include direction-lock wait; partial writes close the socket on abandonment before releasing the write lock, with no whole-message retry. DNS uses the shared bounded blocking path.

Single read(resource, limit) uses the caller-selected maximum buffer and must not silently clamp a valid limit: regular files may satisfy the whole request in one operation, and existing programs rely on that result. Reads may still be short according to the OS. Memory-constrained programs choose a smaller limit or use the pull-based chunks interface; the runtime cannot both return a limit-sized value and avoid storing that value.

JSON uses an acyclic flat document: consecutive postorder IDs, child IDs smaller than parents, Map insertion order independent of ID order. Numbers retain raw JSON spelling, object names are unique, Unicode surrogate escapes must pair. Maximum depth is defined once in dever.json.value; stringifier checks references and output expansion before concatenating child graphs.

Typed wire boundaries are separate from the ordinary source Document API. Runtime wire (enabled by api) owns a borrowed RawValue parser with duplicate checks at every object, total byte/value/depth budgets (16 MiB / 65536 / 64 containers), exact raw Json and bounded output writing. A missing object value must retain its incomplete frame; a byte-limit failure after a partial write permanently prevents finish from publishing Encoded JSON. Generated concrete decoders reject unknown/missing fields and never pass Node/Value to business signatures. API envelopes embed only validated Encoded JSON, preserving raw numeric spelling. Decimal/Id/Uuid use strings; DateTime normalizes offsets to UTC Z with optional three-digit milliseconds, Date is YYYY-MM-DD and Time is HH:MM:SS[.sss]. Reject leap seconds, submillisecond precision and calendar years outside 0000–9999. Duration remains a JSON i64. Select root time_codec with api/reference for the concrete native decoder, policy, parser budgets, native/reference time, Markdown parity and in-process API dispatch checks; it opens no listener.

HTTP/1 server connections reuse AsyncStream/Group and the same task cap, with capacity reserved before accept. Hyper owns framing/keep-alive/pipelining; source handlers specialize directly. Preserve exact record-field contracts at the intrinsic boundary and include callbacks in effects, dependencies and specialization. Header/body/handler/stalled-write deadlines release peers. Configuration, accept and handler faults propagate through serve; ordinary peer failures end only that connection. send errors return Failed, with driver and request polled together. No old wire/transport API, detached driver, fallback parser, TLS/HTTP2, nonempty trailers, upgrades or streaming response in N2. Tests compare with independent wire peers.

N3 live HTTP adds one structured handler per connection, using a Group of one under the same global cap. Response body Drop cancels even HEAD/buffered handlers; a Session guard ends the stream or upgraded socket and invalidates escaped aliases. Ordinary stream idleness is a peer failure; handler faults retain their original error and cannot become a successful chunked EOF. An upgraded Hyper driver finishes before its WebSocket handler: the connection owner must wait for that handler and keep its capacity reservation. Take the concrete TCP/TLS Transport and pre-read bytes out of Hyper on upgrade so the HTTP write timeout does not leak into WebSocket policy.

LiveLimits owns maximum chunk bytes, stream idle deadline and shorter SSE heartbeat interval. A one-slot channel bounds pending chunks; business values, current writes, engine and OS buffers are additional memory. SSE normalizes CR/LF/CRLF without discarding trailing data lines, rejects event/id field injection and checks encoded length before allocation. Heartbeats are three-byte comments generated by polling the body; replay/history is application-owned through Last-Event-ID.

WebSocket data message and write-buffer sizes are bounded, including fragmented messages; read buffer is 4 KiB. Independent direction locks permit simultaneous receive/send. Acquire the writer lock before arming the partial-frame cancellation guard: cancelling a lock waiter cannot close another task's active frame. Endpoint.take wakes ordinary operations while transferring the final transport owner to close-handshake cleanup. Control frames, masking and UTF-8 belong to tungstenite. receive/messages must be polled to process Ping/Close; no detached reader or automatic Ping task. Limits are per operation. N4 adds WSS; subprotocol negotiation, compression and close metadata remain deferred.

N4 pool ownership uses separate request and physical-connection permits, each bounded by Limits.connections; idle and queued drivers count as physical connections. One structured task polls bounded queued/running Hyper drivers and idle expiry. Construct its owner guard before task creation so dropping an unpolled child closes escaped pool aliases. Never detach a connector/driver or retry partially sent requests. Return a connection only after complete EOF; body drop/fault/cancellation aborts that entry. Streamed transfer bounds chunks/read waits, buffered request additionally bounds total body/time. TLS shares trust/session caches with full certificate/name verification and small explicit cache capacities; public roots are bundled, custom roots replace them.

N5 HTTP/2 reuses Hyper/h2 with fixed receive windows, 16 KiB frame/send-buffer settings and decompressed header budgets. TLS must negotiate h2 through HTTP-specific derived configs; do not mutate shared WSS trust/config or downgrade. Cleartext uses prior knowledge. Source targets remain path/query; normalize authority to Host when Host is absent and reject disagreement. Connection-specific fields are rejected rather than silently rewritten. HTTP/1 upgrades remain the WebSocket path; no extended CONNECT, h2c Upgrade, push or nonempty trailers.

Hyper's synchronous Executor must spawn registered Dever child Scopes. A scoped connection owner drains these tasks and their started blocking descendants before releasing its physical guard. Serialize closing admission and child registration; task completion must include fault reporting and registry removal. Cleanup belongs to an uncancellable registered supervisor, even when the caller awaiting stop/finish is cancelled. Never take a Scope work registry in a cancellable caller and lose the captured completions on Drop. Each live HTTP/2 body owns its handler Group under that stream's Scope, so reset before/after response head cancels only that handler; report handler errors explicitly because Hyper consumes HTTP/2 stream errors internally.

HTTP/2 clients lease streams independently from physical connections, with total requests bounded by connections × streams (at most 65536). Upload and download share the stream lease; neither idle expiry nor another stream's cancellation may abort an active neighbor. Create connection scopes when handshake jobs are polled by the persistent pool driver, never under a temporary request Scope. Queued, idle and draining connections share the physical budget. GOAWAY blocks new dispatch while accepted streams drain. Only Hyper TrySendError returning the unsent request permits requeueing within the original deadline; release the old upload lease first. Never replay a sent request or infer dispatch safety from an error string. Single-use send has one deadline spanning TCP, handshake and exchange, followed by mandatory cleanup. Server first-request and protocol liveness deadlines prevent silent peers from holding connections indefinitely.

Listener close ends HTTP accept normally and triggers Hyper graceful shutdown while active response/upgrade owners drain. Public net.connections retains a terminal Failed on explicit listener close. Applications use timeout(server, grace_ms, zero-output fallback) for bounded drain. timeout/race borrow supervisor handles while waiting, cancel and drain losers/expired work before returning, and preserve runtime faults. Source stream adapters retain failure obligations and nullable Channel items; closing the adapter does not close independent Channel aliases.

Create a response-body cancellation owner only after the pending-to-committed state transition is accepted. Dropping an uncommitted replacement body must not close a previously committed response. Rejected duplicate start/respond/SSE/upgrade calls leave the existing stream usable; head delivery failure still cancels the committed body.

4. Validation & Error Matrix

  • New target already exists (including empty directory or dangling symlink), parent is missing, or two creators race: explicit error for the loser; preserve the existing target and remove only owned staging.
  • Signature/payload/skill corruption, incomplete archive or absent official asset: explicit failure, no active-version switch or fallback. Publishing source code is not evidence that a downloadable binary release exists.
  • Truncated Bash body: no installer or sudo execution. Missing prerequisites: fail before metadata download. Failed authentication through Bash: preserve existing active journal/core/bootstrap and clean only owned staging. Tests load the embedded Python from the actual root entry and exercise Bash file/pipe execution; retain a check against the independently provisioned public key. Successful same-version bootstrap may append an activation record; assert selected-version identity rather than a byte-identical journal.
  • Project has a pinned version: skill path <project> resolves that exact installed version. Foreign users must read matching guidance without obtaining the administrator install lock.
  • Test filter/timeout is missing, repeated, non-UTF-8 or malformed: reject before execution. No selected case: fail before compilation. Assertion, process error or timeout: retain labelled captured output, continue later selected cases and return nonzero. Cleanup only the case's process group; never reap unrelated children or leave adopted descendants to PID 1.

Cross build: unknown/duplicate/missing target arguments fail before execution; absent target packs, wrong ELF/archive machine, unsigned target leaves, incompatible lock/runtime/build receipt and changed target inputs fail before cache reuse or linking. Process runtime loader mode must survive both release packing and embedding; a hash-valid non-executable loader is not a usable Worker resource.

Native maker: wrong format/target/version, unknown or duplicate fields, missing profile, non-regular or escaping source, SHA mismatch, exposed/invalid signing key or payload alias to key → explicit failure, no output, owned staging removed. Existing or concurrently created destination → no overwrite. Correct bytes → complete signed v2 catalog with base and extension artifacts, without private key/configuration. Unsupported host publication → explicit failure, never a weaker rename fallback.

Managed input with duplicate fields/noncanonical encoding, unsafe paths or forged resource digest -> reject before publication; invalid source -> original checker diagnostic from worker; unavailable service -> explicit failure; signature/runtime omission or tampering even on a cache hit -> reject; full admission/quota -> bounded error; cancellation/expiry -> reap child and release staging/locks without publishing a partial executable.

External Lib declarations live only in the root lib array of config/setting.json; reject old config/lib.json rather than silently combining it. Canonical dever-lock-v6 locks bind checked Port/Adapter/schema/operations/capabilities and independent Worker roots. Registry artifacts retain exact {ecosystem,locator,filename} sources. Build Receipt.inputs is the complete fixed LockFile: Python build requirements or npm's pre-pruning execution graph (no self-referential build receipt). Receipt.graph remains the post-build result. Doctor rejects stale bindings, missing/cyclic closure or within-environment version conflicts; independent Workers may select different versions. Embedding compares complete normalized provider metadata, including dependencies, runtime, schema and artifacts, not just an artifact subset.

dever lib install <root> requires a current canonical lock, rejects specs, and holds the existing project mutation lock. Restore exact Package ZIPs first, then check declaration/Worker closure and selected target before restoring Lib archives. It never invokes a version resolver or writes setting/lock. A true missing archive uses its recorded source with existing registry host/path/size rules and locked Go evidence. Missing build outputs replay fixed receipt inputs through the same bounded managed executor used by initial resolution; validate runtime/tools/frontend, result graph/outcomes, bytes and digest before publishing. A non-reproducible build is an explicit failure, not authority to rewrite the lock. Ordinary run/build and doctor/remove remain readonly; add/update/install and Package preparation ensure runtime resources before Worker binding, including no-Lib adapters. Build resources are ensured only when the source-build path actually requests them. Cached built outputs do not need build tools.

Production registry access derives from a verified installed version core, not host tools or development fixtures. Signed assets runtime/<ecosystem>/<target>/manifest.json (dever-registry-runtime-v1) bind a RuntimePack identity and the adjacent runtime.pack; Python metadata additionally supplies target markers/wheel tags. Resolver owners implement PyPI PEP 508/440, npm semver/SRI and Go proxy/MVS with fixed HTTPS origins, disabled proxies and bounded work. Redirects are rejected except for Go /@v/*.zip: manually follow at most two hops into the exact HTTPS storage.googleapis.com/proxy-golang-org-prod/ bucket. Validate normalized host/port/path and reject userinfo, fragments, missing/duplicate Location and loops before issuing a subsequent request; all hops share one 30-second deadline and diagnostics must not echo signed URLs. Loopback mirrors are explicit test transport, never project configuration. Unsupported extras/sdist, install hooks and Go sumdb are not silently approximated. Only explicit Lib commands resolve/download; run/build consume locked cached bytes.

workers::prepare(root, Program, resources) expands verified runtime packs (dever-worker-runtime-v1: ecosystem, target, executable, arguments; Go additionally has build) and owned Adapter sources into a per-contract workers/<digest> tree. Python uses exactly -I -S -B, installs the packaged SDK path and imports that trusted SDK before exposing business source/dependency paths, and reserves stdout for protocol; JavaScript binds ESM/CommonJS exports. Both bind each checked Port operation by name using sdk_manifest(). Go consumes fixed-target compiler/linker/source selector and stdlib importcfg from the same exact locked pack, compiles the SDK and checked-operation runner alongside target-selected Adapter files and locked module ZIPs, then embeds only the executable and checked contract. Go source exports one exact func(context.Context, any, any) (any, error) per operation; send maps to Send, dotted segments to PascalCase. Cgo, assembly and unlisted imports fail explicitly. Build tools run by absolute path with an empty environment and bounded lifetime; product compilation does not invoke host go build, PATH, GOOS, GOARCH, GOCACHE or GOPATH. <entry>.dever-worker.json (dever-worker-launch-v1: ecosystem, entry, executable, arguments, working_directory) accepts only manifest-bound resource arguments in that same tree and bounded literal flags. Runtime revalidates the entire private bundle before every launch/restart and clears the inherited environment. Discard consumed raw runtime/archive resources after expansion unless config roots or exec Workers still need them. A private fixed-target pack fixture proves the local compile/link path; signed release packs, Go sumdb and cross-platform distribution remain separate acceptance work.

Packaged exec Workers resolve only against the entry's embedded manifest. Bundle identity includes path, byte digest, length and executable bit. Validate all path segments, Unix owner/private permissions and file bytes on both cache reuse and every Worker restart; do not scan other bundles or fall back to source workers. Publish owner-only files/directories atomically before exposure. These protocol and integrity checks do not establish OS capability isolation; deployment container policies own that boundary.

dever.crypto uses the existing source Result choices and exhaustive Intrinsic bridge. Secret storage lives in the base runtime with zeroize; Argon2id, SHA/HMAC and OS randomness are in the optional crypto feature. Native runtime feature selection inspects already-pruned emitted crypto calls so direct system intrinsics, API roots and Test roots are covered. Password hashing uses RustCrypto Argon2 0.5.3, Argon2id v19 and default Params; PHC verification bounds algorithm/version/memory/time/parallelism/output before computing. Failure messages contain no input. Hash/verify use the existing blocking-worker effect boundary. dever.process exposes arguments only; application settings never come from environment variables.

Cache miss -> compile and publish; changed inputs -> separate key; incomplete/modified published artifact -> explicit error; unchanged sources with modified API baseline -> reject before native reuse. Concurrent writers may reuse only a complete same-identity entry.

Condition Result
Async op Pending; ready typed fault; runtime error No output initialization; move checked fault with original kind/source; move original error bytes into RuntimeAbi fault respectively
Consuming async operation creation returns null Keep caller-owned input live for cleanup; a non-null operation owns the input through completion/cancel
Invalid File/Stream writable slot ABI invalid-input status before I/O or shared cursor progress
Null/misaligned runtime ABI output, null nonempty input or unrepresentable length ABI status 2; never dereference that pointer or read an uninitialized value output
Int overflow, numeric division by zero, nonfinite Decimal bits or invalid UTF-8 ABI status 1 with owned original runtime diagnostic; caller frees Buffer exactly once
Invalid element descriptor/layout, or missing Map-key hash callback ABI status 2 before constructing element storage; callback pointers and concrete row layouts remain compiler-owned lifetime/type obligations
Optional extraction succeeds with presence=0 Do not read the uninitialized row slot; return zero Nullable and release consumed receiver/unvisited cursor rows
Recoverable Bytes operation returns status 1, or any returns status 2 Bytes status 1 becomes its original Failed(Text); status 2 remains RuntimeAbi and is not caught by result
LLVM-generated Windows aggregate object linked without target runtime support Explicit missing __chkstk/_fltused diagnostic; no successful output or fixture replacement symbols
Invalid format input anywhere in source root Diagnostics, zero source rewrites
Markdown source has no program blocks M001 at original source
Program fence is not explicitly closed M002 at opening fence
Package header/type/function crosses program blocks M003; no format writes
Package or declaration section is absent, duplicated or contains the wrong declarations M004/M005; no format writes
Documented package/API/declaration name differs M006 with documentation and code locations
Documented function input differs M007 with documentation and code locations
Documented output/type field/variant differs M008 with documentation and code locations
Same package in .dever and .dever.md Existing C002 duplicate-package check
fmt --check finds changes Exit 1, no writes
Ordinary alias remains live Preserve independent value semantics
Resource-containing local reaches last read Retain lexical lifetime; no earlier socket EOF
Invalid parallel count Source-located failure before pulling or invoking handlers
Stream-containing worker input C005 before native compilation
Invalid scalar index/number input Null, never a default zero or lossy truncation
Exact finite input shorter than requested workers Same visits/results with no more workers than items/batches
Valid one-shot read limit Caller-selected maximum is passed to the OS read; no runtime clamp
Composite/named-output rendering Exact existing bytes, appended through one result buffer
JSON grammar/reference/depth/output violation Explicit Failed with offset/node and message
Component hello/ready/schema/operation/capability mismatch Startup fault before request admission; child is killed and reaped
Component duplicate/unknown/out-of-order/truncated/oversized message Fail the current and queued calls, close the generation and reap the child
Component call timeout or caller cancellation Send one matching cancel, drain one matching result/error within a deadline, otherwise terminate the Worker
Component shutdown with active or queued calls Close admission permanently, cancel the active call, drop queued calls, then bounded shutdown/kill/wait
Managed launch identity/path/argv/runtime drift Reject before executing any interpreter; no host fallback
Shared artifact bad hash/length, overflow, truncation or quota exhaustion Fail without publication; clean the owned staging and release operation/admission guards
Foreign UID requests cache clean Reject by kernel caller identity, regardless of supplied token
HTTP peer framing/body violation Hyper rejection or explicit error response/connection close, no handler invocation
HTTP invalid outgoing message send Failed or serve task fault; never silently rewrite framing
HTTP/2 TLS peer cannot negotiate h2 Explicit TLS/ALPN failure; no HTTP/1 downgrade
HTTP/2 connection-specific header, or response TE header Explicit error; request TE allows only trailers
HTTP/2 reset before/after response head, including a blocked write Cancel that handler and drain its descendants; neighboring streams survive
HTTP/2 handler program fault Original error propagates to serve; never treat it as normal EOF
HTTP/2 GOAWAY while old streams remain Stop admission and keep the physical connection permit until cleanup
HTTP/2 stream/connection budget or window outside its bounds Explicit failure before accepting or connecting

5. Good / Base / Bad Cases

Onboarding base: dever new app followed by run app -- hello.greeting.greet '{"name":"Dever"}' returns the standard envelope with data:"Hello, Dever". Good: --markdown generates equivalent checked declarations; two projects/users share core and skill. Installation good: standalone Bash installs a verified local release into an owned image, then pipe reinstall preserves it. Bad: manual main.dever scaffolding, Go service/Page JSON templates, update URLs in project setting.json, a Git login page served as install, or a global skill copied once and allowed to drift from the installed compiler.

Test base: no filter executes all cases serially; no test directory reports zero success. Good: --filter user.account.register --timeout-ms 10000 selects the original case index while other source errors still fail checking. Bad: using substring matching, renumbering filtered cases, counting no match as success, or timing out only the leader and leaking descendants.

Cross build good: an x86 core uses ARM profiles, ARM Worker assets and x86 Go tools emitting ARM objects. Base: omitted target retains native behavior. Bad: replacing global host identity, executing an ARM build tool on x86, labeling x86 native extensions ARM, or deriving target loader permissions from the host.

Native author base: fixed inputs and temporary key produce a verifiable manifest. Good: two different output names have identical manifests/signatures and payload digests, source mutation does not affect either published copy, and optimized profile programs run through the managed compiler. Bad: hard-link output to build caches, accept a debug all-features archive as four trimmed profiles, or call an unused PostgreSQL configuration a real database test.

Managed base: a signed Package project completes check/test/run/build and its built program runs without daemon. Good: different UIDs and project directories submit the same logical inputs and reuse one entry, while wrong source, unsigned CRT or modified pack fails. Bad: accept client IR, fetch compiled output through artifact digest, upload full Settings, run the application under the daemon UID, or make state/socket directories private to hide a worker permission bug.

Resource/async base: create/read a private fixture file and lower sleep to a real switched-resume frame. Good: aliases share Stream progress; stop releases a pending child and Scope drains descendants; large typed records and errors survive Pending; sync Task inputs/outputs transfer through the same bounded blocking owner. Bad: declare async metadata safe from parameters alone, clone borrowed arguments after initial suspend, reinterpret a typed error as String, or let a same-content overwrite pass the test.

Runtime ABI base: Int 40+2 yields status 0/value 42/null Buffer. Good: explicitly link a runtime-abi-only archive from a C or LLVM caller, read output only on status 0 and free an error/text buffer via the matching symbol. Bad: cast Rust DecimalValue into a C layout, pass aggregates by value, reuse a live owned Buffer slot, free compiler Reply via runtime buffer_free or treat author fixtures as signed release packs.

Managed ABI good: typed C callbacks retain/drop a nested Text record; aliased List/Map updates preserve the original; early cursor release drops remaining rows; duplicate Map keys retain the exact original diagnostic. Bad: byte-copy a managed payload or padding, make ordinary Float elements implement Eq, or confuse outer row existence with a nullable element's null state.

Base: format the hello sample twice; bytes are unchanged on the second pass. Good: move an unaliased Map payload into get, render a nested value into one buffer, or parse and stringify nested JSON with an exact large number. Bad: clamp a valid one-shot read behind the caller's back, move the last Socket alias into a short-lived function, accept conflicting Content-Length values, or compare concurrent stdout as an ordered trace.

Markdown base: an application file documents its path-derived component/domain/role identity in H1 metadata; API sections document declarations and contain no handler bodies. Good: keep every type/function/declaration description synchronized with its checked signature and format without changing prose. Bad: add application main.dever.md, put code under H1, group two functions under one H2, split clauses across H2 sections, execute a quoted example or move a comment across prose during formatting.

HTTP/2 base: null Limits.http2 retains HTTP/1; default_http2_limits() selects 16 streams and fixed 65535/262144-byte receive windows. Good: a TLS proxy makes a nested request through the same one-connection pool while its outer response remains open. Bad: expire that active connection using the idle timer, or reuse a cancelled stream's lease on a replacement connection.

Component base: one selected external Adapter completes hello/ready/health, serves typed Port calls and acknowledges shutdown. Good: a protocol fault closes the old receiver before a later call creates a rate-limited new generation; shutdown rejects every racing or queued call and explicitly reaps the child. Bad: drain a full request queue during shutdown, restart after admission closed, rely only on kill_on_drop, or report handshake capability equality as an OS sandbox.

Managed base: a zero-Lib Python/JavaScript Adapter still locks its signed runtime and generates a typed runner. Good: preserve raw archives shared with exec while removing managed-only copies. Bad: import the Python SDK before restoring the packaged path under -I, use a peer-supplied cache path, or treat verified:false counts as byte-integrity evidence.

6. Required Tests

For onboarding select CLI new_project, lib release_source, shared-toolchain version/skill tests and native-release skill authoring tests, plus python3 -B -m unittest discover -s test/onboarding -v. Assert both formats check/format, no-overwrite concurrency, real CMD/Test/build output, exact signed extraction, corrupt-download retention, project-pinned guidance and foreign-user reads. Project skill installation must cover actual no-argument launcher dispatch from an owned cwd, create/append/replace/idempotence, preservation of user instructions, pinned template selection and failures before writes; no global AI directory or service is needed. The foreign-user test lowers only an owned client UID. Bootstrap script tests mock final installation; report that separately from real native-template execution. Do not activate host services or run full release/CI suites as an onboarding check.

Test-control changes select CLI bin test_arguments, case_process_captures_output_times_out_and_reaps_only_owned_descendants, and llvm_cli::test_filter_still_checks_unselected_sources_and_reports_no_match_before_compilation. The opt-in llvm_test_controls_preserve_indices_prefix_boundaries_and_timeout_continuation consumes an explicitly prepared compiler-relative runtime pack. Assert actual non-first case execution, identity prefix boundaries, no-match failure, source errors outside the selection, timeout output/continuation, large output and owned child/grandchild reap with an unrelated child preserved. Never rebuild runtime archives recursively from tests.

For installer-only changes select test_install*.py and bash -n install; also run toolchain::release_source when its Rust download owner changes. Assert actual Bash file/pipe help, isolated Python, literal argument/exit-status preservation, non-root sudo dispatch, independent-key authentication, new origin paths and rejected redirects. verify_install_entry.py is an opt-in actual signed-payload check: source-free entry, image-only first install, repeat install and corrupt-signature preservation. It uses an existing authenticated release/extractor and no host services; old payloads do not establish new-binary or online update acceptance.

Cross-target changes cover build_arguments, native-release target/ELF/mode cases, CompileRequest validation, cache isolation and Lib/Worker target selection. The opt-in signed_host_compiler_builds_arm_profiles_and_runs_standalone_under_qemu and signed_arm_ecosystems_build_offline_standalone_apps_for_system_guest require explicit author inputs. Run exported Workers/HTTP with test/ecosystem-release/arm64/simulate.py under a complete ARM kernel; assert each successful output, source-located expected failure and child cleanup. Do not substitute QEMU user emulation for namespace/seccomp execution or infer physical ARM performance.

Native release changes select native_release plus affected private pack/installation checks. Default cases cover deterministic bytes/signature, private-copy ownership, malformed configuration/path/digest/key rejection, cleanup, and concurrent no-overwrite publication. Explicit native_release::acceptance consumes prepared optimized archives and author executable; inspect SQLite/PostgreSQL symbols, then repeat packaging, verify signed installation, compile/run all four profiles and run independent outputs after source removal/daemon stop. Report PG-server and cross-host source rebuild evidence separately. Keep native checks and Cargo serial under constrained disk space.

Managed compilation selects packages::managed_compile, the installed Package execution fixture, affected shared_toolchain cache/install/IPC cases, and private llvm_cli. Cover secret-free snapshots, reserved/strict source checks, cross-UID reuse, changed sources, failure recovery, fake-only Test execution, signature reference omissions, cache-hit tampering, limits, real cancellation/disconnect/deadline reaping, and shared install lock lifetime. Tests use owned daemons and temporary signing keys. Check final dever/deverd DT_NEEDED independently: empty-environment success on an LLVM-equipped host cannot establish absence of a dependency.

Runtime ABI changes select native_runtime_abi and opt-in native_runtime_link: exact Decimal word round-trip, checked errors/IEEE floats, borrowed UTF-8/Bytes including null-empty and invalid input, real C-header/staticlib linkage, LLVM scalar/out-pointer calls and matching buffer release. Managed changes include canonical C typed lifecycle callbacks, nested rows, COW aliases, cursors/early release, duplicate Map keys, split descriptor identity and Bytes conversion/slice. Build the offline runtime-only archive explicitly, then set DEVER_RUNTIME_ABI_ARCHIVE to its absolute path for native_runtime_link; release checks must select the actual candidate archive rather than an unrelated fixed-path cache. Do not recursively build it from tests or silently use an embedded-compiler archive. Opt-in llvm_managed_native and llvm_result_native reuse the shared runtime-linked runner to verify real checked-source execution and repeated allocation balance; this is not a general memory profiler or capacity test. Typed lowering/bridge tests and target-pack limitations are specified in compiler-contracts.md.

File/Stream/coroutine ABI changes additionally select llvm_resource_native, llvm_async_native and llvm_async_source. Keep hand-written LLVM/C ABI smoke separate from checked-source lowering evidence; execute both against the actual archive. Assert all initial/pending/final destroy paths, actual Pending/backpressure, typed error transfer, sync input borrowing, non-null creation consumption, nullable row/End, Scope drain and repeat allocation balance. Use an atomic allocation ledger for concurrent workers. Do not run broad database/service/performance checks or claim complete application/target-pack acceptance from these tests.

HTTP/system lowering selects llvm_http_system_source plus the above affected ABI/async targets: repeated headers, independent chunked wire, pooled H1/H2 uploads/downloads, verified TLS, live/SSE, WebSocket typed variants/end, context ownership, failure-500-next-request, original diagnostics, calendar/UUID/Secret/crypto/argv and exact stdout/log JSON. The canonical C protocol fixture must reject null/misaligned destinations before poll, preserve sentinels, allow corrected retry, and reject completed repoll. The pure-log C fixture uses the same strict allocation ledger; logger concurrency/backpressure/panic tests stay under root test/runtime_logging.rs. Six-target object generation is separate from the actual Linux archive execution.

AsyncStream/TCP/timeout/race/ParallelEach changes also select llvm_stream_network_source and the existing async composition/network reference fixtures as appropriate. Cover successful null/Unit versus genuine timeout, exact typed faults without fallback, shared stream close, terminal rows, all dispatch categories and descendant peer EOF after cleanup. C polling invalid input returns DEVER_RT_ASYNC_INVALID_INPUT=4; it must never look like a typed fault. Canonical signatures remain only in runtime.h.

Performance changes select the affected native_ownership, runtime_foundations, concurrency or native_cache cases. HTTP changes select http_engine (independent wire, repeated headers, framing, body limits, deadlines, connection backpressure and task cleanup) and http_library (static handlers/effects, native bridging, examples). Bounded ignored performance tests require explicit scope; correctness checks do not establish throughput or RSS improvements.

Choose relevant root targets: formatter, standard_library, native_ownership, concurrency, json_library, http_library, and opt-in differential. Assert independent expected results, diagnostics, source field/Map order, scope lifetime, actual worker overlap, limits, malformed protocols and wire bytes. Native/resource tests own all temporary files and loopback sockets.

Markdown changes select markdown_source and affected formatter/syntax_and_format regressions. Cover mixed formats/duplicates and unchanged language rejection; H1 metadata without a block and H2 one-block structure; public names/use examples; fields/variants; resolved clause inputs and outputs; explicit empty lists and natural descriptions; original UTF-8/LF/CRLF/CR positions; hidden/nested/nonprogram content; closure and cross-block rejection; comments, prose preservation and idempotence. Verify actual CLI check/fmt/api/run/build with isolated small programs and failure-before-rewrite cases, without a full or service integration suite.

performance is explicitly ignored by default. It measures bounded hot paths after setup against the same representation and runtime, with exact output checks and repeated median measurements. Keep the 1.15 ratio gate meaningful; never replace a baseline by a slower different representation to conceal a compiler regression. Report environment and actual scope, not generic speed claims.

N3 selects live_network and live_library: independent HTTP chunks and WebSocket frame bytes, preread upgrades, masking/fragmentation/control frames/UTF-8, exact SSE field/line/size rules, backpressure, phase vs idle deadlines, task/connection limits, close/cancellation and native static bridging. Existing http_engine, http_library and affected async_network cases cover shared owners. Service examples are checked/formatted without starting their persistent entry point.

N4 selects async_composition, pooled_network and pooled_library: source configuration, affine timeout/race, async memory fusion boundaries, Channel/ticks, exact typed context/effects/failure obligations; independent connection reuse, upload framing, stream backpressure, queue/body/idle deadlines, incomplete-body cancellation, unpolled pool cleanup, CA/name rejection, WSS and graceful draining. Native programs must exercise the complete checked source bridge. The self-contained backend example may run on its owned random loopback port; persistent examples remain check-only.

N5 selects http2_client, http2_server, affected http_library/pooled_library, HTTP/1 pool/live regressions and structured task lifecycle cases. Independent h2 peers must prove actual multiplexing, stream reset isolation, flow-control recovery, stream/physical budgets, active-body idle behavior, ALPN success/rejection, GOAWAY draining and handler error propagation. Native source must cover HTTP/2 single-use send and a TLS proxy that issues a nested request through the same one-connection client, plus streamed upload, SSE and run/wait inside handlers. Functional checks do not establish HTTP/2 throughput or memory improvements.

External Component Protocol changes select external_component, port_adapter and application_testing. The fixture must be an owned test executable, not Python/Node/Go or a service dependency. Assert two calls, declared business error, health, caller cancel, timeout cancel, crash/restart, malformed frames, queued shutdown, schema drift and native Worker execution. These tests establish protocol/lifecycle correctness only; they do not establish ecosystem resolver, packaging, OS sandbox, throughput or RSS.

Resource and Lib changes also select external_resources, CLI external_libs, application_config and shared_toolchain. Include concurrent extraction, execute-bit identity, symlink/permission rejection, no-source/env-cleared packaged exec with repeat runs and tamper rejection, full provider metadata drift and independent Worker lock bindings. The opt-in test/external-sdk/check.py uses explicitly supplied host interpreters and checks all three SDKs, i64 extremes, JSON budgets, health/errors and cooperative/noncooperative cancellation; it does not prove managed runtimes or no-host distribution.

Registry tests exercise real provider metadata through an injected bounded transport, candidate/dependency/version conflicts and runtime identity; owned loopback HTTP tests also cover the Go ZIP redirect and rejection-before-request boundary. They are not public-network or signed-release acceptance. external_workers tests cover Python isolation, ESM/CommonJS binding, wheel/npm rules, path/file conflicts and no-host lookup. Explicit host-copy subprocess cases remain ignored by default. Shared service tests cover real UID separation (opt-in root-owned fixture), bad/truncated concurrent uploads, entry/byte quotas, summary-vs-integrity semantics and owner maintenance. Native tests assert resource-independent generated source size, forged-digest rejection and actual packaged execution; tests derived solely from emit strings do not prove launch.

Durable Worker Lifecycle

The compiler owns Job service startup. Both application backends validate settings and selected runtime.mode before preparing service databases or listening/claiming. API and worker roots stay in one binary; api/worker/all gate only the services, not source reachability. Starting a Job service requires runtime settings; CMD and management commands do not validate or start unrelated services. An enqueue-only CMD may use one database connection without HTTP/worker configuration. API-only applications use api/30000 ms defaults when omitted. Worker pools reserve at least one connection beyond worker slots for queue control and lease renewals. SQLite additionally requires lease_ms > Job timeout_ms before database preparation, because a spare connection does not bypass its single-writer lock.

Tokio's existing signal feature owns SIGTERM/Ctrl-C registration; do not install handlers with unsafe code or detach signal tasks. Lifecycle supervises the application root with the existing task owner. Shutdown stops API accept and Job claim, drains within one deadline, then cancellation joins descendants before database shutdown and log flush. Generated normal/test entries close databases on success and application/startup failure. Worker work and heartbeat use registered tasks, bounded active slots and fencing tokens; cancellation leaves the lease for recovery.

Test-only dever.test.advance_clock and bounded drain_jobs share production clock/store/dispatch logic. Each case has an independent clock/database/fake closure; empty drain needs no database. No test may start API/worker services, select a production Adapter or use deployment configuration. Job test roots must include enqueued handlers even though enqueue is not a synchronous dependency edge.

LLVM Job/Test validation selects llvm_job_test_source and the Job cases in llvm_api_source, plus affected original durable_jobs contracts. Check six-target object emission separately from actual archive execution. Exercise single-suite case isolation, structured failure locations, fake-only external calls, virtual delay/retry/cron, atomic enqueue/handler rollback, timeout child drain and repeated-root allocation balance. Real owned API/worker cases verify tenant queue placement and current permissions after enqueue. Revocation fixtures keep stored references structurally valid; malformed storage ownership is an earlier fail-closed store error, not a successful dispatch-time authorization test.

LLVM external validation selects llvm_external_source, the original external_component/external_resources tests and the existing fake-only Job/Test case. Verify six-target metadata/object layouts separately from actual runtime execution. Run real fixture processes for typed values/errors, malformed payloads, bad Setting/handshake, cancellation, and strict warmup + 64 repeated roots. Relocate only the linked executable and settings before checking embedded exec and managed launch manifests with an empty environment; synthetic managed launch fixtures are not real Python/npm/Go SDK or formal release acceptance. Retain resource SHA verification on every root/restart. Linux allocation ledgers must wrap realpath(NULL) as an owned allocation: glibc's internal malloc bypasses executable linker wrapping, while Rust's later free is wrapped. Account for that owner without relaxing balance or increasing warmups.

Runtime config owns the shared Job bounds: timeout <= 3,600,000 ms and lease in 100..7,200,000 ms. Tests use the maximum lease so every legal timeout fits SQLite without bypassing production policy validation.

Ordinary Linux commands use workers/command.rs with the shared workers/elf.rs dependency-closure checker. Prepare the domain-owned ELF and flat adjacent lib/ from the project or locked Package; never scan host libraries or require a Lib lock for command-only projects. Validate target, GNU interpreter, recursive DT_NEEDED, SONAME, symbol versions and loader hooks. RPATH/RUNPATH must remain in the packaged program tree and private libraries cannot shadow signed process runtime libraries. The launch manifest names the actual executable; dever-process::Launch executes it directly through the kernel, with private Worker/runtime library paths plus inherited driver library paths. The deployment container supplies the matching Linux/glibc OS ABI. Do not launch language executables through the GNU loader: Node/Rust self-executable discovery and subprocess spawning would resolve the loader instead. Signed process-runtime libraries remain build-time target dependency inputs; do not inject their old libc under a different container loader. User argv is appended literally, not interpreted as shell syntax. Commands use dever-command-launch-v1 and the commands/ tree under the existing verified bundle owner.

Command limits are adapter.<port>.command.timeout_ms (default 30000, 1..3600000) and output_limit (default 1048576, 1..8388608 combined stdout/stderr); stdin is bounded at 8388608 bytes and argv at 65536 including NUL terminators, with embedded NUL rejected. A call owns one process, closes absent stdin, drains both output pipes concurrently and never replays. Invalid resources and OS spawn errors are runtime faults. A successfully started executable or loader returns its actual exit status; do not infer a special failure from stderr or a reserved exit code. Invocation shutdown and caller cancellation terminate the owned process group and await the leader; this is not containment for detached sessions. Queued cancellation has no child to drain and must not wait behind an unrelated active call. Ordinary application tests remain fake-only. Focused evidence belongs to external_command, command cases in external_workers/llvm_external_source, and the opt-in signed native-release command acceptance; physical ARM execution must not be inferred from cross-target metadata tests.

Command and Worker cleanup use the same pidfd-pinned process-group owner. Kill the group before reaping its leader so a reused PID cannot target unrelated processes. Test timeout, cancellation, explicit shutdown, root-scope close and successful leader exit with a descendant still holding output pipes. Invalid executable input must fail before any invocation; static checks and ignored fixtures are not execution evidence.

7. Wrong vs Correct

Wrong: update a skill symlink separately after changing the active core, treat a cached older version as a successful failed update, or delete a public output tree after a publication race. Correct: resolve core and signed skill from one active journal, return the original download failure, and publish exclusively owned staging with NOREPLACE.

Test wrong: filter the checked source set, use blocking Command.output without a deadline, or reap every child after killing a test. Correct: select stable case indices after full checking, capture in the case-owned directory, enforce the deadline and reap only its retained process group.

Installer wrong: recreate a separate skill installer or generator, take its key from the downloaded package, or assume changing Git remote changes an old launcher. Correct: maintain the sole root install source with its independent key, verify its actual Bash behavior, and migrate changed stable bootstrap binaries through a newly built signed release.

Cross-target wrong: check ELF headers but use the host loader name to assign executable mode. Correct: validate target architecture and independently preserve each declared executable's mode across signed packaging, embedding and extraction; exercise the resulting Worker bootstrap under the target kernel.

Native authoring wrong: discover a compiler in PATH while signing, overwrite a completed release, or strip a hard-linked archive in place. Correct: separate the recorded source-build recipe from deterministic copy/verify/sign, preserve link symbols, and publish a wholly new directory with the existing signed installation contract.

Wrong: reuse shared-file validation for an owner-only lock, require 0700 on public state ancestors, unlink a held advisory lock, or trust a successful test on a host with LLVM installed. Correct: validate each owner/permission contract separately, retain the lock inode, keep source staging private, and inspect final dynamic dependencies.

Wrong: export a Rust aggregate directly, use C++ free on Rust ABI buffers or ship the LLVM author SDK inside the application runtime. Correct: fixed scalar arguments and explicit output pointers, one canonical header, private allocator-matched exports and separate runtime-abi/embedded features; validate formal target packs separately.

Managed ABI wrong: trust a copied byte buffer as an owned typed value, create per-caller descriptor identities or read an optional out row regardless of presence. Correct: one process-static descriptor per concrete type, typed lifecycle callbacks over aligned uninitialized storage, explicit receiver consumption and full-row nullable extraction.

Async ABI wrong: use regular 0/1/2 status checks for Pending/Ready, raw-copy fault payload padding, free normal guards twice during final destroy, or drop the runtime's input inside SyncFunction.invoke. Correct: explicit async status mapping, typed nominal move/drop with source zeroing, initial/pending reverse cleanup versus final frame-only free, and runtime-owned input release after invoke or cancellation.

HTTP/2 wrong: spawn Hyper futures outside CURRENT_SCOPE, let a body-reset write error stop the whole server, or retry every GOAWAY error. Correct: register protocol tasks under a connection owner, distinguish transport cancellation before propagating handler faults, and only requeue a structurally returned unsent request within its original deadline.

Wrong: formatter reorders effectful constructors; code generation moves resource aliases early; composite rendering first collects every child String; the runtime caps one-shot reads to an arbitrary internal chunk; a benchmark times unequal Decimal initial representations.

Correct: reuse AST/HIR/runtime owners, preserve source ordering and lifetime, consume only disposable native bindings, stream rendering into one output String, keep read size under caller control, and match both semantics and representation before measuring.

Markdown wrong: regex-extract every fence or format all extracted code as one document. Correct: identify program ranges through Markdown parsing, preserve original positions, and reuse the existing Dever pipeline and formatter within those ranges.

Component wrong: use shell command strings, PATH, application environment variables, detached tasks, automatic call replay, a second JSON parser, or a per-ecosystem supervisor. Component correct: resolve one compiler-owned relative entry, clear inherited environment, reuse bounded wire and Scope owners, preserve the first runtime fault, and explicitly kill/wait on every abnormal exit.