Skip to content

Phase 1: Extension SDK, registry, discovery, and compatibility contract #113

Closed

Description

@suraj-ranganath

Summary

Define the stable EEGPrep extension contract. This phase creates the core SDK and registry but does not need to fully wire every GUI/menu/runtime surface yet.

The design should preserve EEGLAB plugin familiarity while using Python-native packaging. EEGLAB's eegplugin_*.m functions mutate menus and MATLAB paths; EEGPrep should instead discover installed Python packages through entry points and register declarative extension specs.

Key Work

  • Add an extension SDK module, likely under src/eegprep/functions/adminfunc/ or a small top-level package module such as src/eegprep/extensions.py if public API clarity warrants it.
  • Define ExtensionSpec with fields for name, display name, version, API version, package name, entry point name, source type, description, docs URL, maintainer, capabilities, dependencies, menus, actions, pop_* functions, help resources, and package-data resources.
  • Define a registry that can discover entry points from importlib.metadata.entry_points(group="eegprep.extensions").
  • Validate extension specs before activating them.
  • Add compatibility checks for EEGPrep version requirements and extension API version.
  • Support lazy loading so heavy extension modules do not slow GUI startup.
  • Support enable/disable state without hidden globals. Store only minimal user preferences in an explicit config location or session-owned state.
  • Define status values for bundled, installed, curated, disabled, incompatible, failed import, invalid spec, missing dependency, and unknown.
  • Isolate failures: one broken extension must not crash EEGPrep startup.
  • Keep runtime code independent of src/eegprep/eeglab.

Edge Cases To Cover

  • Duplicate extension names.
  • Duplicate action names or pop_* function names.
  • Entry point imports but returns the wrong type.
  • Extension requires a newer EEGPrep or unsupported API version.
  • Extension import raises an exception.
  • Extension metadata is valid but a lazy action import later fails.
  • Extension is installed but disabled.
  • Extension package data/help resource is missing.
  • No extensions installed.
  • --no-plugins / include_plugins=False keeps behavior predictable.

Acceptance Criteria

  • EEGPrep can discover extension entry points without importing heavy action modules eagerly.
  • Registry returns a deterministic list of extension records and statuses.
  • Invalid/failing extensions are visible in registry status and logged without crashing.
  • The API is documented enough that later phases can build against it without guessing.
  • Existing bundled plugin inventory behavior remains stable.
  • Unit tests cover discovery, validation, status, duplicate handling, lazy loading, and failure isolation.
  • uv run --no-sync ruff check ., uv run --no-sync ruff format --check ., uv run --no-sync ty check, and focused pytest pass.

/goal Prompt

/goal Implement EEGPrep's external extension SDK, registry, entry-point discovery, lazy loading, compatibility checks, and status model. Use EEGLAB's eegplugin_* startup model only as a behavior reference, not as a Python implementation pattern. Preserve existing bundled plugin behavior, isolate broken extensions, avoid runtime EEGLAB dependencies, add thorough tests for edge cases, and keep lint/type/focused tests green.

