Skip to content

Execution kernel: support cheap preflight gates/lazy providers so ubiquitous host hooks do not need a second handler model #595

Closed

Description

@ScriptedAlchemy

Problem

ScriptedAlchemy/cargo-hauler had to move its ubiquitous shell hooks out of routed events and into config-declared fast-path handlers because every non-cargo shell command paid the full rendered event-route startup cost.

Measured in cargo-hauler #90:

  • routed tool/before: ~0.10–0.11 s, ~64 MB RSS;
  • routed tool/after: ~0.09–0.10 s, ~64 MB RSS;
  • the route loaded the full rendering runtime before it could decide that ls, git, etc. were irrelevant.

The current workaround in cargo-hauler/agent-bundle.config.ts uses hooks.beforeTool.handler / hooks.afterTool.handler pointing at src/hooks/fast-path/*. Those entries are deliberately tiny, avoid React/Effect, and only load the real rewrite/telemetry path when the command contains cargo/hauler tokens.

This solves the performance problem but creates exactly the architectural split #592 is trying to remove: semantic lifecycle events live in src/events/**, while high-frequency hooks need a second handler system because the normal execution kernel cannot short-circuit before expensive route/runtime/provider initialization.

Direction

Add a framework-owned preflight/gate phase to the common execution kernel.

Conceptually:

native host event
   ↓
envelope decode + canonicalization
   ↓
cheap preflight gate       <-- no RSC/React/providers unless requested
   ├─ continue immediately
   ├─ deny immediately
   └─ execute route
          ↓
     providers/layout/rendering

The gate is part of the same event route/application graph, not another host-hook registration model.

Possible authoring forms:

export const preflight = ({ canonical }) => {
  const command = commandFrom(canonical.payload);
  return mentionsCargo(command) ? 'execute' : { outcome: 'continue' };
};

export default async function BeforeTool(props) {
  // full route only runs for relevant events
}

or a convention such as a statically compiled gate export. Exact API is open.

Lazy context/providers

The same issue appears with providers. The framework currently constructs provider values per request before route execution. A high-frequency event that does not need a daemon probe, state store, lineage lookup, etc. should not pay for those values.

Support one or both of:

  • lazy provider resolution on first access;
  • route/gate declarations of required providers;
  • a preflight context that contains only canonical event data, signal, terminal/host capability metadata, and explicitly cheap values.

Preserve deterministic provider ordering once providers are actually materialized.

Compiler/runtime requirement

The emitted hook entry must be physically cheap, not merely logically early inside the full bundle. The compiler should be able to emit a small preflight shell that imports the heavier route/runtime only after the gate says execute.

This is similar to middleware edge-gating in a web framework: the optimization has to exist in the entry graph, not after the application bundle is already loaded.

Relationship to config-declared hooks

Do not remove config handlers until routed events can meet the same latency/runtime characteristics. After this lands, config-declared handlers can remain an escape hatch for genuinely raw/native behavior, but should not be required for ordinary semantic events that need a cheap rejection path.

Acceptance

  • A src/events/tool/before route can reject/continue a non-matching event before loading the rendered route runtime.
  • The generated preflight entry imports no React/RSC renderer or application providers until execution is requested.
  • Preflight sees the same canonical event payload the route would see; no host-native parser duplication is required.
  • Providers can be avoided for routes/gates that do not read them.
  • Host envelope validation, capability translation, timeout handling, and outcome validation remain framework-owned.
  • Performance fixture demonstrates a no-op shell event near plain Node/process startup cost and materially below a full rendered route.
  • cargo-hauler can move src/hooks/fast-path/shell-before.ts / shell-after.ts back under the canonical event-route model without regressing perf(test): drop rstest maxWorkers pins, isolate per RSTEST_WORKER_ID #90.

Consumer evidence

Activity

  1. added
    enhancement
    meta-framework
    on Sep 5, 2026
  2. ScriptedAlchemy commented on Sep 5, 2026

    @ScriptedAlchemy
    OwnerAuthor

    Design: one event node, two execution phases

    This will stay inside #592's Application IR → Projection IR → Artifact IR pipeline. A conventional src/events/** module remains the single semantic event route and the single registration point. Its compiled node may carry a framework-owned gate phase; adapters only project that node into native hooks and Artifact IR emits the corresponding executables.

    The common ordering is:

    native envelope bytes
      → bounded decode + host-envelope validation
      → capability translation + canonical event construction
      → preflight gate
           ├─ continue  → validate/project pass-through, exit
           ├─ deny      → validate/project denial, exit
           └─ execute   → load rendered route runtime
                           → resolve declared providers in deterministic order
                           → state/notices/request context
                           → route render
                           → canonical outcome validation
                           → host projection
    

    Envelope size limits, JSON decoding, native host validation, canonical payload/provenance construction, host capability translation, deadline/abort ownership, gate-result validation, rendered-result validation, and host-native output projection remain framework code. A gate never receives or parses a raw host envelope.

    Authoring form

    The route exposes a named preflight function, with the physically-cheap form as a statically followable relative re-export:

    export { default as preflight } from './before.preflight.js';
    
    export default async function BeforeTool({ canonical, signal }) {
      // full rendered event route
    }
    // before.preflight.ts — plain Node/application code, no React/RSC imports
    export default ({ canonical }) =>
      mentionsCargo(commandFrom(canonical.payload))
        ? 'execute'
        : { outcome: 'continue' };

    The static export scanner will attach the relative preflight source to the same event:tool/before Application IR node. This is not a sibling route, config hook, or second handler registry. Restricting the optimized form to a statically followable relative re-export gives Artifact IR an independently bundleable source graph; importing a named function from the rendered route module itself would still evaluate that module's static React/provider imports and would not satisfy the physical cold-start requirement. Invalid, non-function, bare-package, cyclic, or otherwise non-followable preflight exports will produce named build diagnostics rather than silently falling back to the expensive path.

    The gate contract is sync or async:

    export type EventPreflightResult =
      | 'execute'
      | { outcome: 'continue' }
      | { outcome: 'deny'; reason: string };

    undefined, unknown fields/outcomes, an empty denial reason, and denial on an observation-only event fail closed through framework validation. continue means no host decision; deny uses the existing canonical event outcome projection; execute is the only result that loads the rendered route entry.

    Preflight context

    Preflight receives a frozen, deliberately small context:

    • canonical (the exact canonical identity and payload the route would receive);
    • the request signal owned by the hook deadline;
    • translated host/terminal capability metadata that is already available without application code;
    • explicitly framework-owned cheap values only.

    It does not receive native, state, notices, lineage stores, rendered layouts, application providers, React/RSC helpers, or the application request context. Host-specific raw/native behavior remains the documented config-declared handler escape hatch.

    Provider laziness

    For this change, laziness is declaration-driven rather than a Promise-valued property proxy (which would break the existing synchronous (await agent()).providers.<key> contract):

    • preflight materializes zero application providers;
    • an executed route with no provider declaration preserves compatibility by resolving all conventional providers;
    • an event route may statically declare the provider keys it requires; only that ordered subset is loaded/resolved;
    • selected providers materialize sequentially in the existing deterministic key/source order, once per request, fail closed, with processLifetime seeded first;
    • duplicate/unknown provider keys are build diagnostics.

    This preserves existing provider value types and ordering while letting ubiquitous event routes explicitly avoid unrelated daemon/state/provider work. The compiler will keep provider imports out of the preflight executable entirely; they enter only the deferred rendered-runtime graph.

    Artifact and proof plan

    Projection IR will retain one projected hook per semantic event. Artifact IR will emit a small self-contained preflight shell plus the existing rendered worker/runtime. The shell stays bundled under the current compiler policy (autoExternal: false, bundle: true, splitChunks: false, no framework-added externals); AB6005 continues walking the produced bytes. A graph test will assert that the preflight executable reaches neither React/RSC renderer modules nor application provider sources before the execute import boundary.

    Acceptance evidence will include N-run medians for a no-op shell event versus node -e '' and the full rendered route (wall time and max RSS), plus a scratch packed/preview cargo-hauler migration showing shell-before.ts / shell-after.ts can become event preflights without regressing cargo-hauler#90. Config-declared handlers remain supported as the raw/native escape hatch, not the ordinary semantic-event fast path.

  3. ScriptedAlchemy commented on Sep 5, 2026

    @ScriptedAlchemy
    OwnerAuthor

    Execution-kernel trace surface for #600: this change exports a frozen, payload-free EventTraceEvent discriminated union (preflight.start, preflight.outcome, execute.start, provider/render start+finish, terminal failure) plus EventTraceExecution, bounded EventTraceErrorSummary, eventTraceExecution, createEventTracer, and installEventTraceObserver. Events share execution identity, monotonic timestamp/sequence, and phase-only metadata; absent observers are no-ops and observer failures cannot affect hook execution. The generated preflight kernel emits gate and deferred-execute boundaries through the process-local observer. The surface is exported from agent-bundle and agent-bundle/api, with bilingual authoring docs.

  4. ScriptedAlchemy commented on Sep 5, 2026

    @ScriptedAlchemy
    OwnerAuthor

    Closed by #618 (merge ef2abbaccc0e96ad1943de659b75b057336d4f47).

    Final proof: the generated preflight entry measured 0.06 s / 51,248 KiB median over 7 cold runs for an irrelevant shell command, versus the cargo-hauler #90 routed-hook baseline of approximately 0.10 s / 64 MB RSS. A scratch cargo-hauler migration using locally packed artifacts moved shell-before/shell-after under conventional tool/before and tool/after routes with preflight gates; build, typecheck, route tests, and inspect passed. This is the consumer migration path tracked by cargo-hauler #107. The artifact graph tests also prove the public shell excludes React, RSC rendering, route layouts, and application providers until execute, while both shell and deferred executor remain AB6005-clean.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementmeta-framework

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions