Files
Dario LipicarandClaude Opus 5 95d7b3a9c5 feat: split the SDK by capability, retire the provider-header path, and harden the cdylib decode (#138)
* feat(generator): remove --provider-header (interface: "provider")

Every provider now goes through the module-impl C ABI, so the LOGOS_METHOD
dispatch path is gone: parseProviderHeader, generateProviderDispatch,
ParsedMethod and the joinDocLines helper only it used (~300 lines), plus the
test that covered it.

`toQVariantConversion` is NOT removed — it is shared with live emitters — and
its test stays.

The flag is REFUSED rather than dropped. Without that, `--provider-header x.h`
falls through to the plugin-path branch, which reads the flag itself as a
plugin path and reports "Plugin file does not exist: --provider-header" — a
missing-file error for what is really a retired mode. It now exits 2 with a
message pointing at interface: "universal".

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* feat(sdk): logos_host_services.h — the C++ veneer over the privileged surface

Phase C1. A Qt-free, header-only wrapper over the three trust-root lp_* calls
A3 added, so capability_module can become an ordinary universal module instead
of a hand-written Qt plugin reaching into TokenManager directly.

Deliberately FREE FUNCTIONS, not a LogosModuleContext seam as the plan
sketched. The grant is process-global per IMAGE (host binary and module cdylib
each link their own logos-protocol, so each has its own grant state and its own
TokenManager), so the gate lives in the caller's own image and there is nothing
per-instance to inject; a context seam would imply the privilege is a property
of one impl object, which it is not. It is also markedly cheaper: a seam would
need a new module-impl C ABI export plus lockstep changes in BOTH codegen paths
(the Qt provider glue and the cdylib wrapper).

constantTimeEquals lives here rather than in each caller: the natural spelling
(a == b) leaks the matching-prefix length through timing, and a trust root
comparing tokens with == is the exact bug this file exists to prevent. Ported
from capability_module's own implementation to std::string.

Two things the tests caught that reading had not:

* lp_inform_module_token_to takes SIX arguments (client, auth_token,
  origin_module, module_name, token, timeout_ms), not the three I first wrote.
  The wrapper now mirrors it exactly, with the protocol's own default-timeout
  semantics documented.
* sdk_tests compiles against logos_headers alone, which carries no protocol
  include path. It now resolves logos_protocol.h from LOGOS_PROTOCOL_ROOT,
  accepting either the source layout (cpp/) or a package layout (include/) and
  failing loudly on neither, rather than hard-coding the one in use today.

The suite deliberately does NOT link logos-protocol: the lp_*-calling wrappers
are `inline` and never ODR-used by these tests, so no protocol symbol is
referenced. That is itself the assertion — the veneer must not drag the
protocol library into a header-only consumer. A future test that calls one will
fail to LINK rather than silently pull it in.

Also documents a real gap found while writing it: lp_token_get performs NO
host-service check, so "token_registry" gates ENUMERATION only. The plan claims
that service covers `lp_token_get(any)`; it does not. Flagged at the call site
rather than papered over — if lookup should be gated, the gate belongs in
lp_token_get.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* feat(generator): emit logos_module_grant_host_services in the cdylib exports

Completes the C1 codegen half. A3 declared this entry point in
logos_module_impl.h and documented that the grant MUST cross the C ABI, but the
generator never emitted it, so nothing could open a module's gates.

The body forwards to lp_grant_host_services in the MODULE's own image, which is
the entire point. Verified that premise on a real built module rather than
taking it from the header comment: test_basic_module_cpp_plugin.dylib DEFINES
25 lp_* symbols and imports zero — logos-protocol is statically linked into
each plugin, so the module's gate state really is its own, and a grant recorded
only in the host would leave lp_token_keys() returning null forever. That
failure is silent: null is indistinguishable from an empty token store.

Emitted unconditionally rather than behind a codegen flag. Which modules are
privileged is the host's decision — it pushes nothing to an ordinary module —
and lp_grant_host_services validates the names and fails closed, so a per-module
flag would only add a second place for declaration and capability to disagree.

The comment states the boundary honestly: this is a declaration-and-audit
mechanism, NOT a defence against a hostile module. The cdylib links
logos-protocol, so its own code can call lp_grant_host_services() directly and
self-grant. What the gate buys is that the privilege is explicit, greppable and
off by default. Isolation between modules rests on process separation, the auth
token, and the target's allowedCallers.

Three tests, one per property that could regress independently: the export
exists; its body actually forwards (a stub returning 0 would make every host
push look successful while both gates stayed shut); and it is emitted for an
ordinary module too, not only for privileged ones.

Confirmed in the built artifact: nm on a real universal module lists
_logos_module_grant_host_services alongside the other seven module-impl exports.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(generator): guard the grant export on the protocol MINOR that added it

The emitted logos_module_grant_host_services calls lp_grant_host_services,
which logos-protocol only gained at MINOR 3. A module built against an older
protocol therefore failed to compile in GENERATED code its author never wrote.
Found by giving logos-template-module a standard flake: its own lock resolves
protocol master, and the build died on `use of undeclared identifier`.

Guarded on LOGOS_PROTOCOL_VERSION_MINOR >= 3. A module built against 0.2 has no
grant entry point at all, which is the same fail-closed state as never being
granted.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* docs: point logos_async_result.h at the one LogosModule.cmake

The comment named "logos-plugin-qt/cmake/LogosModule.cmake and its
module-builder twin". There is no twin any more: logos-plugin-qt's copy is
deleted and the file exists once, in logos-module-builder.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* chore(deps): rev-pin logos-protocol at c8bab12 (the trust-root surface)

logos_host_services.h is a veneer over lp_token_keys /
lp_inform_module_token_to / lp_grant_host_services, which landed on
logos-protocol's feat/per-client-token-store branch and are NOT on its
master — master is still LOGOS_PROTOCOL_VERSION_MINOR 2, so the `tests`
check could not compile against the previously locked 03842db.

Rev-pinned in the URL rather than left master-tracking, because
`nix flake update` cannot reach a commit that is not on the tracked
branch. Re-point at master once that branch merges.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* refactor(generator): remove --module-dir, and the two dead files it documented

--module-dir walked a directory of BUILT plugins and generated one consumer
wrapper per dependency by dlopen'ing each and reading its QMetaObject. Every
wrapper now comes from a contract instead -- `--general-only` with one
`--dep <name>=<name>.lidl` per dependency -- which builds no dependency plugin
and, unlike introspection, works under cross-compilation.

It is REFUSED rather than ignored, mirroring --provider-header right below it.
Falling through to the dependency LISTING would have exited 0 having generated
nothing: the exact shape that lets a stale caller look green while shipping a
module with no typed API.

No nix build changes as a result -- the flag had no caller left in any of them,
so a store-path diff would be empty either way and would prove nothing. The
only observable difference is what the binary does when handed the flag, so
that is what the new `generator-cli` check asserts, by EXIT CODE:

  OK: control - --metadata alone exits 0 and lists dependencies
  OK: --module-dir exits non-zero (status=2)
  OK: --module-dir fails with the removal diagnostic
  OK: --general-only still emits the umbrella

The control matters: without it a non-zero exit could equally mean the binary
is broken. It runs against an EXISTING modules directory too, because the old
code only errored when that directory was missing.

Also deleted, both genuinely dead:

  * cpp/compile.sh -- compiles logos_api.cpp, module_proxy.cpp, token_manager.cpp
    and six headers, NONE of which exist in this repo any more (they moved to
    logos-protocol / logos-qt-host in the host split). The script cannot run.
  * docs/docs.md -- 789 lines with zero inbound references anywhere in the
    workspace, documenting --module-dir and a cpp/ layout that is gone.

cpp-generator/compile.sh is KEPT: logos-module-builder's LogosModule.cmake:404
still invokes it (`add_custom_target(cpp_generator_build ...)`) on the
LOGOS_CPP_SDK_IS_SOURCE branch, and it builds into exactly the
LOGOS_DEPS_ROOT/build/cpp-generator path that file then reads.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* refactor(generator): the umbrella emitter leaves legacy/, and gets its own mode

`cpp-generator/legacy/` held four things and only one was legacy. The shared
emitter library was misfiled there: `generator_lib.{h,cpp}` is already consumed
by the MODERN `experimental/lidl_gen_client.h` and by all 11 tests under
tests/generator/. `lidl_to_json.{h,cpp}` likewise. Both are now
`cpp-generator/`; `legacy/` is down to `main.cpp` + `legacy_main.h`.

The logos_sdk umbrella (`struct LogosModules`) is not legacy either — it is the
CURRENT typed-dependency surface. `LogosModuleContext::modules()` returns it,
so every universal module that calls a declared dependency goes through it, and
LogosModule.cmake runs `--general-only` for every module build. Yet the only
code that could emit it lived inside the directory the plan wants deleted.

So `cpp-generator/main.cpp` gains `--umbrella`, with `--general-only` routed to
the same implementation and dispatched before the fall-through to legacy_main.
The deps-driven emission needed no rewriting: `makeUmbrella{Header,Source}
FromDeps` were already in generator_lib, and legacy/main.cpp merely wrapped
them in file I/O. -352 lines from legacy/main.cpp (827 -> 475), including the
interface-wrapper helpers that only that branch used.

`--general-only` keeps working identically, because LogosModule.cmake and
logos-basecamp both call it. The alias is guarded on `--metadata`, since
`--general-only` was never a standalone mode — without metadata it fell through
and reported the flag as a missing plugin path, and it still does.

The scraping `writeUmbrellaHeader`/`writeUmbrellaSource` are untouched: they
belong to `generateFromPlugin`, the QPluginLoader introspection path, and die
with it.

Verified byte-identical, which is the whole claim of a relocation. An
adversarial pass built its own pre- and post-change binaries and diffed the
emitted `logos_sdk.{h,cpp}` across 12 real metadata.json files x {qt,lp} x
{--general-only,--umbrella}: 48/48 identical, stdout/stderr/exit included, with
a positive control (qt vs lp) confirming the harness can see a difference. Real
modules then built through logos-module-builder against both binaries with
`diff -r` empty, including the compiled plugin. 266/266 tests pass, and the
pre-change tree also reports 266, so no test was silently dropped.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* feat(sdk): split the SDK by capability, and add the host façade

Host, module-consumer and module-provider are three distinct capabilities. The
SDK exposed them as one target, so a program linked all three regardless of
what it was. Each now gets its own INTERFACE target:

    ::common    logos_json.h, logos_result.h
    ::consumer  logos_lp_client.h, logos_async_result.h
    ::provider  logos_module_context.h, logos_host_services.h
    ::host      logos_host_core.h        (new)

`logos_headers` stays as an umbrella over all four, so the ~70 existing
consumers are unaffected — logos_module_context.h alone has 66. Migrate to the
narrow targets when touching a repo; additive first, removal second.

NOTE the misnomer the split exposes: `logos_host_services.h` is MODULE-side
despite its name — it is the veneer a privileged module uses for services the
host granted it — so it belongs to ::provider, not ::host. Renaming it touches
9 files across 5 repos, so it is left for a change that can carry that cascade.

── logos_host_core.h ───────────────────────────────────────────────────────

`logos::host::LogosCore`, a plain RAII wrapper over liblogos' logos_core_* C
API, for the four programs that stand up a core (basecamp, logoscore-cli,
standalone-app, module-viewer). They currently open-code the same calls, and
basecamp had already grown a private wrapper for them.

It is deliberately an ORDINARY class — no codegen, no injection seam, no
void*. LogosModuleContext needs `_logosCoreSetContext_`, SFINAE `maybeSet*`
helpers and a void* round-trip because a module impl is user-authored but
FRAMEWORK-instantiated. A host is main(): it constructs this itself. For the
same reason there is no `modules()` here — the host holds its own LogosModules
from its own generated logos_sdk.h, so this header needs no generated type.

What it earns, each tied to a measured hazard:
  * OWNERSHIP. liblogos allocates its char**/char* returns with new[], so
    `delete[]` is correct and free() is undefined behaviour. That rule lived in
    a comment in one repo's .cpp; it is now in one place.
  * ORDERING. Three setters must precede logos_core_start(), stated only in
    comments in logos_core.h. They are constructor arguments here, so the
    illegal order is not expressible.
  * SHAPE. logos_core_get_module_stats() takes no module name and returns one
    blob for every module; stats(name) does that parse once.

The logos_core_* ABI is re-declared rather than included: logos-liblogos
depends on logos-cpp-sdk, so including its header would invert the graph. Every
host already hand-declares it; this makes it one declaration instead of four.

15 tests, 281/281 suite total. They define the extern "C" ABI themselves and
allocate exactly as liblogos does, so the ownership rules are exercised rather
than asserted; the ordering test records call order and pins start() as last.

Also fixes a real gap: nix/include.nix carries its own header list, separate
from cpp/CMakeLists.txt's install(FILES), so a new header silently did not ship
in the export layout.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* feat(generator): a Qt-typed umbrella that needs no LogosAPI

Splits a consumer's TYPE SURFACE from its TRANSPORT. Until now the qt umbrella
was `explicit LogosModules(LogosAPI* api)` while the lp one was default-
constructible, so "Qt types" implicitly meant "has a LogosAPI" — and a cdylib
module, whose provider surface is the std logos_module_impl.h C ABI and which
holds no LogosAPI anywhere, could not have Qt-typed dependency wrappers at all.
Its generated glue emits `new LogosModules()` unconditionally
(lidl_gen_cdylib.cpp:693), so the combination did not merely misbehave, it did
not compile.

That was a codegen choice, not a law: the wrapper bodies already run over lp_*.

`--binding api|origin` selects it, defaulting to `api`. A second enum rather
than a third ApiStyle value, deliberately: ApiStyle names the type surface and
is switched on by six emitters (makeHeader/makeSource/returnTypeFor/
paramTypeFor/toWireFor/fromWireFor); a "Qt types, explicit origin" member would
force all six to answer a transport question whose honest answer is "same as
Qt" every time. ApiStyle::Lp ignores the new axis — lp is origin-bound by
construction — and that is asserted rather than assumed.

The emitted umbrella bakes metadata.json#name as the origin literal:

    LogosModules() : test_fullapi_cpp(QStringLiteral("test_fullapi_qtproxy")) {}
    FullApi bind_full_api(const QString& moduleName) {
        return FullApi(QStringLiteral("test_fullapi_qtproxy"), moduleName); }

Origin is the CONSUMER's own name and target is the dep — origin first in both
bind_ overloads. This is the load-bearing property: LpBridge::forTarget derives
origin from `api->moduleName()`, and reusing it silently gives a consumer the
caller's identity, which has already preserved a privilege escalation once in
this tree. An empty metadata name is refused at the CLI (exit 6, naming the
file) and emits `#error` in the header: a module that cannot state its identity
must not compile, and must never be handed a blank or borrowed one.

Verified additive on 172 real metadata.json x 2 api-styles = 344 runs, all
producing output, byte-identical old binary vs new. Mutation control: swapping
bind_<iface>'s (origin, moduleName) to (moduleName, origin) fails the suite at
MakeUmbrellaTest.QtExplicitOriginStatesTheConsumersOwnNameEverywhere. 281 -> 286
tests.

Framing worth keeping: the origin is SELF-ASSERTED from the module's own
metadata and is not attested by the transport. That is not a regression —
`api->moduleName()` is equally process-stated — but "explicit origin" means the
module names itself, not that the host vouches for the name.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* docs(generator): stop pointing callers at a flag that no longer exists

--backend qt is deleted from logos-qt-generator, and this repo was still
signposting it. main.cpp's refusal said "Use it for --backend qt", and the usage
text advertised --lidl … --backend qt and --from-header … --backend qt. Those
now point at nothing — the exact failure the deletion removes, one repo over.

The refusal names the real replacement chain instead: --backend cdylib here,
then logos-qt-host-generator --backend cdylib for Qt-plugin packaging.

docs/project.md's "Provider Generation" section documented three emitters that
no longer exist; rewritten to state the seam and the two-step pipeline.
docs/spec.md's dataflow diagram showed <name>_qt_glue.h / <name>_dispatch.cpp as
outputs; the diagram is corrected and the sections describing that shape are
marked historical rather than deleted, because the onInit wiring they document
still applies to the cdylib glue.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* refactor(cpp-generator): merge legacy/ into the generator, dropping its dead half

`legacy/` was never a library with an API surface. Two files, 475 lines, exactly
one exported symbol — `int legacy_main(int, char**)` — with every other
definition `static`, compiled INTO logos-cpp-generator and reached by fallthrough
at the end of main(). So there was nothing to keep separate: it is one mode of
this binary, and it now lives beside the others as plugin_introspect.{cpp,h}
behind `runPluginIntrospectMode()`, named for what it does.

Deleting it was never an option — that premise was checked and refused earlier.
`--general-only` alone has ~10 live callers across 7 repos including the central
module path (buildPlugin.nix:206,211, buildHeaders.nix:221,
LogosModule.cmake:423). The mode is load-bearing; only its packaging was wrong.

110 lines go with the move, all genuinely unreferenced:

  * cppStringEscape — zero callers anywhere.
  * writeUmbrellaHeader / writeUmbrellaSource and the `if (!moduleOnly)` block
    that called them. This is the real prize: a SECOND, directory-SCRAPING
    implementation of logos_sdk.{h,cpp}, unreachable in practice because
    generate-module-headers.sh:60 always passes --module-only. generator_lib's
    deps-driven makeUmbrella*FromDeps is now the only umbrella emitter, so the
    two cannot drift.
  * a dead `QJsonDocument doc(methods);` and its commented-out use.

With the block gone, `--module-only` suppresses nothing, so the parameter and
its plumbing go too. The FLAG stays tolerated rather than rejected, because
generate-module-headers.sh passes it unconditionally — a comment at the old
parse site says so.

Verified: #default builds, and both checks pass — `generator-cli` (which
exercises the CLI surface, including --general-only) and `tests`.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* feat(sdk): make the by-name call path a supported API

