Repository navigation
Conversation
|
Codex review: needs maintainer review before merge. Reviewed August 20, 2026, 3:25 AM ET / 07:25 UTC. ClawSweeper reviewWhat this changesThis PR makes deferred context-engine maintenance preemptible, fenced, quarantined on timeout, and able to return visible recovery guidance instead of blocking later messages. Regression provenancePossible regression — probable (reproduction; reviewed change). No predecessor PR is attributed. Merge readinessKeep this PR open for maintainer review: current main still waits unboundedly for deferred maintenance, while the PR adds a tested preemption and recovery boundary. No discrete patch defect was found; acceptance needs an explicit compatibility decision for the expanded context-engine host contract. Priority: P1 Review scores
Verification
Live VerificationCommand: Result: PASS (completed) Assertions:
Recorded live on the PR head ( How this fits togetherContext engines run optional maintenance after agent turns, sharing a session’s sequencing with later inbound work. The maintenance scheduler, plugin registry, and reply layer together decide whether a foreground turn waits, recovers through the fallback engine, or receives a visible failure. flowchart LR
A[Completed agent turn] --> B[Deferred maintenance]
B --> C[Session task lane]
D[New message or manual compact] --> E[Foreground preemption]
E --> F[Write fence and grace period]
F --> G[Quarantine and fallback]
G --> H[Visible recovery or next turn]
Decision needed
Why: This is a public plugin-contract compatibility choice; source can show the documented existing projection rule but cannot decide the repository’s desired upgrade posture for third-party engines. Before merge
Agent review detailsSecurityNone. PR surfaceSource +465, Tests +677, Docs +10, Other 0. Total +1152 across 29 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Keep the scheduler-owned preemption and fence design, but land only after the context-engine owner accepts the public host-parameter compatibility contract and exact-head checks are green. Do we have a high-confidence way to reproduce the issue? Yes. Current main directly awaits the active maintenance promise; the PR regression drives an abort-ignoring background engine and a same-session foreground admission. Is this the best way to solve the issue? Yes, with the stated compatibility decision. The scheduler owns preemption and fencing, while the registry owns quarantine and fallback rather than adding downstream workarounds. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against 49cd6009cc08. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (7 earlier review cycles)
|
|
@clawsweeper re-review Addressed the prior review:
|
|
🦞🧹 I asked ClawSweeper to review this item again. |
fd2268e to
2ec6f1a
Compare
2ec6f1a to
c2bec2d
Compare
|
@clawsweeper re-review Closes the late-persist fence race flagged in the previous review. What changed:
Why this closes the race: Validation:
Scope unchanged:
Squashed to one commit. |
|
🦞🧹 I asked ClawSweeper to review this item again. |
f62b2ca to
3dc8dd5
Compare
3dc8dd5 to
aba68fd
Compare
aba68fd to
21952fb
Compare
|
Rebased onto latest upstream/main (clean, no conflicts, 72 new upstream commits). New head |
|
Rebased onto latest upstream/main (clean, no conflicts). New head |
|
Fixed the |
|
Rebased onto latest upstream/main. One conflict in |
|
Rebased onto latest upstream/main (clean, no conflicts). New head |
Co-authored-by: Jerry-Xin <[email protected]>
…tivation
Split the plugin registration signal into two axes: the public
registrationMode ('full' only on genuine activation) and a separate
runtime-capability flag. A private runtime handle now registers the
selected context engine with a runtime-usable lifecycle while presenting
'discovery' to plugins, so full-only side-effect branches (provider
broker acquisition, WSL probes, HTTP route registration) no longer fire
during gateway post-ready prewarm for a non-activated handle.
…iring Move the process-scoped SIGINT/SIGTERM abort-signal fan-out out of context-engine-maintenance.ts into a self-contained sibling module so the file stays within the max-lines budget. Pure code move plus import wiring; preemption, write-fence, serialized maintenance, and per-task timeout behavior are unchanged.
…orting Reorder foreground-preemption teardown so the write fence is closed before the scheduler abort fires. Previously abort ran first, leaving a narrow window in which a write initiated from a synchronous abort listener could pass the still-open fence and land a late transcript rewrite after preemption had begun. Closing the fence first makes any such late rewrite a guaranteed no-op (fence-closed rejection), with no change to current execution paths and no ordering dependency between the two statements.
Normal embedded runs resolve their context engine through resolveLogicalTurnContextEngines, but that path neither carried the default-engine metadata needed to record a quarantine nor consulted existing quarantine state. A wedged or timed-out deferred-maintenance run therefore failed to quarantine the engine, and the next logical turn re-resolved the same stuck engine instead of recovering on the fallback. Thread the default engine id into the configured logical-turn wrapper so a host-owned maintenance failure can quarantine that slot (the default engine still never self-quarantines), and skip a quarantined configured engine in favor of the fallback until process restart or re-registration. Record the skip as a typed resolution field so the operator warning picks the correct persistence wording without re-parsing the failure text. Add successor-turn regressions proving the quarantined turn serves the fallback without re-running the wedged factory, and that the default engine is never quarantined.
…nd path Add a regression proving the normal inbound foreground admission preempts an in-flight, abort-ignoring deferred turn-maintenance run for the same session before the successor turn proceeds, via the shared waitForDeferredTurnMaintenanceForSession helper (the call site used by run-orchestrator and the CLI next-turn path), and that the preemption is scoped to the matching session lane and does not abort an unrelated session's maintenance run.
Clarify that the maintain() abortSignal is an additive, optional host parameter: declaring it is opt-in and honoring it is a cooperative optimization, not a correctness obligation. Existing engines remain compatible without changes because the host bounds a wedged run and recovers on the fallback engine even when the signal is ignored.
…text-engine owner resolveSelectedContextEnginePluginIds() previously returned the configured context-engine slot's owner plugin id whenever the slot resolver produced one, even when a non-empty plugins.allow explicitly omitted that id. The prepared runtime path then appended the id through withRuntimePluginIdsAllowed(), which rewrote plugins.allow to include it, and force-activated it — broadening the executable plugin surface past the operator's declared allowlist. Mirror the memory sibling: if the selected plugin id is omitted by a non-empty allow list, return no owner. The prepared runtime then falls back to the core context engine without materializing the allowlist, matching how the memory slot and codex harness paths already treat allowlist omissions. An empty or absent allow list is nonrestrictive (guard is allow.length > 0 && !allow.includes(pluginId)), so operators without an allowlist keep the same custom-vs-core selection they have today. Flip the runtime-plugin test that encoded the bypass: with allow limited to an unrelated plugin, the selected custom context engine must be dropped from plan.pluginIds, plugins.allow must stay ['unrelated-plugin'] (not materialized), and no forced entry may be added. Add a positive counterpart that keeps a context-engine owner when the same id is explicitly listed in plugins.allow, so the guard is proven to fire only on omission.
A private runtime plugin handle presents registrationMode 'discovery' to plugins while still needing the selected context engine usable at runtime. The registrar previously marked such discovery-mode registrations lifecycle 'runtime', which could construct a discovery-conditioned factory that the read-only-discovery contract says must not be built, and it also defeated the promotion path that carries a genuinely runtime-safe factory from the active registry. Register a runtime context-engine lifecycle only for genuine full activation (registrationMode === 'full'). A discovery-mode registration stays read-only, and promoteMatchingRuntimeContextEngineRegistrations supplies the runtime-safe factory from the active registry when the plugin is active there, so the selected engine remains usable without force-constructing a discovery-mode factory.
Switch the runtime-promotion regression to adoptRuntimeContextEngineRegistrations and resolve through the returned cloned registry via the runtime registry scope, matching the current copy-on-write adoption contract. Keep the original discovery handle unmutated and assert the private discovery factory is never constructed.
Extract the runtime quarantine state group from registry.ts into quarantine-state.ts (registry keeps the public re-export) so the file stays under the max-lines threshold. Replace the two non-const type assertions flagged by the assertion-safety ratchet with type-safe constructs: in-operator narrowing for the maintenance error marker and a direct NodeJS.Process annotation for the abort-signal fallback. Adjust the grandfathered baseline for context-engine-maintenance.ts to record the already-removed assertion.
…ask cleanup The owner-scoped task APIs fail closed when they cannot resolve the caller agent id, and a bare (non-agent-scoped) session key yields none on its own. Resolve the agent identity from the session key (session-key parse first, config roster only when a config is already in scope) and forward it as callerAgentId on the cancel/supersede cleanup paths so deferred-maintenance tasks always reach a terminal state instead of silently no-op'ing. Closes the pre-existing bare-key cleanup gap; no behavior change for agent-scoped session keys.
|
@clawsweeper re-review Landed the approved hardening: the deferred-maintenance cancel/supersede cleanup paths in |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
Thanks for the thoughtful work here. We re-tested this on current main with two same-session messages from a real Telegram user and a deliberately wedged background-maintenance fixture. Both messages received replies; the normal turn path no longer enters that maintenance flow, so the reported failure is not reproducible on main. Closing because the original premise no longer applies. If a currently reachable reproducer emerges, we can revisit it in a focused follow-up. |

What Problem This Solves
Deferred context-engine maintenance can outlive an idle session and block the next message. This PR makes that boundary safe and visible:
/compactasks maintenance to stop and allows one second for cooperative cleanuptimed_outplugins.allowis now honored end-to-end: when the allow list excludes the selected context-engine plugin, the prepared runtime drops that owner and falls back to the core engine instead of rewriting the allow list to include itThose are two parts of one operational fix: safe maintenance recovery, and loading the selected engine into the runtime where that recovery runs — without broadening the operator's execution allowlist. No config, environment variable, command-queue policy, notification policy, or persistent state is added.
Discovery-mode context-engine registrations stay read-only
The prepared-runtime handle presents
registrationMode: "discovery"to plugins (so full-only side effects — broker acquisition, WSL probes, HTTP routes — do not fire during gateway prewarm) while still needing the selected context engine usable at runtime for wedge recovery. A context-engine registration now becomeslifecycle: "runtime"only for genuine full activation (registrationMode === "full"); a discovery-mode registration — including one made under a private runtime handle — staysreadOnlyDiscovery.This honors the documented read-only-discovery contract (
src/plugins/plugin-registration.types.ts; discovery registration skips runtime resources): the resolver short-circuits areadOnlyDiscoveryslot and falls back to the default engine without constructing the registered factory, so a discovery-conditioned, construction-unsafe factory is never built. The selected engine still reaches the prepared handle as runtime-usable through the existing promotion mechanism:promoteMatchingRuntimeContextEngineRegistrations(src/context-engine/registry.ts, called fromsrc/agents/runtime-plugins.ts) carries the genuinely full-activated, runtime-safe factory from the active gateway registry into the prepared handle's read-only slot. Directly marking the private discovery registrationruntime(the earlier approach) both risked constructing a discovery-only factory and defeated this promotion (which only replaces slots that are stillreadOnlyDiscovery), so switching the lifecycle decision toregistrationMode === "full"is strictly safer and keeps the recovery path intact.A regression pins the contract: an active registry holds a runtime-safe factory for the engine, the private prepared handle's discovery-mode registration uses a factory that throws if constructed, and resolving the configured engine under the prepared registry uses the promoted runtime-safe factory (called at least once), never constructs the throwing discovery factory (zero calls), and records no quarantine. A companion loader test asserts a private runtime handle's context-engine registration stays
readOnlyDiscovery.Why This Change Was Made
The deferred-maintenance scheduler owns invocation, preemption, settlement, rerun coalescing, and the host-write fence. The context-engine registry owns quarantine and fallback routing. The prepared-runtime loader owns the private runtime-capable plugin registry and the allow-list boundary for that private handle. The reply boundary carries the producer-owned recovery message to the channel.
OpenAI Codex needs no protocol field. Direct source inspection found no maintenance-debt or cancellation field in
codex-rs/app-server-protocol/src/protocol/v2/thread.rs:95-180; thread-start processing consumes the existing shape incodex-rs/app-server/src/request_processors/thread_processor.rs:810-865. OpenClaw's shared lifecycle therefore owns this behavior.Compatibility:
abortSignaland undeclared enginesThe additive
abortSignalonmaintain()does not break existing undeclared context-engine plugins, because host-parameter projection to undeclared engines is intentional current behavior, not an accidental leak:src/context-engine/registry.ts,projectContextEngineHostParams) returns the full host-parameter set to any engine that does not declareacceptedHostParams. This is the deliberate model afterrefactor(context-engine): retire legacy host param default(refactor(context-engine): retire legacy host param default #122434), which removed the previous date-gated legacy narrowing (its removal window closed 2026-08-12). The retired narrowing is recorded in the compat registry (src/plugins/compat/registry-records.ts) asstatus: "removed", with the note that engines withoutacceptedHostParamsnow receive all current host fields.docs/concepts/context-engine.mdstates that engines without anacceptedHostParamsdeclaration receive every current host field, and that an engine validating a narrower input shape should declare an explicit list (including[]). An engine that strictly rejects unknown keys therefore declaresacceptedHostParamsand is never sentabortSignalunless it lists it. The defaultlegacyengine declares[...CONTEXT_ENGINE_HOST_PARAMS], explicitly opting in.maintain().abortSignalfield is documented insrc/context-engine/types.tsas additive, optional, and cooperative: an engine that ignores it (or never declares awareness of it) is still bounded by the host and recovered on the fallback engine, so no engine is required to change. The registry wrapper enforces this — amaintain()throw is caught, the slot is quarantined, and the fallback engine serves the turn.src/context-engine/host-param-projection.test.tsasserts that fresh and resolved undeclared engines receive every host parameter, includingabortSignal.Gating
abortSignalbehind an explicitacceptedHostParamsmembership would contradict #122434, the documented contract, and those tests, and would also weaken this fix: the normal-inbound foreground-preemption regression (src/agents/embedded-agent-runner/context-engine-maintenance.test.ts) drives an undeclared background engine and asserts itsabortSignalfires so the foreground turn is released. Removing the signal from undeclared engines would strip the cooperative-yield path from exactly the default case #96703 targets, to protect a strict-but-undeclared engine that the quarantine + fallback machinery already protects and that the contract already directs to declareacceptedHostParams.User Impact
Before this change, a background maintenance task that never settled could hold a queued interactive message indefinitely, so the user's next message or manual
/compactappeared to hang with no feedback. After this change, the foreground turn is released promptly: it either proceeds once maintenance yields, or fails fast with visible retry/restart guidance while the stuck task is quarantined to the fallback engine and its late writes are rejected. Operators who configure a restrictiveplugins.allowcontinue to see that allow list respected — a custom context-engine plugin omitted from the allow list is not silently loaded or force-enabled; the runtime falls back to the core engine instead. No user-facing configuration changes; behavior is safe by default.Evidence
Exact head:
0074d2fb81c804b344b8a6524f7abe1c07a97316The fixed behavior was exercised at head
0074d2fb81c804b344b8a6524f7abe1c07a97316against the real maintenance modules driven through the production admission helper, not a single unit assertion. The reproduce entrypoint reads the live git head and asserts it equals the pinned code SHA before the driver runs. A background-mode context engine whosemaintain()ignores its abort signal and never self-settles — the exact wedged condition from the report — is registered through the real plugin registry, resolved via the realresolveContextEngine, and scheduled as real deferred turn-maintenance; a second same-session foreground admission then goes through the exact production helperwaitForDeferredTurnMaintenanceForSession(src/agents/embedded-agent-runner/run-orchestrator.ts:188). The real code paths under test arecontext-engine-maintenance.ts(deferred run, foreground preemption, bounded grace,timed_outterminal state),context-engine-maintenance-abort-signal.ts(realAbortControllerwiring),context-engine-maintenance-fence.ts(write-fence close/drain and late-write rejection),context-engine-maintenance-error.ts(visible recovery guidance),context-engine/registry.tsquarantine + fallback routing withlegacy.registration.ts/legacy.ts,process/command-queue.tsper-session lane serialization, and thetasks/*task-registry terminal status. Only true leaf I/O boundaries are stubbed — the capability lookup, the transcript-rewrite sink,SessionManager.open, and the runtime transcript read target — identical to the shipped unit tests; nothing in the preemption, fence, quarantine, or serialization path is stubbed.performance.now,setTimeout, and the realTURN_MAINTENANCE_PREEMPT_GRACE_MS=1000grace are the real wall clock (no faked time).{"schemaVersion":"wedge-maint-proof/1","verdict":"PASS","headSha":"0074d2fb81c804b344b8a6524f7abe1c07a97316","ranInContainer":true,"containerImage":"docker.io/library/node:24-bookworm@sha256:5711a0d445a1af54af9589066c646df387d1831a608226f4cd694fc59e745059","containerNode":"v24.18.0","wedgedEngine":"background turnMaintenanceMode engine whose maintain() ignores abortSignal and never self-settles","boundedGraceClockMs":1000,"blockedTurn":{"visibleRecoveryGuidance":"⚠️ Deferred maintenance did not stop. The context engine was quarantined, but this turn was stopped to avoid overlapping engine operations. Retry after maintenance finishes or restart the gateway.","elapsedMs":1031,"providerCallsWhileBlocked":0},"recovery":{"abortObserved":true,"quarantinedToFallback":true,"fallbackEngine":"legacy","originalEngine":"wedge-maint-proof-engine","originalEngineMaintainCalls":1,"lateHostRewriteRejected":true,"hostRewriteSinkCalls":0,"originalSettledBeforeFallback":false,"visibleFallbackReply":"Background task timed out: Context engine turn maintenance (run turn-mai).","taskStatus":"timed_out","taskStatusStable":true},"successorResult":{"changed":false,"enteredWedgedEngine":false,"blocked":true,"reason":"successor did not enter the wedged engine before prior run exited (serialized)"},"boundariesReal":["context-engine-maintenance.ts (deferred run, foreground preemption, bounded grace, timed_out terminal)","context-engine-maintenance-abort-signal.ts (real AbortController + signal handlers)","context-engine-maintenance-fence.ts (write fence close/drain, late-write rejection)","context-engine-maintenance-error.ts (visible recovery guidance)","context-engine/registry.ts (real resolveContextEngine + quarantineResolvedContextEngine + fallback routing)","context-engine/legacy.registration.ts + legacy.ts (real fallback engine)","process/command-queue.ts (real per-session lane serialization + task terminal status)","tasks/* task-registry + detached-task-runtime (real terminal status persistence)","waitForDeferredTurnMaintenanceForSession (the run-orchestrator.ts:189 admission helper)","real wall clock: performance.now(), real setTimeout, real TURN_MAINTENANCE_PREEMPT_GRACE_MS=1000ms"],"boundariesStubbed":["context-engine-capabilities.resolveContextEngineCapabilities (LLM/tool capability lookup — pure leaf lookup)","transcript-rewrite.rewriteTranscriptEntriesInSessionManager (transcript write sink — leaf I/O)","sessions/index.SessionManager.open (durable session store open — leaf I/O)","transcript-runtime-state.resolveRuntimeTranscriptReadTarget (runtime transcript read target — leaf I/O)"]}The blocked foreground turn is released within the bounded grace (the real wall clock advanced ~1031 ms, just past the 1000 ms
TURN_MAINTENANCE_PREEMPT_GRACE_MS, before release — versus hanging forever on the never-settling run), with no additional enginemaintain()calls during the blocked window. The successor maintenance only enters after the prior run exits and observes the engine downgraded tolegacy.Foreground-preemption teardown now closes the deferred-maintenance write fence before firing the scheduler abort (previously abort ran first). Closing the fence first makes any write initiated from a synchronous abort listener a guaranteed no-op via the fence-closed rejection, instead of slipping past a still-open fence and landing a late transcript rewrite after preemption has begun. The two statements have no
awaitbetween them, so both effects (fence closed, controller aborted) land in one synchronous tick and any suspended async worker observes them atomically regardless of order; the only observable difference is the synchronous-abort-listener write path, where close-first is strictly safer and never worse. The maintenance/command-queue unit tests remain green (abortSignal.abortedafter preemption and the post-preemption fence-closed rewrite rejection both hold under the new ordering), and no test asserts the old abort-then-close sequence.Logical-turn resolver now honors quarantine on the production recovery path. Normal embedded runs resolve their context engine through
resolveLogicalTurnContextEngines, but that resolver previously neither attached the default-engine metadata needed to record a quarantine nor consulted existing quarantine state, so a wedged or timed-out deferred-maintenance run failed to quarantine the engine and the next logical turn re-resolved the same stuck engine instead of recovering on the fallback. The configured (non-default) logical-turn wrapper now carries the default engine id so a host-owned maintenance failure quarantines that slot (the default engine still never self-quarantines), and a quarantined configured engine is skipped in favor of the fallback until process restart or re-registration. The skip is recorded as a typed resolution field so the operator warning selects the correct persistence wording without re-parsing the failure text. Successor-turn regressions assert that after quarantine the next logical turn is served by the fallback (legacy) with a quarantine failure reason and the wedged custom factory is not re-invoked, and that the default engine is never quarantined.Foreground preemption covers the normal inbound path, not only manual compaction. The mechanism lives in the shared
waitForDeferredTurnMaintenanceForSessionhelper (which triggerspreemptForForegroundon the in-flight run), and the normal inbound admission calls it insiderunEmbeddedAgentInternalbefore the global lane and before the context-engine lease begins, while the CLI next-same-session inference calls the same helper before its run; the manual/compactqueued path adds one further call for its own lifecycle. A regression drives that shared helper against a wedged, abort-ignoring same-session maintenance run and asserts the run is preempted (its abort signal fires and the wait settles within the bounded grace instead of hanging), while an unrelated session's in-flight maintenance run is left untouched — proving the preemption is scoped to the matching session lane.Restrictive-allowlist behavior is now enforced end-to-end for the selected context-engine owner.
resolveSelectedContextEnginePluginIdsinsrc/agents/harness/runtime-plugin-load-plan.tsnow consults the samerestrictiveAllowlistOmitsPluginguard the memory-slot and codex-harness siblings already use, so a non-emptyplugins.allowthat omits the selected engine id causes the resolver to return no owner; the prepared runtime then falls back to the core engine without materializing the allow list or force-activating the excluded plugin. An empty or absentplugins.allowremains nonrestrictive (the guard isallow.length > 0 && !allow.includes(pluginId)), so operators without an allow list keep the same custom-vs-core selection as before, and denylist /enabled: falseremain honored by the shared slot resolver ahead of this guard. A paired pair of regressions insrc/agents/harness/runtime-plugin.test.tsdrives the guard end-to-end throughresolveAgentRuntimePluginLoadPlan: the omitted case asserts the engine is dropped fromplan.pluginIds,plugins.allowstays['unrelated-plugin']unchanged, and no forcedentriesentry is added; the explicitly-allowed case asserts the engine is kept inplan.pluginIds, listed inplugins.allow, and enabled inentries. A fresh independent autoreview on the guard commit confirmed the fix is at the correct layer (the plan resolver, not the shared slot resolver), does not regress the empty-allowlist or denylist paths, and the two regressions exercise the behavior through the production helper.Deferred-maintenance task cleanup now forwards the owner agent identity. The owner-scoped task APIs fail closed when they cannot resolve the caller agent id, and a bare (non-agent-scoped) session key yields none on its own; the cancel and supersede cleanup paths in
context-engine-maintenance.tspreviously passed only the bare session key ascallerOwnerKey, so for bare-key sessions the cleanup lookup could silently no-op and leave the maintenance task non-terminal. The cleanup paths now resolve the agent identity from the session key (session-key parse first, config roster only where a config is already in scope) and forward it ascallerAgentId, so cancelled and superseded maintenance tasks reach a terminal state reliably. This closes the pre-existing bare-key cleanup gap (upstream main uses the same bare-key pattern); behavior for agent-scoped session keys is unchanged. A regression registers a maintenance task under a bare owner key, drives the supersede path, and asserts the task reachescancelledwithnotifyPolicy: silent; removing the identity forwarding fails the regression with the task leftqueued.Additional validation:
waitForDeferredTurnMaintenanceForSessionadmission path, at head0074d2fb81— passed (bounded release ~1031 ms,timed_outterminal, quarantine→legacy, late host rewrite rejected, successor serialized)cancelledterminal state through the forwarded agent identity; identity removal reproduces the silent no-op) — passed (context-engine-maintenance.test.ts)runtime-plugin.test.ts)context-engine.test.ts)readOnlyDiscoveryfor promotion) — passed (loader.runtime-registry.test.ts)context-engine-maintenance.test.ts,host-param-projection.test.ts)git diff --check— passedSize and cleanup
Every production line maps to the single operational invariant: a wedged or timed-out configured-engine maintenance run must yield to a foreground turn, be bounded, recover onto the default engine, reject its late writes, tell the operator, and not broaden the operator's execution allowlist along the way. The net production delta overstates new logic — a large share of
context-engine-maintenance.tsis the abort-signal machinery relocated to a sibling file (counted as a deletion here and an addition there) and therewriteTranscriptEntriesbody re-routed through the fence; the genuinely new machinery is the singleDeferredTurnMaintenanceRunowner that replaces the previous closure-based pseudo-state machine, consolidating completion, abort, fencing, rerun, timeout, and drain behavior.Scope maps to the fix, area by area:
context-engine-maintenance.ts+context-engine-maintenance-fence.ts+context-engine-maintenance-abort-signal.ts— the fix core: foreground preempt, bounded 1 s grace,timed_outterminal state, and a write fence that drains admitted writes so the preempted run and the fallback cannot both write the transcript.context-engine/registry.ts(quarantine +defaultEngineIdplumbing) and the logical-turn resolver — the recovery half: a non-default engine that wedged is skipped for the default on the next turn, and the default engine never self-quarantines.context-engine-maintenance-error.ts+agent-runner-failure-reply.ts+context-engine-logical-turn.ts— turn the blocked admission into visible operator retry/restart guidance with correct quarantined-vs-retried wording (no silent dead-end).context-engine/types.ts— additive, optionalabortSignalon the publicmaintain()host contract; existing engines require no change.compact.queued.ts— applies the same wait/serialize on the manual/compactsibling path so the wedge does not simply relocate.context-engine-maintenance.tscleanup identity forwarding — resolves and forwards the owner agent identity on the cancel/supersede task-cleanup paths so bare-key sessions reach the task terminal state reliably (pre-existing gap; no behavior change for agent-scoped keys).loader-*.ts,registry-api.ts,registry-registrars-capabilities.ts,runtime-plugin-load-plan.ts,runtime-plugins.ts) — the reachability precondition for recovery: the selected installed context engine reaches the prepared runtime handle as runtime-usable through promotion of the genuinely full-activated, runtime-safe factory from the active registry, while the private handle still presentsdiscoveryto plugins and a discovery-mode registration staysreadOnlyDiscovery(so no discovery-only factory is force-constructed). It also honors a restrictiveplugins.allowend-to-end for the selected context-engine owner by mirroring the memory-slot guard. Without this reachability the private runtime would fall back to legacy/discovery-only behavior instead of the engine that actually wedged, so it cannot be split out without weakening the fix. The publicfullactivation signal is the sole gate for a runtime context-engine lifecycle, so full-only side-effect branches do not fire during gateway prewarm.No config, environment variable, command-queue policy, notification policy, or persistent state is added.