Two adjacent gaps cubic flagged on the previous diff:
1. spawner.startTask stored input.agent (potentially prefixed with sort
marker and ZWSP) in setSessionAgent, but the prompt body used the
stripped/normalized form. The session-agent registry therefore did
not match what promptAsync actually dispatched. Capture the
normalized agent once at the top of startTask and use it for
setSessionAgent plus the launch log lines.
2. manager.startTask wrote setSessionAgent(sessionID, input.agent)
before the cancelled and stale-attempt cleanup branches, but those
branches only cleared subagentSessions and the delegated bootstrap.
The session->agent mapping survived as orphan state after an aborted
launch. Call clearSessionAgent inside both early-return paths so
nothing remains tied to a session we just aborted.
Adds focused tests for both: spawner persistence parity with promptAsync
and manager cancellation cleanup leaving getSessionAgent undefined.
Tests that mock an AgentFactory were using an `as AgentFactory` cast
and a separate mutation of `mockFactory.mode` to satisfy the type.
Replace with Object.assign so the factory type is constructed correctly
without casts. Also type the empty discoveredSkills fixture so its
element type is inferred from the function signature instead of
collapsing to never[].
Two call sites built the sync delegate tool gate independently:
sync-prompt-sender's prompt body construction and sync-task's bootstrap
registration. Drift between them would let bootstrap claim one tool set
while the actual prompt sent a different one. Extract buildSyncPromptTools
and route both call sites through it so the registered bootstrap and the
dispatched prompt always agree.
call_omo_agent sync path created the child OpenCode session and went
straight into promptAsync without registering child session agent,
session tools, or bootstrap state. If first dispatch failed before any
durable user message persisted, runtime fallback could not reconstruct
the original prompt or the agent identity for that child session.
Bind setSessionAgent and setSessionTools to the child session id with
the same tool restrictions that the prompt body sends, register a
delegated child session bootstrap with the prompt text, fallback chain,
and prompt tools, then clean bootstrap + session tools in finally for
sessions this call created.
Three coupled gaps surfaced after the initial spawn fix:
1. fallback-retry-handler dropped task.skillContent and
task.sessionPermission when rebuilding LaunchInput, so the retried
background task lost the delegated system prompt and question-deny
permission rule.
2. manager.startTask never bound the child sessionID to the resolved
agent via setSessionAgent, leaving runtime fallback and other hooks
with no idea which agent owned the new child session.
3. The fallback-to-general path in spawner.ts rebuilt the prompt body
without going through buildFallbackBody, so bootstrap state, session
tools, and session agent updates drifted apart.
Persist skillContent and sessionPermission on BackgroundTask, bind
setSessionAgent/updateSessionAgent at session creation and on fallback,
and route the FALLBACK_AGENT retry through buildFallbackBody so the
prompt body, bootstrap tools, and session registries all agree.
When the first prompt fails before any durable user message persists,
runtime fallback retry was rebuilding the request from parts alone and
losing the delegated agent system prompt and tool gates. Now it threads
bootstrap.system and bootstrap.tools into the retry body alongside the
captured retry parts, so the retried prompt keeps the same scope as the
initial delegate launch.
Add optional system and tools fields to DelegatedChildSessionBootstrap
so callers can stash the original delegated context alongside retry
parts. Backward compatible - existing callers stay unchanged.
Preserve delegated child prompt/bootstrap metadata for early runtime fallback before OpenCode has persisted the first user turn. Bind prompt gate calls to the SDK session receiver and keep completed background task lookup visible across plugin manager instances.
Documents the v4.2.0 release window in Keep-a-Changelog format, including prompt gate fixes, internal audits, known issues, and the watchdog supersession history.
Closes LOW-14, LOW-16
New AST-based audit walks all *.test.ts files under src/ and asserts every mock.module(...) call is paired with cleanup. Existing offenders are documented in MOCK_MODULE_LIFECYCLE_ALLOWLIST with TODO references.
Closes HIGH-10
Race-condition and concurrency fixes must include reporter-verified repro confirmation before the originating issue is closed. Adds the checklist and rationale grounded in recent incident examples.
Closes MEDIUM-12
Documents the reservation-based duplicate-injection guard introduced in v4.2.0 with accepted status, exported API signatures, release semantics, migration notes, and commit references.
Closes MEDIUM-11
The promptWithModelSuggestionRetry async variant did not release the
post-dispatch reservation when the wrapped promptAsync threw. Callers
that immediately retry (such as sendSyncPrompt error toast paths) hit
the gate as reserved and surfaced 'promptAsync skipped by gate: reserved'
instead of the underlying error.
Mirrors the existing sync variant fix from ff1b15d53.
Closes regression introduced by BLOCKER-2 hardening
Lines 79/142/428 of prompt-async-gate.test.ts used timer-based synchronization, violating .sisyphus/rules/test-discipline.md which forbids time-based test waits. Replace them with explicit dispatch awaits and mocked-time expiry so the assertions do not depend on CI machine speeds.
Closes BLOCKER-3 (Wave 2 cleanup)
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)
Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
Replace the inlined parent-wake coalescing logic in manager.ts with delegation to the ParentWakeNotifier extracted in c1ccf8d09. The four timer Maps and the related methods now live in their own module with a narrow public API, while BackgroundManager retains the wiring point and the enqueue-callback bridge.
Closes HIGH-9 (step 2: integration)
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)
Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
PR #3825 introduced a delegated child-session bootstrap to capture first-prompt retry payloads before history is persisted, addressing the empty-history fallback gap. After merge the PR's own regression test failed on clean root bun test (6828 pass / 1 fail), so PR #4044 reverted it. Ship v4.2.0 with the bug documented and a workaround so users have an explicit story for the unfixed delegated child-session early-failure path. Reland will target v4.2.1.
Closes BLOCKER-4 (Path B - reland deferred to v4.2.1)
Document all 7+ BLOCKER+HIGH fixes, breaking-change-free additions
(public exports), known issue for delegated child-session fallback
(PR #3825 deferred to v4.2.1), and internal-only changes.
Closes L14
Walk all test files, parse with TypeScript Compiler API, assert every
mock.module(path, factory) invocation has a paired afterEach/afterAll
cleanup. Existing offenders are allowlisted with TODOs for v4.2.1 work.
Closes H10
Test-discipline.md forbids setTimeout(resolve, N) and sleep(N) in test bodies. Replace the 3 microtask and expiry sleeps with explicit microtask yields and deterministic clock advancement, preserving the prompt gate invariants without real-time waits.
Closes BLOCKER-3
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)
Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
PR #3825 added a shared bootstrap context to capture delegated
child-session retry payloads before the first prompt dispatch, so
empty-history failures could still retry through the fallback chain.
The PR's own regression test failed on clean root bun test after merge
(6828 pass / 1 fail). PR #4044 reverted the merge to keep dev green.
Ship v4.2.0 with the bug documented and a workaround so users have an
explicit story for the unfixed delegated child-session early-failure
path. Reland targets v4.2.1 once the regression test is stabilized.
Closes BLOCKER-4 (Path B - documentation, reland deferred to v4.2.1)
Race-condition and concurrency fixes must include reporter-verified repro
confirmation before the originating issue is closed. CI green is necessary
but not sufficient.
Closes M12
PR #3825's fac90d69f introduced a shared bootstrap context to fix delegated child-session fallback when the first prompt fails before any session history is persisted. PR #4044 reverted that fix because its own regression test failed on a clean root suite (6828 pass / 1 fail). The bug remains unaddressed in v4.2.0; reland is deferred.
This commit documents the symptom, history, workaround, and tracking issue so users have visibility.
Closes BLOCKER-4 via Path B (documentation).
Refs PR #3825, PR #4044, issue #4059.
PR #3825 introduced a delegated child-session bootstrap to capture first-prompt retry payloads before history is persisted, addressing the empty-history fallback gap. After merge the PR's own regression test failed on clean root bun test (6828 pass / 1 fail), so PR #4044 reverted it. Ship v4.2.0 with the bug documented and a workaround so users have an explicit story for the unfixed delegated child-session early-failure path. Reland will target v4.2.1.
Closes BLOCKER-4 (Path B - reland deferred to v4.2.1)
After BLOCKER-2's post-dispatch hold landed (the gate now keeps the
reservation through the hold window regardless of whether the dispatch
threw), the synchronous retry path inside promptSyncWithModelSuggestionRetry
hit 'reserved' on its own second attempt because the first attempt's
post-dispatch hold was still active.
The first attempt's failure is ProviderModelNotFoundError, which is a
synchronous SDK rejection - the prompt never reached the server, so
there is no durable session state worth protecting from a duplicate
injection. Release the post-dispatch reservation hold explicitly before
the suggested-model retry so the second attempt can dispatch immediately.
Fixes test regression introduced by the gate hardening (BLOCKER-2 fix).
Extracts the parent-wake coalescing logic (pending/dispatched wake maps,
timers, notification reply assembly) from manager.ts into a standalone
ParentWakeNotifier class. Takes dependency-injected client, directory,
and an enqueueNotificationForParent callback, so the manager can delegate
parent-wake state to a narrow API.
This commit only introduces the new module; wiring manager.ts to use it
is a follow-up commit so the refactor stays atomic (HIGH-9 step 1 of 2).
Closes HIGH-9 (step 1: extraction)
Refs HIGH-9 (step 2: manager.ts integration deferred until verification)
Co-authored-by: manager-extract (deep / gpt-5.3-codex high)
Replaces the previous regex-based audit (6 line-prefix patterns) with a
TypeScript Compiler API AST walker that detects raw client.session.prompt
and client.session.promptAsync access in any access shape:
- direct call (existing): client.session.promptAsync(...)
- property access reference: const x = client.session.promptAsync
- bracket access: client['session']['promptAsync']
- optional chaining: client.session?.promptAsync
- type cast aliasing: (client.session as { promptAsync }).promptAsync
- destructuring: const { promptAsync } = client.session
RAW_PROMPT_ALLOWLIST captures two legitimate callers that route through
the gate but reference promptAsync as a property value:
- src/plugin/event.ts wires a client facade for team-idle-wake-hint
- src/hooks/session-recovery/recover-unavailable-tool.ts guards capability
before dispatching through promptAsyncAfterSessionIdle.
Each allowlist entry carries a justification string so future contributors
understand why the exception exists.
Closes HIGH-5
Co-authored-by: audit-ast (deep / gpt-5.3-codex high)
Adds regression coverage for BLOCKER-1 (dispatch timeout releases
reservation for next caller after stalled upstream) and BLOCKER-2
(post-dispatch error preserves the post-dispatch hold so an immediate
second caller observes the reservation and is gated).
Both tests subscribe-first on the promptAsync call count and assert
status transitions without sleep-based synchronization. dispatchTimeoutMs
is the system under test, so passing it explicitly as 1ms in those tests
is the SUT, not a sleep-as-synchronization (per test-discipline.md).
Closes BLOCKER-3 (dispatch timeout + post-dispatch coverage)
Co-authored-by: gate-tests (deep / gpt-5.3-codex high)
BLOCKER-1 (dispatch deadlock): wrap session.promptAsync / session.prompt in
withDispatchTimeout() that uses Promise.race with a default 30s timeout.
Stalled upstream responses no longer hold the reservation forever.
BLOCKER-2 (post-dispatch failure released too early): collapse the
holdReservationAfterDispatch flag into a dispatchAttempted state so the
post-dispatch hold runs in the finally block regardless of whether
promptAsync resolved or threw. AGENTS.md's documented race window where
promptAsync 'returns before durably accepted, later failures arrive as
session.error' is now covered.
HIGH-6 (sync/async protocol duplicated): extract dispatchAfterSessionIdle
internal runner. promptAsyncAfterSessionIdle and promptAfterSessionIdle
become thin wrappers passing client.session.promptAsync vs prompt as
the dispatch callback. Future reservation semantics fixes apply once.
HIGH-7 (releasePromptAsyncReservation prefix foot-gun, partial): tighten
reservationSourceMatches to require prefix strings to end in ':' so
release cannot accidentally free reservations whose source merely starts
with the same identifier characters. Symbol token verification is still
internal-only as the audit invariant prevents external callers from
bypassing the gate.
Closes BLOCKER-1, BLOCKER-2, HIGH-6
Refs HIGH-7 (prefix hardened; token-required release deferred to follow-up)
Co-authored-by: gate-correctness (deep / gpt-5.3-codex high)
The next release adds public exports for the prompt-async-gate primitives
(promptAsyncAfterSessionIdle, promptAfterSessionIdle,
releasePromptAsyncReservation, DEFAULT_PROMPT_ASYNC_POST_DISPATCH_HOLD_MS)
and introduces new safety semantics that affect 13+ internal hook callers.
Per semver, adding public exports mandates a MINOR bump from 4.1.x.
No public API removals or breaking signature changes, so this is NOT MAJOR.
Closes pre-publish-review version-bump consensus
Co-authored-by: api-surface (deep / gpt-5.3-codex high)
createPluginModule and PluginModuleDeps were exposed at package entry as
a test seam. Their export creates accidental public TS API obligations
for internal manager/tool/hook constructor types. Move to
src/testing/create-plugin-module.ts so only tests reach them.
Closes HIGH-8
Co-authored-by: api-surface (deep / gpt-5.3-codex high)