The dynamic (by-name) invoke path already existed and was already ungated at
every layer — lp_client_create / lp_invoke in the C ABI, logos::LpClient above
it, and the Qt client above that. Nothing checked a host service; there was no
gate to open. What was missing was the ERGONOMICS, which is what turned a
supported capability into something callers reached around the umbrella to get.

Three additive pieces, no gate touched:

1. LogosModuleContext::moduleName() — the module's own registry name, i.e. the
   origin it authenticates as. The typed wrappers bake their origin in at
   codegen time; a by-name call has to state one, and a wrong origin
   authenticates as nobody and fails far from the call site. Set through a NEW
   `_logosCoreSetModuleName_`, deliberately not a fourth parameter on
   `_logosCoreSetContext_`: every generated provider calls that signature, so
   widening it would break each one until regenerated, for a value the
   generator knows statically. Set before the context, so moduleName() is live
   inside onContextReady().

2. LogosModules::dynamic(target) on the origin-bound umbrella — the untyped
   client, with the origin baked in exactly as the typed members' is, and
   cached per target because LpClient owns a connection. The typed members over
   metadata.json#dependencies stay the ordinary way to call another module;
   this is for the cases whose target is a runtime value (a proxy, a router).

3. LpClient::getMethods() over the already-exported lp_get_methods. Invoke
   without introspect is guessing — a caller that cannot ask what exists can
   only hardcode, and a wrong guess fails at runtime like a typo.

