Skip to content

feat(studio): add exact plan control and authorization review prerequisite - #1909

Merged
samuv merged 33 commits into
mainfrom
impl/studio-chat-approvals-review-escape
Sep 25, 2026
Merged

samuv merged 33 commits into
mainfrom
impl/studio-chat-approvals-review-escape

Conversation

@samuv

@samuv samuv commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Tracking: #1848

Stage and approved contract

Implementation, release prerequisite. This PR targets main and is based on the merged Plan / Interface PR #1888, merge commit 98dfad2e1bed66809f68b104c4f207df2d2b1dda. The plan is in progress on this branch. The directing human previously waived the plan-merge gate while #1888 was open and authorized the direct call-ID, server-owned continuation, lease-loss, ADR-number, and protobuf-field amendments; those amendments are included in the merged plan and ADR 0366.

Included

  • Exact ResolvePlanAsk gRPC and HTTP controls bind a verdict to the authorized session, expected run, pending root plan ask, and explicit verdict. Stale, duplicate, ordinary, and child asks cannot approve a successor. Optional PermissionAsk.call_id = 6 projects the durable call ID for presentation correlation only, never verdict authority.
  • Normal prompts retain client-owned plan continuation. Studio can opt a run into server-owned continuation with Prompt.server_owned_plan_continuation = 4, its HTTP mirror, and the SDK run option. Unopted live asks reject strict verdicts without consuming them; opted-in live asks reject in-stream plan approval. Existing mecatui and SDK query() keep client-owned continuation.
  • The daemon reserves one accepted continuation before the plan terminal, prioritizes it over competing prompts and retries, and releases it on every exit. A known failed proceed start appends and publishes a content-safe plan.continuation_failed event (Event.plan_continuation_failure = 26) while the daemon holds the lease. After lease loss the former owner emits no failure and the outcome remains uncertain. The original plan run retains one terminal result. Without an event log, the strict feature and opted-in starts are unavailable.
  • The SDK feature-gates opt-in and exact verdicts, verifies run/ask acknowledgements, rejects incompatible responders and retry opt-in, and projects the failure event. Generated protocol and SDK references, engine API snapshot, changelog, and public documentation are updated.
  • Studio's external authorization review uses an authenticated same-origin new-tab presentation route and exact session/authorization-ID Recheck and Cancel controls. It correlates handoffs with proven run/call identity, reconciles ambiguous outcomes from durable activity, and avoids duplicate continuation rows on replay. The presentation route rejects cross-site navigation before fetching the live URL. Permission evaluation remains deny-dominant.

Acceptance status and dependency

AC2.2, AC3.1, and AC3.2 are complete in this slice. AC1.1's call-ID projection and AC2.3's SDK control and run-start option are enabling work; their browser interactions remain pending. Ordinary inline approvals, plan-review submission and continuation UI, layered Escape, shortcut hints, steer trace, and the #1776 offline browser journey remain in five pending #1848 tasks. This PR does not close #1848 or mark the plan landed.

Studio consumes npm-published SDK packages under ADR 0351. The published @stacklok-oss/[email protected] lacks these new controls and projection. The remaining Studio browser controls therefore wait for a reviewed SDK release from main; no local SDK path or session-only verdict fallback is used.

Interfaces match the merged approved contract: Yes for this implemented slice. The merged #1888 plan includes every human-authorized amendment. The review repairs add no contract deviation. Human merge and SDK publication remain separate steps.

Review and verification

The review's blocking retry race was reproduced and fixed: RetryFailedRun now shares the reservation guard used by prompt entry. Focused tests prove one proceed run and no false failure event. Other repairs add a classified, content-safe failure diagnostic; make Refresh activity work for idle sessions; checkpoint the exact authorization handoff before a cursorless control; preserve stream deduplication across replay; restrict the presentation GET to same-origin browser navigation; and document SDK event fields. The activity cursor now belongs to the exact session, run, authorization, and call, so replay of an older pending event cannot clear uncertainty. Durable EvApproval.Actor now uses the accepted exact verdict caller for plan, ordinary, and scoped asks, while in-stream approvals retain the run caller and an unverified control caller remains absent. Accepted surfaced child verdicts now produce one safe approval on the parent run before its terminal result; aborted sends requeue for the terminal sweep, and the configured event sink observes the same approval-before-result order. Child arguments stay out of that record and an empty call ID prevents parent permission rule replay from a colliding child ID. The SDK high-level surface inventory includes resolvePlanAsk after #1917 merged. The relay can still wait behind another holder of the session entry lock before the old stream closes; moving that lock acquisition is deferred because it affects terminal persistence and gRPC handoff ordering.

