Repository navigation
Description
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/beforeroute 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.tsback under the canonical event-route model without regressing perf(test): drop rstest maxWorkers pins, isolate per RSTEST_WORKER_ID #90.
Consumer evidence
ScriptedAlchemy/cargo-hauler/issues/90ScriptedAlchemy/cargo-hauler/agent-bundle.config.ts- Meta-framework architecture: one application graph, capability-driven projections, one execution kernel #592
Activity
ScriptedAlchemy commentedon Sep 5, 2026
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:
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
preflightfunction, with the physically-cheap form as a statically followable relative re-export:The static export scanner will attach the relative preflight source to the same
event:tool/beforeApplication 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:
undefined, unknown fields/outcomes, an empty denial reason, and denial on an observation-only event fail closed through framework validation.continuemeans no host decision;denyuses the existing canonical event outcome projection;executeis 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);signalowned by the hook deadline;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):processLifetimeseeded first;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);AB6005continues walking the produced bytes. A graph test will assert that the preflight executable reaches neither React/RSC renderer modules nor application provider sources before theexecuteimport 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 showingshell-before.ts/shell-after.tscan 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.ScriptedAlchemy commentedon Sep 5, 2026
Execution-kernel trace surface for #600: this change exports a frozen, payload-free
EventTraceEventdiscriminated union (preflight.start,preflight.outcome,execute.start, provider/render start+finish, terminalfailure) plusEventTraceExecution, boundedEventTraceErrorSummary,eventTraceExecution,createEventTracer, andinstallEventTraceObserver. 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 fromagent-bundleandagent-bundle/api, with bilingual authoring docs.refactor(events): remove trivial preflight accessor and redundant wra…
feat(events): add cheap preflight gates (#618)
ScriptedAlchemy commentedon Sep 5, 2026
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/beforeandtool/afterroutes 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 untilexecute, while both shell and deferred executor remain AB6005-clean.