Verified: #default builds, and both checks pass (tests, generator-cli).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(cdylib): shape-check [any]/{tstr:any} args, and fix the umbrella's includes

TWO fixes; the second is a regression I introduced two commits ago.

1. jsonArgToStd() returned the raw json for LogosList / LogosMap — "untyped JSON
   passes through, as it always has". Arity was checked, type was not, so a
   scalar reached a `[any]` parameter untouched. A proxy forwarding it through a
   Qt-typed consumer then turned "notalist" into
   ["n","o","t","a","l","i","s","t"], because qvariant_cast reads a QString as a
   sequential container — and the downstream provider saw a well-formed array
   with nothing left to refuse. Now emits logos::jsonRequireArray /
   jsonRequireObject; the throw lands in the dispatch's existing catch as
   {"code":"dispatch_failed"}. Bare `any` stays raw, deliberately: it declares
   nothing, so there is nothing to check it against.

   Measured on the conformance matrix: closes all 8 failing cells (498/22/12/8
   -> 500/18/12/2), and a whole-matrix per-cell diff shows exactly 14 status
   changes, every one inside the two hostile cases. The other 518 cells are
   byte-identical in status and value. The remaining 2 are the fix working — the
   C++ cdylib provider now refuses the same input, which cases.json still pins
   as lenient via expect_by_provider; that is a registry edit, and known.json's
   Q1b already names this exact outcome as the intended fix.

2. The Lp umbrella emitted `logos::LpClient& dynamic(...)` and a
   std::map<..., std::unique_ptr<logos::LpClient>> while <map>, <memory> and
   logos_lp_client.h were conditional on interfaceNames. A module WITH
   dependencies compiled by accident, because <dep>_api.h drags the header in
   transitively. A module with NO dependencies and no interfaces includes
   nothing else and failed outright with "no type named 'LpClient' in namespace
   'logos'". test_fullapi_cpp is exactly that shape.

   I shipped that in 1be71bb and did not catch it: I verified #default and both
   checks, which are the SDK's own targets, not a dependency-free consumer of
   its codegen. `.#logos-test-modules--test_fullapi_cpp` is the case that
   exercises it and now builds.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* ci: use logos-co/setup-nix-cache-action for Nix setup and caching

Replaces the per-repo installer + cachix pair with the shared action, which
installs Nix with the Logos Attic cache (cache.nix.logos.co) preconfigured and
publishes what the job builds — master to the public cache, every other ref to
ci.

Each converted job also gains

    environment: ${{ github.ref == 'refs/heads/master' && 'public-cache' || '' }}

because ATTIC_TOKEN_PUBLIC only exists inside that environment. Without it the
secret resolves empty on master and publishing is silently skipped — the job
still passes, so the omission would not show up as a failure.

The action installs Nix itself on every runner, macOS included. That is a
deliberate reversal of the workaround these files carried: the comments here
said cachix/install-nix-action collides with the runner's pre-existing _nixbld
users (eDSRecordAlreadyExists), so DeterminateSystems' installer was used
instead. It no longer reproduces — logos-delivery-module has already been
converted the plain way and its `build-and-test (macos-latest)` leg passes.
Keeping the workaround would have meant a second installer plus a duplicated
substituter/key block in ten files, guarding against something two green runs
say does not happen. If it ever recurs it fails loudly at install, which is
recoverable; the silent-skip above is the failure mode worth engineering
against.

One property is deliberately NOT carried over: the old cachix step ran with
`continue-on-error: true` so a failed cache push could not fail a job whose
tests passed. The action exposes no equivalent, and adding one here would also
swallow genuine setup failures now that the same step installs Nix rather than
only publishing at the end.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* chore(deps): track logos-protocol master again