Focused server package and race tests, engine child-approval race tests, Studio mounted tests (43/43 on the combined cursor repair), presentation route tests, SDK exact-plan and high-level surface tests (11/11), SDK generated-reference checks, acceptance-plan validation, CGO_ENABLED=0 task docs, site build, and diff checks passed during the review repairs. The local macOS default CGO linker is broken; focused Go race tests passed with the installed macOS SDK. Follow-up Domain, Test adequacy, and Security rechecks found no unresolved blocker in the reviewed slice.

The earlier b99ad336d head passed all 33 applicable GitHub Actions checks. The next head exposed a test-only router wrapper to the pinned engine linter; it was removed and the tests now call the production resolution path. PR CI on the rebased 7e7e5f7f0 head passed: 34 checks successful, four optional/live checks skipped, zero failures or pending checks. This includes Analysis, Lint, root and engine race suites, Studio, SDK codegen and offline e2e, kind, performance, docs, and build.

@peppescg

Copy link
Copy Markdown
Contributor

Implementation review: #1909

CI is green. The identity checks are solid:

  • Live path: validates generation, cancelling state, exact run and lease under persistMu and s.mu.
  • Restored path: preserves the resumeMu→runEntryMu lock order and revalidates after acquireLease.
  • Double submit: resolvePlan checks origin and deletes under one lock, so a second submit gets ask_not_pending.
  • Other asks: child asks and ordinary asks are rejected.
  • call_id = 5: optional, passed through valid() in the mapper, never used for authority.
  • SDK resolvePlanAsk: gates on the capability before any RPC, checks the run and ask echoes, and never retries a verdict.
  • Authorization redirect: http/https allowlist, noopener noreferrer, CSRF on the POST routes. The security.ts change only adds a header.
  • Diff size: the large deletions are regenerated code only.

Needs changes

  1. The planContinuation reservation leaks. Only finishExactPlanRun (exact_plan_ask.go:225) releases the detachedControlWG count and the detached context. Failure scenario:

    1. The plan run ends StopPlanApproved.
    2. Before the relay's deferred finishRelayRun runs, another StartRunContent takes runEntryMu. That can be a user prompt, a scheduler delivery or a legacy client.
    3. startRunContentLocked (service.go:4650) sees the terminal snapshot and calls deregister → removeRunState (service.go:7977), which never touches st.planContinuation.
    4. finishExactPlanRun then sees st.run != run and returns false.

    The result:

    • the WaitGroup never drains, so every later Service.Close blocks until engineCloseTimeout;
    • the detached context's shutdown hook leaks;
    • the approved proceed run silently never starts.

    The comment in startRunContentLocked about runEntryMu only covers the window after finishExactPlanRun has taken the lock. The other deregister callers have the same exposure.

    Fix: release the reservation in removeRunState, or refuse and repair in startRunContentLocked while planContinuation != nil.

  2. A live allow races clients that continue on their own. mecatui and the SDK query() fire their own proceed prompt after plan_approved, so a live allow on a run they own races the server continuation. That race either fails the client's proceed call or triggers the leak in item 1. This needs a rule in ADR 0362 (see my comment on docs(plan): define Studio chat approvals and exact plan control #1888).

Minor

  • Converse stream held open: finishExactPlanRun runs inside the Converse/SSE handler's defer and holds runEntryMu through startRunContentLocked. That call includes lease acquisition, engine rebuild and awaitContextWindow, so the old stream's close waits for the whole start.
  • Continuation failure only logged: a continuation that fails to start is only a diagnostics WARN (exact_plan_ask.go:252). Legacy approvePlan emits EvResult{StopError}.
  • Sticky "uncertain" state (authorization-review.tsx:158): AuthorizationReview keeps a local uncertain flag that is never cleared, and the component is rendered without a key. An ambiguous Recheck on handoff A therefore disables Recheck and Cancel on handoff B. Add key={sessionId+authorizationId} or drop the local state; the workspace-level authorizationUncertain already exists.
  • No way out of workspace uncertainty: authorizationUncertain clears only on a non-pending authorization.resolved. If the handoff really is still pending, Recheck and Cancel stay disabled until a full reload, even though the alert suggests "Refresh activity".
  • Test gaps in exact_plan_ask_test.go:
    • The live allow test calls svc.FinishRun by hand, so the relay-defer hand-off is never exercised.
    • Nothing covers a competing StartRunContent between the terminal and relay finish, or Close timing after an accepted allow.
    • Nothing covers live concurrent verdicts, rejection of a live ordinary or child plan ask at the Service level, or EvApproval landing in the event log.
  • Nits:
    • routes/chat.ts:711 redirects to the raw url instead of destination.href, so a control character gives a 500 instead of the intended 502.
    • docs/acceptance/README.md says proposed while the plan header says in-progress.
    • ADR 0362 is still Proposed.

Scope note: the PR delivers the daemon and SDK half plus Scenario 3. The plan card, inline ordinary-ask card, Escape layering and steer trace (AC1.x, 2.1, 2.3, 4.x, 5.x) are still to come. That matches the "prerequisite" title and the rollout order, and nothing overclaims.

samuv added a commit that referenced this pull request Sep 25, 2026
Address the #1888 and #1909 review with a run-start opt-in and a correlated continuation-start failure event.

Co-Authored-By: Codex <[email protected]>

Signed-off-by: Samuele Verzi <[email protected]>
@samuv samuv self-assigned this Sep 25, 2026
Base automatically changed from impl/studio-chat-transcript-composer to main September 25, 2026 12:37
samuv added a commit that referenced this pull request Sep 25, 2026
Address the #1888 and #1909 review with a run-start opt-in and a correlated continuation-start failure event.

Co-Authored-By: Codex <[email protected]>

Signed-off-by: Samuele Verzi <[email protected]>
@samuv
samuv force-pushed the impl/studio-chat-approvals-review-escape branch 2 times, most recently from 7c9f61b to 0007e78 Compare September 25, 2026 12:59

@peppescg peppescg left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed head b99ad336. Most of my earlier findings are fixed:

  • Reservation leak: removeRunState now releases the reservation exactly once, and startRunContentLocked refuses a competing entry under persistMu.
  • Double continuation: there is a run-start opt-in on gRPC and HTTP. A non-opted live ask is refused without being consumed, and an in-stream plan frame on an opted-in run is refused.
  • Failed continuation start: plan.continuation_failed is appended and published, content-safe, and lease-gated. Without an event log the feature is not advertised.
  • Proceed-run start: it now runs in a goroutine.
  • Studio side: the uncertain-state key, the destination.href redirect and the README status are all fixed.

Also verified:

  • Lock order, lease and owner checks are correct.
  • Guardrail reconciliation is correct.
  • Proto field numbers don't collide, and task generate leaves no diff.
  • api:check and the CHANGELOG are correct.
  • The ADR 0027 inventory rows are present.
  • The tests run under -race over real gRPC and HTTP relays.

Blocking

  1. RetryFailedRun destroys an accepted plan continuation. In internal/adapter/server/service.go (RetryFailedRun), a registered run whose snapshot is terminal is deregistered. This happens before the eligibility check and without the reservation guard that startRunContentLocked now has.
    • Scenario:
      1. An opted-in plan run reaches StopPlanApproved.
      2. Before its relay calls finishRelayRun, a caller invokes RetryFailedRun (for example, a retry click).
      3. removeRunState records plan.continuation_failed, attributed to the retry caller, and releases the reservation.
      4. The retry returns "not eligible".
      5. The relay then finds no reservation, so the approved proceed run never starts.
    • Reproduction: copy the "priority over a competing prompt" subtest and swap StartRunContent for RetryFailedRun. The event log then shows result, plan.continuation_failed, and waitExactPlanProceed fails.
    • Why it matters: this violates ADR 0366 Decision 3.
    • Scope: the other deregister callers (approvePlan, autoApproveContinuation, and the two in mcp_authorization.go) only remove runs they started themselves, so this is the only gap.
    • Fix: apply the same reservation guard, ideally through one helper shared with startRunContentLocked, and add a regression test.

Minor

  1. The start-failure WARN drops the cause. exact_plan_ask.go:283 doesn't log err from startRunContentLocked, so operators can't see why the proceed run failed. The event must stay content-safe; the diagnostic doesn't have to. Also consider downgrading it, since the event already owns the fact.
  2. "Refresh activity" can silently do nothing. refreshAuthorizationActivity only bumps reconnectGeneration, and the watch effect returns early when !watchable. Scenario: a Cancel commits on the daemon but its response is lost, and the session goes idle. The card then stays "Pending" with both actions disabled until reload. With no beforeCursor, the refresh replays without the reconciliation callback, so a still-pending handoff can't clear either. Either disable the button when a refresh can't run, or report "no newer activity".
  3. A resumed refresh can duplicate transcript content. The current messages are kept, and events after beforeCursor are replayed with a fresh deduplicator. If the control stream had already rendered part of the continuation run, its tool rows or text appear twice. No test covers a continuation that had rendered output before the failure.
  4. Hardening: the presentation route has no same-origin check. The GET under /api/v1/.../presentation isn't covered by the same-origin check that guards mutations. A cross-site top-level link, where the Lax cookie is sent, still gets a 302 to a fresh authorization page. The only legitimate caller is the same-origin <a target=_blank>, so requiring Sec-Fetch-Site: same-origin is cheap.
  5. Minor: the relay defer still takes runEntryMu synchronously. It runs completeRelay under that lock (exact_plan_ask.go:250-264), so the old stream's close can wait behind another holder of that session's entry lock.

