A dependency-isolated capability-composition runtime: heterogeneous tools run in their own environments behind a uniform HTTP/JSON boundary; the host composes them into workflows with resource-aware scheduling and threads provenance through a context graph.
cjm_substratecjm_substrate.bootstrap— One-call factory that assembles a CapabilityManager + JobQueue + capabilitycjm_substrate.cli— CLI tool for declarative capability management.cjm_substrate.corecjm_substrate.core._telemetry— Shared GPU/CPU attribution helpers used by both JobQueue._sample_resource_snapshot (CR-6 Stage 3) and CapabilityManager._record_sample_safe (CR-7).cjm_substrate.core.adapter— The typed-task half of the capability-unit fracture (pass-2 Thread 3) —cjm_substrate.core.adapter_manifest— The ADAPTER unit's registration manifest + the surface-based compatibility matcher (CR-17 pt 2, stage 4). Pass-2 Thread 3: registration/discovery = per-unit manifests generated in-env and found by discover_manifests(); compatibility is DERIVED, not declared — the capability records only its structural surface, the adapter declares its protocol (recorded here as member names + parameter lists), and the substrate matches manifest-vs-manifest. Works against UNLOADED capabilities with zero protocol imports host-side.cjm_substrate.core.capability— The tool-capability interface — the manage-the-tool half of the capability-unit fracture (pass-2 Thread 3): identity, lifecycle, config, cancellation, and observability for a tool running in a worker process, serving both concrete capabilities (in workers) and remote proxies (in the host). The task channel is deliberately NOT here: typed task contracts live on task adapters (core.adapter + the per-task cjm--adapter-interface libraries) and results cross the worker boundary through the typed wire layer (core.wire); execute_stream's transitional default remains for fused-era capabilities only. Also home to the CR-12 worker-env contract (EnvVarSpec + the Q1-A template vocabulary), the SG-44/T28 action-dispatcher convention, and the pass-2 Thread-3 structural-surface derivation.cjm_substrate.core.config— Project-level configuration for paths, runtime settings, and environment management.cjm_substrate.core.config_store— Persistent storage for per-instance capability configuration (config + enabled flag + worker-env override), keyed by instance_id.cjm_substrate.core.diagnostics_store— CR-14 (stage 7): the disposable diagnostic-narrative class. Worker-writtencjm_substrate.core.empirical_store— Persistent store for empirically-observed resource usage per (instance_id, config_hash) pair. CR-7's data foundation — record_sample is called from CapabilityManager.execute_capability* finally blocks; aggregates feed eviction-candidate selection + future UI hints + cost-aware retry decisions.cjm_substrate.core.errors— Typed exception hierarchy + JobError dataclass + default classification of bare Python exceptions. The substrate's CR-5 implementation per the 2026-05-19 substrate audit.cjm_substrate.core.journal_store— CR-14 (stage 7): the durable account-of-action. One substrate-derived,cjm_substrate.core.manager— Capability discovery, loading, and lifecycle management via process isolation.cjm_substrate.core.manifest_format— Typed parser + writer for the nested v2.0 manifest layout (2026-05-19 substrate audit, CR-8).cjm_substrate.core.metadata— Data structures for capability metadata.cjm_substrate.core.platform— Cross-platform utilities for process management, path handling, and system detection (Linux, macOS, Windows).cjm_substrate.core.ports— Capability compositions as DAGs of invocation nodes with typed input/outputcjm_substrate.core.proxy— Host-side bridge to isolated capability workers: RemoteCapabilityProxy implements ToolCapability but forwards every call over HTTP to a Universal Worker subprocess running in the capability's own environment. Owns worker process management (spawn with the manifest's python_path, SG-4 parent-bound listening socket / FD inheritance, suicide-pact --ppid, CR-14 stream pump + lifecycle journaling), zero-copy input transfer (FileBackedDTO -> temp files), the typed error contracts crossing the wire (409 -> CapabilityCancelledError; _job_error 500 bodies and stream terminal chunks -> typed exceptions; CR-7 Track A worker-death classification), and a dual sync/async interface for scripts and FastHTML hosts.cjm_substrate.core.queue— Resource-aware multi-lane job queue for capability execution (stage 3 / CR-16 rework).cjm_substrate.core.scheduling— Resource scheduling policies for capability execution.cjm_substrate.core.secret_store— CR-12: project-local secret storage for API-based capabilities (file-backed, 0600).cjm_substrate.core.wire— Typed data transfer at the worker boundary — the zero-copy FileBackedDTOcjm_substrate.core.worker— FastAPI server that runs inside isolated capability environments (the Universal Worker): dynamically loads the capability class named on the CLI, exposes the HTTP lifecycle / execute / task / monitor surface for the proxy, monitors the parent process (the suicide-pact watchdog prevents zombie workers), and reports process-subtree telemetry for resource-scheduling decisions. This module is a process ENTRYPOINT (SG-39): host code never imports it.cjm_substrate.core.workspace— Workspace resolution: the marker-rooted directory that owns a pipeline's local artifacts (runs, graph data, substrate stores, TUI sidecars).cjm_substrate.utilscjm_substrate.utils.cache_paths— Per-(input-content, config) deterministic cache directories for capability outputs. Same (input content, action, config) always resolves to the same directory; any change to input content OR config produces a different one — no silent overwrites, no stale-artifact accumulation, and chained invalidation for capability sequences (see the cache-paths-design-provenance note for the ffmpeg-bug origin story).cjm_substrate.utils.hashing— Shared cryptographic hashing primitives for content integrity verification.cjm_substrate.utils.sidecar— JSON sidecar for shell view-state — settings and bookmarks that persistcjm_substrate.utils.validation— Validation helpers for capability configuration dataclasses.
Pipelineclass — Assembled substrate stack: manager + queue + capability bindings.create_pipelinefunction — Assemble a CapabilityManager + JobQueue + capability bindings in one call.
generate_adapter_manifestfunction — CR-17 pt 2 (stage 4): introspect a task-adapter impl in-env and write its adapter manifest.install_allfunction — Install and register all capabilities defined in capabilities.yaml.list_capabilitiesfunction — List installed capabilities from manifest directory.list_secretsfunction — List the secret KEY NAMES stored for a capability — never the values (CR-12).logs_commandfunction — Tail / follow the observability stores (CR-14).mainfunction — cjm-substrate CLI for managing isolated capability environments.regenerate_manifestfunction — Re-run introspection for an installed capability and rewrite its manifest.remove_capabilityfunction — Remove a capability's manifest and conda environment.retention_commandfunction — Apply the diagnostics retention policy now (CR-14).run_cmdfunction — Run a shell command and stream output.set_secretfunction — Store a capability secret in the project-local SecretStore (CR-12).setup_hostfunction — Install interface libraries in the current Python environment.setup_runtimefunction — Download and setup micromamba runtime for project-local mode.validate_filefunction — SG-6 + T23: validate a manifest / capabilities.yaml / capability source.workspace_doctor_cmdfunction — Run workspace integrity checks; exits non-zero when any check warns.workspace_initfunction — Declare a workspace: write the marker + create the conventional layout (idempotent; an existing marker is left untouched).
attribute_gpu_to_worker_subtreefunction — Attribute GPU memory across the worker's process subtree.
TaskAdapterclass — Base for task adapters — the typed-task half of the capability-unit
AdapterManifestclass — A discovered ADAPTER unit (CR-17 pt 2) — the registration record for oneadapter_manifest_from_dictfunction — Reconstruct anAdapterManifestfrom its on-disk JSON shape.is_adapter_manifestfunction — Route a manifest file by theunitdiscriminator (capability manifestsmatch_protocol_against_surfacefunction — Surface-based compatibility (pass-2 Thread 3) — host-side, manifest-vs-
ConfigOptionclass — CR-11: one live option for a dynamic config field, with optional metadata.EnvVarSpecclass — CR-12: one entry of a capability's spawn-time worker-environment contract.FieldOptionsclass — CR-11: the live option domain for one dynamic config field.ToolCapabilityclass — Tool-capability interface: manage the tool/worker — identity, lifecycle,capability_actionfunction — Marker decorator tagging a capability method as the handler foraction_name.collect_capability_actionsfunction — Collect action names from@capability_action-decorated methods oncls.derive_structural_surfacefunction — Record a capability class's structural surface by pure self-introspection.expand_worker_env_templatefunction — Substitute${VAR}placeholders intemplateusingplaceholders.template_check_placeholdersfunction — Return the set of placeholder names referenced by a worker-env template.
CJMConfigclass — Main configuration for cjm-substrate.CondaTypeclass — Type of conda implementation to use.RuntimeConfigclass — Runtime environment configuration.RuntimeModeclass — Runtime mode for the capability system.SubstrateConfigclass — Substrate behavior toggles.get_configfunction — Get current config (loads defaults if not set).load_configfunction — Load config with layered resolution (CLI > env vars > yaml > workspace > defaults).reset_configfunction — Reset to unloaded state (for testing).set_configfunction — Set current config (called by CLI callback).
CapabilityConfigRecordclass — Persisted state for a capability INSTANCE: config + enabled flag + worker-env override.CapabilityConfigStoreclass — Protocol for persisting per-instanceCapabilityConfigRecordacross sessions.LocalCapabilityConfigStoreclass — SQLite-backed default implementation ofCapabilityConfigStore.deletefunction — Remove the record for an instance.getfunction — Fetch the record for an instance.list_allfunction — Return all stored records keyed by instance_id.setfunction — Persist a record. Stampsupdated_atto the current time.
DiagnosticRecordclass — One structured worker log record (CR-14 diagnostics class).DiagnosticsLogHandlerclass — Worker-side logging handler writingDiagnosticRecords (CR-14).DiagnosticsStoreclass — Protocol for the disposable diagnostic-narrative store (CR-14).LocalDiagnosticsStoreclass — SQLite-backed defaultDiagnosticsStore(CR-14).StreamChunkclass — One raw stdout/stderr line the host pump captured (death-rattle floor).append_chunkfunction — Persist one raw stream line.append_recordfunction — Persist one structured record.apply_retentionfunction — Retention as a QUERY (the CR-14 reframe's mechanical payoff).install_worker_diagnosticsfunction — Configure worker-process logging (replaces the oldbasicConfig).normalize_stream_linefunction — Collapse CR progress frames to the final frame; drop empty results.query_chunksfunction — Raw stream read, session-scoped.query_recordsfunction — Filtered structured-record read.
EmpiricalResourceRecordclass — Aggregated empirical resource profile for a (instance_id, config_hash) pair.EmpiricalResourceStoreclass — Protocol for persisting empirically-observed resource usage.LocalEmpiricalResourceStoreclass — SQLite-backed default implementation ofEmpiricalResourceStore.ResourceSampleclass — Single observation captured after an execute call completes.compute_config_hashfunction — CR-7: hash a capability instance's effective config for empirical-record keying.
CapabilityCancelledErrorclass — Cooperative cancellation signal raised fromToolCapability.check_cancel().CapabilityConfigErrorclass — Unknown / invalid keys in a config dict against a capability's config schema.CapabilityDisabledErrorclass — JobQueue / execute_capability rejected: the capability is currently disabled.CapabilityErrorclass — Base for substrate-recognized capability exceptions.CapabilityFatalErrorclass — Bug / irrecoverable state. The capability cannot complete this job; retrying won't help.CapabilityInputErrorclass — User-fixable error: bad config, invalid argument, missing file.CapabilityNotLoadedErrorclass — Caller submitted to a capability that was never loaded.CapabilityResourceErrorclass — Resource exhaustion: GPU VRAM, system RAM, disk full.CapabilityTimeoutErrorclass — A per-job timeout fired before the capability finished.CapabilityTransientErrorclass — Temporary failure: timeout, network blip, brief resource contention.JobErrorclass — Structured failure summary recorded on a completed Job.ResourceShortfallclass — Quantitative gap between what a capability needed and what was available.TracebackPolicyclass — How much exception detail the substrate records on a JobError.WorkerOOMErrorclass — The worker subprocess died with a kill-signal during an active execute call.classify_exceptionfunction — Return the substrate category for any exception.map_bare_exception_to_job_errorfunction — Convert any exception into a structuredJobError.
JournalEventclass — One durable observability record (CR-14).JournalStoreclass — Protocol for the durable account-of-action (CR-14).LocalJournalStoreclass — SQLite-backed defaultJournalStore(CR-14).SubstrateEventTypeclass — Journal vocabulary beyond the job-scopedJobEventTypeset (CR-14).appendfunction — Persist one event; sets and returnsevent.seq.countfunction — Total journal rows (volume regression checks).queryfunction — Filtered read; all filters AND-combined.terminal_state_eventsfunction — The durable job history (_historymigration rider): terminal
CapabilityBindingclass — Pre-bound view of a single capability through a shared CapabilityManager.CapabilityManagerclass — Manages capability discovery, loading, and lifecycle via process isolation.
CodeSectionclass — Code-derived facts refreshed bycjm-ctl regenerate-manifest.DriftTrackingclass — Witness hashes for drift detection.InstallSectionclass — Deployment-specific facts populated at install time.ManifestV2class — Top-level v2.0 manifest with four named sections plusformat_version.compute_config_schema_hashfunction — Hash a JSON Schema with stable canonicalization.compute_structural_surface_hashfunction — Hash a structural surface with stable canonicalization.load_manifestfunction — Load a manifest file and return a typedManifestV2.manifest_to_dictfunction — Serialize aManifestV2to a v2.0 dict.write_manifestfunction — Serialize aManifestV2to disk in v2.0 nested layout (indent=2).
CapabilityInstanceclass — Per-instance runtime state for a loaded capability (CR-10 multi-instance).CapabilityLoadSpecclass — One entry inCapabilityManager.load_capabilities_concurrent's batch input (CR-10).CapabilityMetaclass — Metadata about a capability.ResourceRequirementsclass — Binary hard-facts about what a capability needs to run (Phase 5a).
build_conda_commandfunction — Build a complete conda/mamba/micromamba command.conda_env_existsfunction — Check if a conda environment exists (cross-platform).download_micromambafunction — Download and extract micromamba binary to the specified path.ensure_runtime_availablefunction — Check if the configured conda/micromamba runtime is available.get_conda_commandfunction — Get the conda/mamba/micromamba base command with prefix args for local mode.get_current_platformfunction — Get current platform string for manifest filtering.get_micromamba_binary_pathfunction — Get the configured micromamba binary path for the current platform.get_micromamba_download_urlfunction — Get the micromamba download URL for the specified or current platform.get_popen_isolation_kwargsfunction — Return kwargs for process isolation in subprocess.Popen.get_python_in_envfunction — Get the Python executable path for a conda environment.is_apple_siliconfunction — Check if running on Apple Silicon Mac (for MPS detection).is_linuxfunction — Check if running on Linux.is_macosfunction — Check if running on macOS.is_windowsfunction — Check if running on Windows.run_shell_commandfunction — Run a shell command cross-platform.terminate_processfunction — Terminate a subprocess + its entire process subtree (grandchildren, etc).terminate_selffunction — Terminate the current process (for worker suicide pact).
Compositionclass — A static DAG of capability-invocation nodes, submitted as one unit.CompositionBindingErrorclass — AnOutputRefcould not be resolved against the producer's recordedCompositionNodeclass — One capability invocation in a composition.CompositionNodeRunclass — Live state of one node within a composition run.CompositionRunclass — Tracks a submitted composition through execution (lives inCompositionValidationErrorclass — A composition failed submit-time validation (duplicate ids, unresolvedNodeStateclass — State of one composition node (and, for the terminal subset, of aOutputRefclass — Binding marker: this kwarg's value comes from an upstream node's result.extract_output_fieldfunction — Extract a field from an upstream result for binding into a kwarg.new_composition_runfunction — Validate a composition and build its run record.resolve_node_kwargsfunction — Materialize a node's kwargs by resolving itsOutputRefmarkers.validate_compositionfunction — Validate a composition and return its derived dependency map.
RemoteCapabilityProxyclass — Proxy that forwards capability calls to an isolated Worker subprocess.
CancelPhaseclass — Phase of a cancellation in progress (CR-6 + CR-4 pairing).Jobclass — A queued capability execution request (CR-6 reshape; stage-3 compositionJobEventclass — A push-based job event (CR-6; stage-3 composition tags).JobEventTypeclass — Push-based job event types (CR-6; stage-3 composition rework; CR-14JobQueueclass — Resource-aware multi-lane job queue with journal-primary observabilityJobQueueDependenciesclass — Substrate dependencies the JobQueue requires (CR-6 + stage 3).JobStatusclass — Status of a job in the queue.QueueStatsclass — Aggregate counts returned byJobQueue.get_stats()(CR-6).ResourceSnapshotclass — Point-in-time resource usage for one job (CR-6 Stage 3).
PermissiveSchedulerclass — Scheduler that allows all executions (Default / Dev Mode).ResourceSchedulerclass — Abstract base class for resource allocation policies.
LocalSecretStoreclass — File-backed defaultSecretStore(0600 JSON undersecrets_dir).SecretStoreclass — Protocol for resolving per-capability secrets (API keys, tokens).delete_secretfunction — Remove a secret, pruning now-empty capability/scope containers.get_secretfunction — Resolve a secret value.list_keysfunction — Return the names of secrets stored for a capability (never the values).set_secretfunction — Persist a secret value.
CallEnvelopeclass — Substrate-owned per-call identity + control block (CR-14 / CR-15).FileBackedDTOclass — Protocol for Data Transfer Objects that serialize to disk for zero-copy transfer.begin_account_capturefunction — Start a fresh account list for the current call span (worker endpointdrain_accountsfunction — Return + clear the current span's recorded accounts ([] outside a spanflat_from_dictfunction — Default reconstruction for FLAT wire DTOs (no nested-DTO fields).get_call_envelopefunction — The current call envelope, or None outside any call span.record_accountfunction — Record one substrate-family account for the current call span.reset_call_envelopefunction — Restore the prior envelope (always pair withset_call_envelopein finally).set_call_envelopefunction — Set the current call envelope; returns the token forreset_call_envelope.wire_decodefunction — Reconstruct a typed result from its tagged envelope (host side).wire_encodefunction — Wrap a registered wire DTO in its tagged envelope (worker side).wire_typefunction — Register a dataclass as a typed wire DTO underkind.
EnhancedJSONEncoderclass — JSON encoder that handles dataclasses and other common types.create_appfunction — Create FastAPI app that hosts the specified capability.parent_monitorfunction — Monitor parent process and terminate self if parent dies.run_workerfunction — CLI entry point for running the worker.
Workspaceclass — A resolved workspace: the marker-rooted directory owning pipeline artifacts.WorkspaceErrorclass — A workspace was named (flag or env) but could not be resolved.find_workspace_rootfunction — Upward walk — the git-style discovery that makes workspace identity launch-cwd-independent.init_workspacefunction — Declare a workspace: write the marker + create the conventional layout.relativize_recordedfunction — Writer half of the 5daadfc4 recording contract (rung f).resolve_recorded_treefunction — Reader half of the recording contract (rung f; anchor rule ratified 2026-07-19).resolve_workspacefunction — Resolve the active workspace: explicit flag > CJM_WORKSPACE env > upward walk > None.workspace_doctorfunction — Integrity-check skeleton for the workspace doctor verb.
cache_dir_for_configfunction — Return (and optionally create) a per-(input-content, config) cache directory.list_cache_entriesfunction — Enumerate all per-config cache directories for a given (input, action).prune_cache_for_inputfunction — Delete per-config cache directories for(input, action), optionally
hash_bytesfunction — Compute a hash of byte content.hash_dict_canonicalfunction — Hash a dict via canonical JSON encoding.hash_filefunction — Stream-hash a file without loading it entirely into memory.verify_hashfunction — Verify content against an expected hash string.
SidecarStateclass — One JSON sidecar file: never-raise load, merge-on-save, best-effort write.
config_to_dictfunction — Convert a configuration dataclass instance to a dictionary.dataclass_to_jsonschemafunction — Convert a dataclass to a JSON schema for form generation.dict_to_configfunction — Create a configuration dataclass instance from a dictionary.extract_defaultsfunction — Extract default values from a configuration dataclass type.validate_configfunction — Validate all fields in a configuration dataclass against their metadata constraints.validate_field_valuefunction — Validate a value against field metadata constraints.
Depends on: fastapi, fastcore, httpx, psutil, pyyaml, typer, uvicorn
Used by: cjm-capability-pyannote, cjm-capability-pysbd, cjm-context-graph-projection, cjm-graph-storage-adapter-interface, cjm-markdown-decompose-core, cjm-sentence-segmentation-adapter-interface, cjm-speaker-diarization-adapter-interface, cjm-transcript-correction-core, cjm-transcript-correction-qt, cjm-transcript-correction-tui, cjm-transcript-decomp-core, cjm-transcript-decomp-qt, cjm-transcript-decomp-tui, cjm-transcription-core, cjm-transcription-qt, cjm-transcription-tui, cjm-vad-adapter-interface, cjm-workflow-hub-qt, cjm-workflow-hub-tui