The rev pin on feat/per-client-token-store existed because the trust-root
surface it needed lived only on that branch while protocol master was still
LOGOS_PROTOCOL_VERSION_MINOR 2. Both comments here said to re-point once it
merged; it has (logos-protocol#59), and master is 0.4.0 — MINOR 4, carrying
lp_token_keys, lp_inform_module_token_to, lp_grant_host_services and
TokenManager::forIdentity / isolateIdentity.

That matters beyond compiling: the cdylib glue's grant forwarding is guarded on
MINOR >= 3, so a master pin taken too early would not have failed loudly — it
would have dropped the grant silently. The guard now opens.

Verified against master rather than assumed: #default builds and the checks pass
(cpp-sdk `tests`, plugin-qt `qt-host-generator`).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* docs: the generator has no legacy/ directory any more

This should have been part of the merge commit and was not. `docs/project.md`
still listed `legacy/` in the project tree, named `legacy_main()` as the
fallthrough target, and described `--api-style` as being threaded through
`legacy/main.cpp` → `generateFromPlugin` / `writeUmbrellaHeader` — a directory,
a function and two emitters that no longer exist. `docs/spec.md` still pointed
backwards-compatibility at `legacy_main()`.

Corrected to `plugin_introspect.{cpp,h}` / `runPluginIntrospectMode()`, with the
provenance kept rather than erased: the tree entry says what it was and why it
was never a library, because "there used to be a legacy generator" is the
question a reader will actually arrive with.

The umbrella line gets the deletion too — `writeUmbrellaHeader` /
`writeUmbrellaSource` were the second, directory-scraping implementation of
logos_sdk.{h,cpp}, and their absence is the point: `makeUmbrella*FromDeps` is
now the only umbrella emitter, so the two cannot drift.

Two nearby lines were stale independently of that move and are fixed with it:

  * "the legacy emitters in tests/generator/" — those tests cover the SHARED
    generator_lib emitters (test_make_header/source/umbrella, the type maps),
    which are not legacy and never were.
  * "consumer wrappers real modules get come from legacy/main.cpp →
    generateInterfaceWrappers" — generateInterfaceWrappers is in main.cpp and
    was already there, so that path was misattributed before this branch.

Every other use of "legacy" in these docs is left alone: `interface: "legacy"`,
legacy Qt types (QVariantMap / QVariantList / QStringList), legacy Q_INVOKABLE
modules and the legacy consumer path are all real things that still exist.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* docs: correct generator ownership after the Qt host split

Comments and docs across the repo still claimed this generator emits the Qt
plugin glue, and pointed `--backend qt` users at logos-qt-generator. Neither
is true: the Qt-plugin (provider) glue is emitted by logos-plugin-qt's
logos-qt-host-generator --backend cdylib, on top of the C ABI this tool emits
with --backend cdylib, and logos-qt-generator owns only `consumer` and `ui`
(it refuses the flag too).

Also corrects the LogosModuleContext header, whose comments described the
retired Qt provider path throughout — `<name>_events.cpp` marshalling into a
QVariantList and a provider `onInit` setting the context. The emitted file is
`<name>_events_cdylib.cpp`, it marshals into nlohmann::json, and the C-ABI
export TU installs the callback. The runtime path it named
(runtime_qt/host/module_initializer.cpp) no longer exists.

The only behaviour change is the text of three --backend/--from-header error
messages, which named the wrong tool. Nothing asserts on them.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(generator): refuse --backend qt before validating --impl-class

The `backend == "qt"` refusal sat below the --impl-class / --impl-header
requirement checks, so `--backend qt` alone never reached it: it exited 1 with
"Error: --backend qt requires --impl-class <ClassName>", which reads as though
qt would work given one more flag. qt was removed; no flag rescues it.

Hoisted the refusal (and the unsupported-backend error) above those checks.
The cdylib branch returns on every path before this point, so the two checks
could only ever gate a backend that was about to be rejected anyway; they are
dropped rather than left unreachable.

`--backend qt` now exits 6 with the removal message, `--backend bogus` exits 1,
and cdylib is untouched. checks.generator-cli and checks.tests pass.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* ci(doctests): skip the qt-api-events spec, which builds a provider module

This PR removes `logos-cpp-generator --provider-header`. The watcher fixture in
doctests/cpp-sdk-qt-api-events.test.yaml is `interface: "provider"`, so
logos-module-builder reaches "generating provider dispatch (qt_watcher_module)"
and the generator refuses:

    Error: --provider-header was removed.

That one build failure cascades through the rest of the spec (install, load,
subscriptionAccepted, greetThrough, greetedCount, lastGreeted), which is the
whole of the red on both ubuntu-latest and macos-latest. notifier_module is
`interface: universal` and builds fine.

Skipped rather than rewritten. The replacement shape that keeps the Qt-typed
dependency wrappers without the retired provider dispatch is
`interface: universal` + `codegen.consumer_api_style: "qt"`, and
logos-module-builder master does not carry that key yet — while this spec pins
the builder to master. It arrives with the B4 stack.

The spec file is kept and annotated, not deleted, because it covers two things
nothing else does: the Qt-TYPED wrapper emission (separately generated code
from the lp path, so lp-path specs cannot catch a bug in it) and a subscription
made from onInit() before the dependency is reachable. Both are UNTESTED until
this is restored — a known, accepted gap recorded in the spec header and in the
workflow.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-19 15:49:30 -03:00

26 KiB

Logos Code Generator — Experimental

Overall Description

The experimental code generator extends logos-cpp-generator with two new capabilities: a lightweight Interface Definition Language (LIDL) for declaring module contracts, and a C++header parser that can infer module interfaces directly from pure C++ implementation classes. Both paths produce the same output: the Qt-free logos_module_* C-ABI provider glue that bridges pure C++ module implementations to the runtime. (It used to emit the Qt plugin glue directly; turning the C ABI into a Qt plugin is now a downstream step, logos-qt-host-generator --backend cdylib in logos-plugin-qt, and that seam is what lets the Rust and JS providers target the same ABI.)

The goal is to decouple module business logic from the Qt framework. Module authors write standard C++ using std::string, int64_t, std::vector<T>, and the build system generates all Qt boilerplate (QObject, Q_PLUGIN_METADATA, QString conversions, method dispatch) automatically.

Definitions & Acronyms

Term Definition
LIDL Logos Interface Definition Language — a lightweight DSL for declaring module interfaces
Universal Module A module whose implementation is pure C++ (no Qt types) with all Qt glue generated at build time
Provider Glue Generated code that wraps a pure C++ impl class in a LogosProviderObject with callMethod() dispatch and getMethods() introspection
Client Stub Generated type-safe C++ wrapper class that callers use to invoke a module's methods without string-based dispatch
Dispatch The generated callMethod() function that maps string method names to typed method calls on the provider object
Impl Header The pure C++header file (_impl.h) that declares a module's public methods using standard C++ types
TypeExpr The AST node representing a type in the LIDL type system
ModuleDecl The AST node representing a complete module declaration (name, version, methods, events, types)

Domain Model

Two Paths to the Same Output

Path 1: LIDL file                    Path 2: C++ impl header
    │                                     │
    ▼                                     ▼
 lidlParse()                       parseImplHeader()
    │  (logos-lidl's lidl::parse,         │
    │   via lidl_compat.h)                │
    ▼                                     │
 lidlValidate()                           │
    │                                     │
    ▼                                     ▼
 ModuleDecl  ◄────── same AST ──────► ModuleDecl
    │                                     │
    ├──► lidlMakeTypesHeaderCdylib()      │
    │    lidlMakeModuleImplExports()      │
    │    lidlMakeEventsSourceCdylib()     │
    │         → logos_module_* C ABI       │
    │           (Qt packaging is a         │
    │            downstream step:          │
    │            logos-qt-host-generator)  │
    │                                     │
    ├──► lidlMakeHeader()                 │
    │         → <name>_api.h              │
    │                                     │
    └──► lidlMakeSource()                 │
              → <name>_api.cpp            │

(There is no lidlTokenize() step here any more: the lexer lives in logos-lidl with the rest of the frontend, behind lidl::parse.)

Both paths converge at ModuleDecl, the shared AST. From there, the same generation functions produce identical output regardless of the input format.

LIDL Language

LIDL is a minimal interface definition language. A module declaration contains metadata, type definitions, method signatures, and event signatures:

module wallet_module {
    version "1.0.0"
    description "Wallet operations"
    category "finance"
    depends [crypto_module]

    type Account {
        address: tstr
        balance: uint
        ? label: tstr          ; optional field
    }

    method createAccount(passphrase: tstr) -> tstr
    method getBalance(address: tstr) -> uint
    method listAccounts() -> [tstr]
    method transfer(from: tstr, to: tstr, amount: uint) -> result

    event onTransfer(from: tstr, to: tstr, amount: uint)
}

Comments start with ; and run to end of line.

Type System

Built-in primitive types:

LIDL type Meaning Qt mapping C++ std mapping
tstr Text string QString std::string
bstr Binary data QByteArray std::vector<uint8_t>
int Signed 64-bit integer qlonglong int64_t
uint Unsigned 64-bit integer qulonglong uint64_t
float64 Double precision float double double
bool Boolean bool bool
result Structured result (success/value/error) LogosResult LogosResult
any Untyped value QVariant QVariant
void No return value void void

Composite types:

  • [T] — Array of T (e.g., [tstr]QStringList / std::vector<std::string>)
  • {K: V} — Map from K to V (e.g., {tstr: int}QVariantMap)
  • ?T — Optional T (→ QVariant on the Qt surface, which loses the value type; std::optional<T> on the std surface — see Optionality in project.md)

Named types reference type definitions within the same module.

C++ Header Parsing

The --from-header mode parses a C++implementation header to extract public method signatures. It maps C++ types to LIDL types:

C++ type LIDL type
std::string / const std::string& tstr
bool bool
int64_t int
uint64_t uint
double float64
void void
std::vector<std::string> [tstr]
std::vector<uint8_t> bstr
std::vector<int64_t> [int]
std::vector<uint64_t> [uint]
std::vector<double> [float64]
std::vector<bool> [bool]
LogosMap {tstr: any} (Map) — nlohmann::json alias; sets jsonReturn flag
LogosList [any] (Array) — nlohmann::json alias; sets jsonReturn flag
QVariantMap {tstr: any} (Map) — legacy Qt type
QVariantList [any] (Array) — legacy Qt type
QStringList [tstr] (Array) — legacy Qt type
Anything else any

LogosMap and LogosList are using aliases for nlohmann::json defined in logos_json.h (part of the SDK). They allow module implementations to remain completely Qt-free while returning rich structured data. The parser maps them to the same LIDL shapes as QVariantMap/QVariantList, but sets the jsonReturn flag on the method so the generator emits an nlohmannToQVariant() conversion in the glue layer.

The parser uses a state machine to find the target class, track access specifiers (public/private/protected), and extract method declarations. It skips constructors, destructors, typedefs, using declarations, std::function members, and non-method statements. While scanning, it also captures any doc comment immediately above a method declaration as that method's description (see Method documentation).

Module metadata (name, version, description, dependencies) comes from metadata.json, not from the header.

Method documentation

A doc comment written directly above a method's declaration in the impl header becomes that method's description, stored on MethodDecl.description in the shared AST and emitted into the description field of each getMethods() entry. Because getMethods() is what the framework's getPluginMethods() returns, the description flows — with no extra call — to lm methods, logoscore module-info, and Basecamp's Methods list.

Only doc comments are captured: /// line comments and /** … */ / /*! … */ block comments. Plain // and /* … */ comments are ignored, so section separators and incidental notes don't leak into the API. A multi-line doc comment is preserved with its line breaks (markers stripped, lines joined with \n; leading/trailing blank lines dropped, interior blank lines kept), and only comments immediately adjacent to the declaration (no blank line in between) attach.

class WalletModuleImpl : public LogosModuleContext {
public:
    /// Transfers `amount` from the active account to `toAddress`.
    /// Returns the resulting transaction hash.
    std::string transfer(const std::string& toAddress, int64_t amount);
};

→ the transfer entry in getMethods() gains "description": "Transfers amountfrom the active account totoAddress.\nReturns the resulting transaction hash." (the two lines preserved, joined with \n)

A method with no doc comment simply has no description field. Methods introspected purely via Qt's QMetaObject (legacy Q_INVOKABLE modules with no generated dispatch) carry no comments at runtime and therefore have no description.

Event documentation

Events are the subscribe-half of a module's API (methods are the call-half), and document the same way. A doc comment directly above an event declaration in the logos_events: section (see Event Emission below) becomes that event's description, stored on EventDecl.description in the shared AST and emitted into the description field of the event's entry in getMethods().

getMethods() returns the module's whole interface — methods and events — with each entry tagged by a "type" field ("method" or "event"). Events ride inside getMethods() deliberately: there is no separate getEvents() vtable method, so LogosProviderObject's vtable layout never shifts and old/new hosts and modules stay binary-compatible (see Why events live in getMethods() below). The framework then offers three filtered views over that one call — getPluginMethods() (entries that aren't events), getPluginEvents() (type == "event"), and getPluginInterface() (everything) — so the description flows, with no extra provider call, to lm events, logoscore module-info's Events section, and Basecamp's Interface screen.

The capture rules are identical to methods: only /// line comments and /** … */ / /*! … */ block comments are captured (plain // and /* … */ are ignored); multi-line comments preserve their line breaks (markers stripped, joined with \n, leading/trailing blanks dropped); only comments immediately adjacent to the declaration attach.

logos_events:
    /// Emitted once the user has authenticated.
    /// Carries the freshly issued session token.
    void userLoggedIn(const std::string& userId, const std::string& token);

→ the userLoggedIn entry in getMethods() gains "type": "event" and "description": "Emitted once the user has authenticated.\nCarries the freshly issued session token."

An event entry carries type: "event", name, signature, parameters[] (each with type and name), and — when documented — description. Unlike a method entry it has no returnType or isInvokable: events are void, fire-and-forget. Events are a universal (--from-header) concept. (An entry with no "type" is treated as a method, so a module built against a pre-events SDK simply reports zero events.)

An event's description may also be supplied out-of-band via an optional description field on the corresponding metadata.json events[] entry (the doc comment takes the same role for both sources).

Event Emission via logos_events:

Universal modules declare events in a Qt-signals:-style section parsed by the codegen. The same method name appears on both sides — declared in logos_events:, called directly to emit:

#include <logos_module_context.h>

class MyModuleImpl : public LogosModuleContext {
public:
    void doWork() {
        userLoggedIn("alice", 12345);            // typed emit, same name
    }

logos_events:                                     // expands to `public:`; recognised by impl_header_parser
    void userLoggedIn(const std::string& userId, int64_t timestamp);
    void messageReceived(const std::string& from, const std::string& body);
};

impl_header_parser.cpp recognises the raw logos_events: token (before preprocessing) and populates ModuleDecl.events with one EventDecl per prototype. Three artifacts get emitted from this:

  1. <name>_events_cdylib.cpp — Qt-MOC-style definitions of each declared event method on the impl class. Bodies marshal typed args into an nlohmann::json array and call this->emitEventImpl_("<event>", &args), a protected helper on LogosModuleContext:

    void MyModuleImpl::userLoggedIn(const std::string& userId, int64_t timestamp) {
        nlohmann::json args = nlohmann::json::array();
        args.push_back(userId);
        args.push_back(timestamp);
        emitEventImpl_("userLoggedIn", &args);
    }
    

    (This used to be a <name>_events.cpp marshalling into a QVariantList, back when the emitter it fed was a Qt provider object. A universal module's impl side is Qt-free, so the payload is JSON and the file carries the _cdylib suffix.)

  2. Emit-callback wiring<name>_module_impl.cpp, the generated C-ABI export TU, installs the callback through _logos_codegen_::maybeSetEmitEvent alongside maybeSetModuleName / maybeSetContext / maybeSetLogosModules. The lambda casts the void* back to nlohmann::json, dumps it, and hands it to the logos_module_emit_cb the host registered via logos_module_set_emit_callback:

    _logos_codegen_::maybeSetEmitEvent(lidlImpl(),
        [](const std::string& name, void* args) {
            const nlohmann::json* payload = static_cast<const nlohmann::json*>(args);
            std::lock_guard<std::mutex> lock(g_emitMutex);
            if (g_emitCb)
                g_emitCb(name.c_str(), payload ? payload->dump().c_str() : "[]", g_emitUd);
        });
    

    (Was a <name>_qt_glue.h lambda forwarding to LogosProviderBase::emitEvent(QString, QVariantList); that glue is the retired shape described under Generated Output below.)

  3. <name>.lidl sidecar — a serialised view of the module's declared events (using lidlSerialize, which since the frontend extraction is lidl::serialize in the logos-lidl library, re-exported by experimental/lidl_compat.h; the lidl_serializer.cpp that used to hold it is gone from this repo):

    module my_module {
      event userLoggedIn(userId: tstr, timestamp: int)
      event messageReceived(from: tstr, body: tstr)
    }
    

    buildPlugin.nix ships this at $out/share/logos/<name>.lidl. buildHeaders.nix passes it to the consumer-side codegen via --events-from, which adds typed on<EventName>(callback) accessors to the generated <Module> wrapper (one per declared event, callback-arg types respect --api-style).

Module metadata (name, version, description, dependencies) still comes from metadata.json, not from the header.

Generated Output

Historical. <name>_qt_glue.h / <name>_dispatch.cpp were emitted by lidl_gen_provider, which is deleted. A module now emits the logos_module_* C ABI (--backend cdylib) and logos-qt-host-generator turns that into a Qt plugin. The sections below describe the retired shape and are kept because the onInit wiring they document still applies to the cdylib glue.

Provider Glue (<name>_qt_glue.h)

Contains two classes:

  1. ProviderObject — inherits LogosProviderBase, holds an instance of the impl class (m_impl). Each public method is wrapped with type conversion:
  • Qt parameters → C++ std parameters (e.g., QString.toStdString())
  • Call m_impl.method(...)
  • C++ std return → Qt return (e.g., QString::fromStdString(result))
  • For jsonReturn methods (returning LogosMap/LogosList), the glue calls a generated nlohmannToQVariant() recursive helper to convert nlohmann::jsonQVariant/QVariantMap/QVariantList
  • Always overrides onInit(LogosAPI*) to (a) copy the three runtime-injected properties (modulePath, instanceId, instancePersistencePath) into the impl when it inherits from LogosModuleContext, and (b) construct a per-module LogosModules (from generated_code/logos_sdk.h) owned by the provider, threading its pointer through the same context base. Both wire-ups go through SFINAE'd helpers in logos_module_context.h (_logos_codegen_::maybeSetContext / maybeSetLogosModules), so non-inheriting impls compile unchanged and the LogosAPI never escapes the provider.
  1. PluginQObject subclass implementing PluginInterface and LogosProviderPlugin. Carries Q_PLUGIN_METADATA and Q_INTERFACES. Its createProviderObject() factory returns a new ProviderObject instance.

Dispatch (<name>_dispatch.cpp)

Implements two methods on the ProviderObject:

  1. **callMethod(methodName, args)** — string-based dispatch table. For each method, extracts args from QVariantList, calls the typed wrapper, returns result as QVariant. Void methods return QVariant(true).

  2. **getMethods()** — returns a QJsonArray describing the module's whole interface — both methods and events. Each entry carries a "type" of "method" or "event":

    • method entries have type: "method", name, signature, returnType, isInvokable, parameters[] (with type and name), and — when the declaration has a doc comment — description (see Method documentation).
    • event entries (one per logos_events: declaration) have type: "event", name, signature, parameters[], and an optional description (see Event documentation). They omit returnType/isInvokable — events are void.

    The framework slices this single array into getPluginMethods() (non-event entries), getPluginEvents() (type == "event"), and getPluginInterface() (everything), which is what surfaces in lm methods/lm events, logoscore module-info, and Basecamp's Interface screen.

Why events live in getMethods()

Folding events into getMethods() — rather than adding a sibling getEvents() virtual — is a deliberate ABI choice. LogosProviderObject is the in-process vtable contract between a host/runtime and a loaded module; inserting a new virtual would shift every later vtable slot and break any mix of old/new host and module binaries. Reusing the existing getMethods() slot keeps the vtable byte-for-byte stable: a new host reading an old module just sees no type: "event" entries (so zero events), and an old host reading a new module ignores the "type" field (events show up in its method list — cosmetic, never a crash). Legacy Qt modules declare no events, so their getMethods() is methods-only.

Client Stubs (<name>_api.h + <name>_api.cpp)

Generated from LIDL (not from --from-header). Each module gets one <Module> wrapper class whose signature shape is picked by the consumer's build via --api-style:

--api-style Wrapper signatures
qt (default) QString / QStringList / QVariantList / QVariantMap / int / LogosResult
lp std::string / std::vectorstd::string / LogosMap / LogosList / int64_t / StdLogosResult, over the Qt-free logos-protocol C ABI

(std — the same signatures over a QVariant / LogosAPIClient body — was retired; --api-style=std is now an error.)

Both styles provide:

  • Typed sync methods. The Qt style calls LogosAPIClient::invokeRemoteMethod() and converts the QVariant result; the lp style calls logos::LpClient::invoke() and converts the nlohmann::json result — no Qt anywhere in the call.
  • Async overloads with callback + timeout.
  • Event subscription. The Qt style exposes the generic on(eventName, callback) channel plus one typed on<EventName>(callback) adapter per declared event; the std style exposes the typed adapters over logos::LpClient::subscribe, holding each RAII LpSubscription for the wrapper's lifetime. (Both styles once also emitted setEventSource() / eventSource() / trigger() — a consumer-side emission surface. It is gone: test_lidl_gen_client.cpp asserts no trigger( is emitted. A module emits its own events through logos_events:, never through a dependency's wrapper.)

The lp wrappers marshal over the logos-protocol C ABI (lp_*) instead, so the calling translation unit needs zero Qt headers and links no qt-sdk. (The retired std style was the one that shared invokeRemoteMethod with the Qt path and generated a Qt<->std conversion inline in its .cpp.) Both styles emit the same filename (<name>_api.h / <name>_api.cpp) and the same class name (<Module>) — the two are mutually exclusive at build time. No _api_std.{h,cpp} files are ever produced.

Umbrella files (logos_sdk.h / logos_sdk.cpp) aggregate every dep into a flat LogosModules struct — one accessor per metadata.json#dependencies entry, nothing else:

struct LogosModules {
    LogosAPI*    api;
    SomeDep      some_dep;       // one per declared dependency
    // ...
};

Only the modules explicitly listed as dependencies appear. The runtime's core_manager is intentionally NOT exposed here — apps that need to manage the core (basecamp, logoscore) use liblogos' C API directly, not a typed RPC wrapper.

Features & Requirements

LIDL Pipeline

The whole frontend now lives in the standalone logos-lidl repo; this generator links it and reaches it through experimental/lidl_compat.h, which re-exports the three stages below under their historical lidl* names. There is no separately callable lexer entry point here any more — lidlTokenize was part of the embedded copy that was deleted.

  1. Lexer — tokenizes source into keywords, identifiers, string literals, symbols (internal to lidl::parse)
  2. Parser (lidlParselidl::parse) — recursive descent parser producing a ModuleDecl AST
  3. Validator (lidlValidatelidl::validate) — checks for duplicate names, unknown type references, builtin shadowing, duplicate parameters
  4. Serializer (lidlSerializelidl::serialize) — pretty-prints a ModuleDecl back to LIDL text (useful for roundtrip testing)

Impl Header Pipeline

  1. parseImplHeader — reads metadata.json + C++ header, produces a ModuleDecl
  2. Same generation functions as LIDL path

Backwards Compatibility

  • The remaining generator modes (--metadata, plugin path) continue to work unchanged via runPluginIntrospectMode() (plugin_introspect.cpp; was legacy/main.cpp's legacy_main()). --provider-header (the LOGOS_METHOD dispatch behind interface: "provider") was REMOVED — every provider now goes through the module-impl C ABI; the flag is refused with a message pointing at interface: "universal"
  • The new --from-header and --lidl modes are additive
  • Generated plugins implement both PluginInterface (for lm introspection) and LogosProviderPlugin (for new-API provider creation)
  • The runtime (logos-liblogos) already supports both old and new plugin types via qobject_cast detection

Conversion Helper Generation

Conversion helpers are only emitted when needed:

  • String vector helpers (lidlToQStringList, lidlToStdStringVector) — emitted when the module uses [tstr] parameters or return types
  • nlohmann→Qt helper (nlohmannToQVariant) — emitted when any method has jsonReturn = true (i.e., the impl returns LogosMap or LogosList). This recursive function converts nlohmann::json objects, arrays, strings, numbers, and booleans to their QVariant equivalents.