Nit

  • PlanContinuationFailureEventPayload.planRunId and askId show as "(undocumented)" in the three etc/*.api.md reports.

@samuv
samuv force-pushed the impl/studio-chat-approvals-review-escape branch from b99ad33 to 977e291 Compare September 25, 2026 13:43
samuv and others added 14 commits September 25, 2026 15:59
Co-Authored-By: OpenAI Codex <[email protected]>

Signed-off-by: Samuele Verzi <[email protected]>
Co-Authored-By: OpenAI Codex <[email protected]>

Signed-off-by: Samuele Verzi <[email protected]>
Present authorization status on the originating tool call, redirect through a fresh BFF presentation URL, and stream exact recheck or cancel flows with their continuation events.

Co-Authored-By: Codex <[email protected]>

Signed-off-by: Samuele Verzi <[email protected]>
Bind plan verdicts to the authorized run and pending ask, preserve plan provenance, and start one server-owned proceed run after an accepted plan terminal. Publish strict gRPC and HTTP controls and durable tool-call correlation in the generated contracts.

Co-Authored-By: Codex <[email protected]>

Signed-off-by: Samuele Verzi <[email protected]>
Add feature-gated plan verdict control with run and ask echo checks across gRPC and HTTP. Project optional permission ask call IDs and update the public SDK reports and method reference.

Co-Authored-By: Codex <[email protected]>

Signed-off-by: Samuele Verzi <[email protected]>
Co-Authored-By: OpenAI Codex <[email protected]>

Signed-off-by: Samuele Verzi <[email protected]>
Co-Authored-By: OpenAI Codex <[email protected]>

Signed-off-by: Samuele Verzi <[email protected]>
Read the live run state under the service lock in both exact plan ask paths, preserving the existing exact run and ask rechecks.

Co-Authored-By: OpenAI Codex <[email protected]>

Signed-off-by: Samuele Verzi <[email protected]>
Key uncertainty to its handoff, refresh from the last observed durable cursor, and preserve separate runless authorization statuses. Redirect using the validated presentation URL and document the recovery action.

Co-Authored-By: Codex <[email protected]>

Signed-off-by: Samuele Verzi <[email protected]>
Require a streamed authorization status to match the pending review card’s call before confirming a control. A mismatched status now leaves the outcome uncertain and blocks duplicate controls until activity is reconciled.

Co-Authored-By: Codex <[email protected]>
Signed-off-by: Samuele Verzi <[email protected]>
samuv and others added 13 commits September 25, 2026 15:59
Consolidate run stream handling for chat and authorization routes.

Co-Authored-By: OpenAI Codex <[email protected]>

Signed-off-by: Samuele Verzi <[email protected]>
Co-Authored-By: OpenAI Codex <[email protected]>

Signed-off-by: Samuele Verzi <[email protected]>
Share the terminal run admission guard across prompts and failed-step retries so a completed plan run cannot be removed while its exact allow has reserved a proceed run. Cover the blocked terminal relay and record a content-safe start failure code in diagnostics.

Co-Authored-By: OpenAI Codex <[email protected]>

Signed-off-by: Samuele Verzi <[email protected]>
Signed-off-by: Samuele Verzi <[email protected]>

Co-Authored-By: OpenAI Codex <[email protected]>
Keep parent approval correlation metadata safe across child and parent call ID collisions. Flush accepted verdicts before parent terminal events, including cancelled and abandoned children, and mirror sequenced events to the injected sink.

Signed-off-by: Samuele Verzi <[email protected]>

Co-Authored-By: OpenAI Codex <[email protected]>
samuv and others added 4 commits September 25, 2026 16:25
Keep stale routes retractable, requeue aborted approval emits, and emit final child verdicts outside the registry lock. Return stale compatibility approval errors and mirror sequenced child events to the sink.

Signed-off-by: Samuele Verzi <[email protected]>

Co-Authored-By: OpenAI Codex <[email protected]>
Mirror accepted child approvals before releasing the child emission gate, then allow the terminal result to follow. Pin concurrent close order and child abort behavior.

Signed-off-by: Samuele Verzi <[email protected]>

Co-Authored-By: Codex <[email protected]>
Wait for the parent terminal to remain blocked while the accepted approval sink callback is parked. This makes the prior mirror-after-unlock ordering fail reliably.

Signed-off-by: Samuele Verzi <[email protected]>

Co-Authored-By: Codex <[email protected]>
Exercise routeResolution directly in child router tests and retain accepted, duplicate, and stale verdict assertions.

Signed-off-by: Samuele Verzi <[email protected]>

Co-Authored-By: Codex <[email protected]>
@samuv

samuv commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor Author

Addressed the requested changes on the rebased #1909 head 2e84eb334:

  • RetryFailedRun and prompt entry now share the terminal-run deregistration guard. A retry cannot remove a run with an accepted plan continuation. The regression pauses the terminal relay, races both competing entries, then proves one proceed run and no false plan.continuation_failed event.
  • A failed proceed start records a safe diagnostic error code alongside the content-safe durable event. The diagnostic test checks that the error is classified without copying the sensitive underlying detail into the event or log.
  • Refresh activity now runs for an idle session after a lost authorization-control response. The browser checkpoints the exact session/run/authorization/call handoff before submitting a cursorless control, reconciles from that cursor, and preserves deduplication if continuation content was already rendered. Mounted tests cover both a completed cancellation and a still-pending handoff.
  • The authorization presentation GET requires same-origin Fetch Metadata before requesting a fresh URL. The generated SDK API reports now document the continuation failure IDs.
  • Exact live plan, ordinary, and scoped approval records use the verified verdict caller as actor. Accepted surfaced child verdicts are recorded once on the parent run before its result, with no child arguments or parent permission-rule call ID. A stopped reader requeues an unsent approval for terminal accounting; the event sink retains approval-before-result order. The sink-order regression failed against the old ordering and passes on this head.

The relay defer still waits synchronously for runEntryMu before the old stream closes. Moving that lock acquisition changes terminal persistence and gRPC handoff ordering, so I left that timing change for a separately reviewed design.

This is still the partial daemon/SDK and authorization slice described in the PR, with the remaining Studio approval and review controls awaiting a published SDK release. The PR remains open for human review; it is not a completed #1848 implementation.

CI on 7e7e5f7f0 has finished: 34 checks passed, including Analysis, Lint, Studio, SDK, docs, build, both root race jobs, kind, and performance. Four optional/live checks were skipped; none failed or remain pending.

@peppescg peppescg left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving. The RetryFailedRun blocker is fixed. The remaining points are minor, so they can be addressed in a follow-up PR if needed.

@samuv
samuv merged commit b09f573 into main Sep 25, 2026
38 checks passed
@samuv
samuv deleted the impl/studio-chat-approvals-review-escape branch September 25, 2026 15:10
This was referenced Sep 25, 2026
samuv added a commit that referenced this pull request Sep 25, 2026
Record that #1909 supplied authorization prerequisites while #1848 layered Escape browser work is still pending. Keep the #1850 acceptance contract proposed and its frame ownership unchanged.

Co-Authored-By: OpenAI Codex <[email protected]>

Signed-off-by: Samuele Verzi <[email protected]>
jbeda added a commit that referenced this pull request Sep 25, 2026
…mit-coauthor-guidance

* origin/main: (32 commits)
  docs: plan optional native Kubernetes execution provider (#1579)
  feat(mecatui): restore session status metrics (#1891)
  docs(plan): bound agent inventory viewport (#1946)
  docs: include user-docs in matlatl and use local documentation links (#1934)
  feat(mecatui): bound sessions inventory (#1944)
  feat(studio): show session delegation activity (#1907)
  docs(plan): define Studio session activity (#1885)
  Release TypeScript SDK v0.4.0 (#1940)
  Release v0.0.41 (#1941)
  docs(mecatui): plan bounded sessions inventory (#1906)
  feat(studio): add exact plan control and authorization review prerequisite (#1909)
  test(app): eliminate real ToolHive probe deadline wait (#1937)
  docs(plan): define Studio chat approvals and exact plan control (#1888)
  test(sdk): enforce SDK/TUI high-level parity (#1471) (#1917)
  docs(plan): propose SDK high-level parity coverage (#1471) (#1916)
  docs: improve gRPC schema table readability (#1842)
  test(app): eliminate real waits in durable learning tests (#1933)
  feat(studio): align chat transcript and composer (#1886)
  docs(plan): define Studio chat transcript and composer (#1880)
  feat: correlate provider requests with the root session (#1883)
  ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Studio chat: inline approvals, plan review, and Escape behavior

2 participants