Activity

  1. added
    phase
    on Jun 2, 2026
  2. claude commented on Jun 2, 2026

    @claude
    Contributor

    🤖 Plan:

    Scope: Phase 1 is a new multi-module SDK + registry with discovery, validation, status, lazy loading, and tests. This is well over the 100-line bug-fix bar, so no PR yet - design first.

    Research

    EEGPrep already ships an EEGLAB-flavored "plugin inventory" but it is a hard-coded tuple plus a read-only Qt dialog; there is no discovery, no entry-point group, no API/compat version, no per-extension lifecycle, and the GUI hard-wires each bundled plugin's menu by name. The Phase 1 contract has to replace the static inventory with a registry that bundled and external packages can both feed, while keeping the existing GUI/console flows working through the same data shape ({plugin, name, version, status, source, menu, ...} already consumed by plugin_menu, plugin_status, session.PLUGINLIST).

    Key constraints from AGENTS.md: no globals for processing, runtime must not depend on src/eegprep/eeglab, GUI/console state must flow through EEGPrepSession, help text must be EEGPrep-owned Markdown under resources/help/, and pop_* functions must remain return_com-compatible. The new SDK has to honor all of these.

    Relevant code

    Proposed Design

    1. Public SDK module

    Add src/eegprep/extensions.py as the only public import path; everything in this module is the Phase 1 contract. Internal helpers (discovery walk, validation, status enum, defaults) live in src/eegprep/functions/adminfunc/extensions/ so the public surface stays small. Re-export the same names through eegprep.__init__ via the existing lazy-export table.

    Public names:

    • ExtensionSpec (frozen @dataclass)
    • ExtensionRecord (frozen @dataclass - runtime view: spec + status + load error + source)
    • ExtensionStatus (StrEnum)
    • EEGPREP_EXTENSION_API_VERSION (int constant, 1)
    • EEGPREP_EXTENSION_ENTRY_GROUP = "eegprep.extensions"
    • ExtensionRegistry (class; iterable, indexable by name)
    • get_registry() (returns the process-local registry; first call performs discovery)
    • discover_extensions(*, include_external=True, include_bundled=True) (pure function - does not mutate the cached registry; useful for tests and the Extension Manager refresh)
    • register_bundled(spec) (only called from bundled plugin __init__ modules; not part of the external author API but needed so Phase 2 can migrate firfilt / ICLabel / dipfit / EEG_BIDS / clean_rawdata off the hard-coded tuple)
    • ExtensionError, InvalidExtensionSpec, IncompatibleExtension exception types

    2. ExtensionSpec fields

    @dataclass(frozen=True)
    class ExtensionSpec:
        name: str                              # canonical machine id, e.g. "firfilt"
        display_name: str                      # GUI label
        version: str                           # PEP 440 string
        api_version: int                       # which EEGPREP_EXTENSION_API_VERSION it targets
        eegprep_requires: str = ""             # PEP 440 specifier, e.g. ">=0.2,<0.4"
        package: str = ""                      # importable distribution package
        entry_point: str = ""                  # "pkg.module:spec_factory"
        source: ExtensionSource = ExtensionSource.EXTERNAL  # bundled | external | curated
        description: str = ""
        docs_url: str = ""
        maintainer: str = ""
        capabilities: tuple[str, ...] = ()     # free-form tags ("filter", "ica", ...)
        requires: tuple[str, ...] = ()         # other extension names this depends on
        menus: tuple[MenuContribution, ...] = ()
        actions: tuple[ActionContribution, ...] = ()
        pop_functions: tuple[str, ...] = ()    # "eegprep.plugins.firfilt.pop_firws:pop_firws"
        help_resources: tuple[HelpResource, ...] = ()
        package_data: tuple[str, ...] = ()     # importlib.resources paths

    MenuContribution reuses MenuItemSpec plus an insert_after anchor (e.g. "pop_eegplot:data") so Phase 2 can drop the hand-coded _insert_*_plugins helpers. ActionContribution carries name, dotted_target, and allows_multiple. HelpResource carries function_name and package_resource (importlib.resources ref, never a filesystem path under src/eegprep/eeglab).

    Action / pop-function / help references are stored as strings, never resolved at registration time - that is what gives us lazy loading.

    3. Discovery

    def _discover_external() -> Iterable[ExtensionSpec]:
        for ep in importlib.metadata.entry_points(group=EEGPREP_EXTENSION_ENTRY_GROUP):
            try:
                factory = ep.load()
                spec = factory() if callable(factory) else factory
            except Exception as exc:
                yield _failed_spec(ep, exc); continue
            yield from _coerce_specs(spec, ep)
    • Bundled plugins are registered by calling register_bundled(spec) from the existing plugins/*/__init__.py modules. Phase 1 lands the API and (to keep the change reviewable) provides a bridge that synthesizes ExtensionSpec instances from the existing _BUNDLED_PLUGINS tuple; Phase 2 migrates each bundled plugin to call register_bundled directly. bundled_plugins() stays as a thin shim around the registry so the old call sites and tests remain green.
    • External discovery uses importlib.metadata.entry_points(group="eegprep.extensions"). We do not import the action / pop modules at discovery; only the entry-point factory is imported, and it is expected to return a declarative ExtensionSpec.
    • --no-plugins / include_plugins=False short-circuits external discovery only; bundled extensions still register.

    4. Status model

    class ExtensionStatus(StrEnum):
        BUNDLED = "bundled"
        INSTALLED = "installed"
        CURATED = "curated"             # known in catalog, not installed
        DISABLED = "disabled"
        INCOMPATIBLE = "incompatible"   # api_version or eegprep_requires mismatch
        FAILED_IMPORT = "failed_import"
        INVALID_SPEC = "invalid_spec"
        MISSING_DEPENDENCY = "missing_dependency"
        UNKNOWN = "unknown"

    ExtensionRecord wraps the spec with status, load_error (str), source (bundled / external / curated), and installed (bool). The existing plugin_status() keeps its tuple return contract by translating these to 1/0 for backwards compatibility with EEGLAB-shaped callers.

    5. Validation rules (raised as InvalidExtensionSpec or surfaced as INVALID_SPEC)

    • name matches ^[a-z][a-z0-9_]*$; version parses as PEP 440.
    • api_version is an int and <= EEGPREP_EXTENSION_API_VERSION.
    • eegprep_requires (if set) parses as a PEP 440 specifier and matches eegprep.__version__.
    • Duplicate extension name across entry points -> first wins, later ones recorded with status=INVALID_SPEC and a deterministic load_error.
    • Duplicate action.name or pop_function name across extensions -> both extensions marked INVALID_SPEC; registry logs a single warning naming both.
    • Entry point returns wrong type -> INVALID_SPEC.
    • requires references unknown extension -> MISSING_DEPENDENCY.
    • All failure paths must record the exception type and message, never re-raise out of get_registry().

    6. Lazy loading

    The registry only stores specs. The first call that needs an actual implementation (registry.resolve_action(name), registry.resolve_pop_function(name)) imports module:attr and caches the resolved object inside the record. A lazy-resolution failure flips that record to FAILED_IMPORT but does not affect other records. Importantly, get_registry() itself must not import any plugin action module - that guarantee is what keeps GUI startup fast and is one of the test cases.

    7. State and user preferences

    No global mutable state for enable/disable. The set of disabled extension names lives in EEG_OPTIONS (existing options file mechanism) under a new disabled_extensions key, queried by the registry at construction time. Tests pass an explicit disabled={...} argument; the registry never reads environment variables.

    8. EEGLAB vs EEGPrep equivalence

    EEGLAB EEGPrep
    eegplugin_<name>.m startup function eegprep.extensions entry-point factory returning ExtensionSpec
    plugin_status.m plugin_status() shim over registry.find()
    plugin_menu.m GUI retained; Phase 2 will rebuild it on top of the registry
    MATLAB path append not modeled - Python imports replace it
    Plugin folder zip upload not modeled (epic #112 scope: out)

    This keeps the EEGLAB user mental model ("my plugin is something with a name, version, menu, and pop functions") while replacing the MATLAB-specific lifecycle with Python packaging.

    9. Testing (all under tests/test_extensions_registry.py, plus targeted updates to tests/test_plugin_menu.py and tests/test_console_workspace.py)

    • Discovery returns the five bundled plugins with ExtensionStatus.BUNDLED and matches the existing bundled_plugins() names/order.
    • A fake distribution registered via importlib.metadata (using importlib.metadata.EntryPoint plus a monkey-patched entry_points for the test) is discovered, validated, and shows up as INSTALLED.
    • Entry point that raises on load -> status FAILED_IMPORT, registry construction does not raise, other entries still load.
    • Entry point that returns a non-ExtensionSpec -> INVALID_SPEC.
    • Duplicate extension name and duplicate action name -> second entry recorded INVALID_SPEC, first remains usable.
    • api_version newer than runtime, or eegprep_requires mismatch -> INCOMPATIBLE and not active.
    • disabled_extensions setting -> DISABLED and not active, but still listed.
    • Lazy loading: discovering and listing extensions does not import any module listed in actions or pop_functions; explicitly resolving one then does.
    • include_external=False returns only bundled records; "no extensions installed" returns an empty external list without errors.
    • Failure isolation: importing eegprep and calling get_registry() with one malformed entry point still yields the bundled five.

    No mocks for the registry logic itself; the only patched boundary is importlib.metadata.entry_points for the synthetic external entry-point cases.

    10. Out of scope for Phase 1

    • Replacing the hard-coded _insert_*_plugins menu insertion (Phase 2).
    • Migrating each bundled plugin __init__.py to call register_bundled instead of going through the bridge (Phase 2, behind the shim).
    • Extension Manager UX changes (Phase 3).
    • Authoring template / docs / Codex skill (Phase 4).
    • Catalog validation, signing, security policy (Phase 5).

    11. Estimated size

    Roughly 600-900 LOC in src/eegprep/ (most of it in the new extensions/ package plus the extensions.py facade), plus ~250-350 LOC of new tests. The legacy plugin_menu.py shrinks to a shim over the registry, and functions/guifunc/main_window.py / adminfunc/console.py change only enough to consume the new ExtensionRegistry API where they currently consult bundled_plugins().

    12. Open questions for human review

    1. SDK module path: eegprep.extensions (new top-level) vs eegprep.functions.adminfunc.extensions? I prefer the former because the SDK is a public surface and AGENTS.md only forbids generic "utilities" at the top level, not stable public APIs - but happy to defer.
    2. Should EEGPREP_EXTENSION_API_VERSION start at 1 (clean break) or 0 (signals "unstable" for the duration of the epic)? I propose 1.
    3. disabled_extensions belongs in EEG_OPTIONS or in a separate extensions_state.json? Current plan: EEG_OPTIONS to match EEGLAB's single-options-file pattern.
    4. Do we want a register_bundled public function at all, or should bundled plugins go through the same entry-point mechanism via internal entry-point metadata? Going through entry points is purer but adds packaging complexity to pyproject.toml for code we already ship; current plan is the explicit register_bundled call.
    5. MenuContribution.insert_after anchor format - string action id like "pop_eegplot:data" (current de-facto pattern) or a structured (menu_path, action) tuple? Leaning string for parity with MenuItemSpec.action.

    Once these are settled (or explicitly deferred) I will open an implementation PR on an agent/20260602-fix-113 branch.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

phase

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions