Repository navigation
refactor(integrations): run the Claude Code and Codex prompt flow from the lifecycle package - #2682
Conversation
Claude Code's scripts/workspace_scope.py and Codex's scripts/scope_binding.py carried the same Scope client: build the session and workspace binding keys, resolve them to a Scope, and bind or clear the workspace. They differed in the integration name in the keys, the User-Agent, and their settings types, and only Codex bound the session to the Scope it resolved. The client now lives once in src/powercontext_integration_lifecycle/, in scope_binding.py. Its functions take the HostProfile, which already names the integration and the User-Agent, and plain ScopeBindingSettings, which keep the credential out of repr. Each plugin's settings class converts itself with scope_binding_settings(); Codex unwraps its SecretStr there instead of in each request. Codex still binds the session through the persist_session option it already passed, and Claude Code still does not pass it. WorkBuddy's client, which carries its own errors and HTTP helpers, is unchanged. The two scripts remain command-line shells with the same paths, arguments, and output. The hooks and the Claude Code status line import the client from the package, so they no longer put scripts/ on sys.path. The SessionStart shells still pass the flow its Scope resolver and error-code reader through BootstrapConnection; both now come from the package client. ty no longer searches the two scripts directories either; only those imports needed them. Because the Claude Code directory came before WorkBuddy's, ty resolved WorkBuddy's own workspace_scope import to the Claude Code script, which type-checked only while that script held the client. Requests and output are unchanged, and the Claude Code and Codex characterization fixtures pass as recorded. The plugin tests patch and call the client in the package module, and the Codex command-line tests check that the script passes the converted settings. The Claude Code tests drop that module between tests like the other package modules; a client cached from an earlier test would raise error classes that the current hooks do not recognize. The status line test for a slow Scope response also runs with a request timeout below the budget: no Claude Code test covered the per-request timeout, which now passes through the settings conversion.
Claude Code's hooks/user_prompt_submit.py and Codex's hooks/recall.py carried the same prompt flow: resolve the Scope, take the session's bootstrap receipt, recall prepared context, capture the prompt, and flush, with the same HTTP helpers, failure classification, and diagnostics. They differed in the integration name in source IDs and metadata, the User-Agent, the diagnostic component, the metadata field for the host's prompt identifier, the payload fields they read, and their settings types. The flow now lives once in src/powercontext_integration_lifecycle/, in user_prompt_submit.py. run_user_prompt_submit() takes the HostProfile, a UserPromptEvent that the hook translates from the host's payload, and PromptSettings. PromptSettings carries the ScopeBindingSettings that the Scope client uses, and the flow's own requests use the same Server, credential, and request timeout. HostProfile gains prompt_id_field, the metadata field in which a captured prompt keeps the host's identifier for it: prompt_id for Claude Code and turn_id for Codex. Each plugin's settings class converts itself with prompt_settings(). A Scope that cannot be resolved becomes a scope_resolve diagnostic, as it did in the hooks, and the result then has no scope_id. The flow scrubs the prompt before it resolves the Scope, so the result always carries the scrubbed prompt; scrubbing has no side effects. Codex's POWERCONTEXT_CODEX_PROMPT_RECALL setting from oceanbase#2453 moves with the flow as PromptSettings.prompt_recall. With it off, the flow sends no prepare request and injects nothing, and it still takes and clears the session's bootstrap receipt, as the hook did. With recall and capture both off, the flow returns before it looks at the event, so the hook sends no request and writes nothing. Claude Code has no such setting and passes prompt_recall=True. The two hooks remain shells with the same paths. They read stdin, match the event name, translate the payload, load settings, start the HTTP budget where each did before, and write the host output. Codex still writes its evaluation trace after the capture, now from the translated event. Codex's token savings hook imports its HTTP helpers from the package module instead of the recall hook. The comment in the WorkBuddy hook, which adapts the same flow, points to the package module. The capability manifest counted a registered prompt hook as complete when its script named the prepare, capture, and flush endpoints. Those requests are now in the package module, so the check also reads the plugin module from which the hook script imports run_user_prompt_submit(), resolved from the plugin root that the hooks put on sys.path. It follows no other imports: Codex's token savings hook imports HTTP helpers from the same module without running the flow, and a test checks that registering it for UserPromptSubmit still counts as incomplete. The test that rewrites a hook's registered command copies whole plugins, without their .venv and __pycache__ directories, instead of their hooks directories, so that the other hosts' hooks still find their modules. One behavior changes, in Codex. When the recall raised an error that the flow does not classify, the Codex hook ended before it captured the prompt. The Claude Code hook has captured the prompt in that case since oceanbase#1237, and both hosts' docs say that recall and capture fail independently. Codex lost the capture when oceanbase#45 narrowed which recall errors it reports, and no test covered it. Responses that break off or cannot be decoded are classified now, so no known Server response reaches this case. Both hosts now lose only the context. A Codex test like the Claude Code one covers it and fails against the previous hook. Requests and output are otherwise unchanged, and the Claude Code and Codex characterization fixtures pass as recorded. The plugin tests patch and call the flow in the package module. The Claude Code tests drop that module between tests like the other package modules. A Codex test checks that the include_code setting reaches the prepare request, which now passes through the settings conversion; no Codex test covered it.
The characterization fixtures give the Claude Code and Codex prompt hooks payloads written by hand. The UserPromptSubmit payloads now in tests/fixtures/recorded_host_payloads were recorded from Claude Code 2.1.277 in a headless claude -p run and from Codex 0.165.0-alpha.1.2 in a codex exec --json run. Codex sends its permission mode, which the characterized payload lacks. The payloads keep every key and value except the session ID, working directory, transcript path, prompt identifier, and prompt, which follow the characterization fixtures. The fixtures group the recorded payloads by hook event; the SessionStart payloads are unchanged. Each recorded payload replaces the payload of the characterized case in which a prompt recalls context and is captured as a Source. It must lead to the same requests, output, and state. A shell that ignored payloads carrying a permission mode would fail only this test. The test also passes before the flow moved into the lifecycle package.
…rompt event's repr UserPromptEvent carries the host's raw prompt and working directory. Nothing logs the event, but its default dataclass repr would print both if a log line or traceback ever showed it. Like the credential in ScopeBindingSettings, the two fields now stay out of repr. A test checks that repr() of an event contains neither.
hidb4ai
left a comment
There was a problem hiding this comment.
Reviewed commit 5a0e4dd. I found no confirmed correctness regression in the shared Scope client and prompt-flow extraction.
Merge readiness remains blocked by kimi-acceptance / controlled-cli (windows-latest): the concurrent/overflowed history test at integrations/kimi-code/plugins/powercontext/tests/plugin.test.mjs:466 expected empty stderr but received runtime_unavailable. The affected Kimi code and workflow are unchanged by this PR, so I am not attributing this failure to the refactor. Please rerun or investigate this required check before merging: https://github.com/oceanbase/powercontext/actions/runs/44004692396/job/133826193722.
Validation limit: my local live-Server suite did not fully pass; three cases failed at Server startup, before exercising the changed hooks, on a heavily loaded machine. This does not establish a defect in this PR, but I cannot independently confirm full live-chain acceptance from this run.
|
please resolve conflicts |
hireview001
left a comment
There was a problem hiding this comment.
- Resolve merge conflicts with the target branch.
…ion-lifecycle-prompt-flow-v3
|
Thanks @hidb4ai; this also answers the hireview001 review. Current master (437aa06) is merged into the branch as 3b2b4a9, without a rebase, so the four reviewed commits are unchanged. The conflicts came from #2669 and #2641, which touch files this PR turns into host shells:
The rest of the PR's diff against master is unchanged apart from hunk offsets. On the Validation at 3b2b4a9:
|
hidb4ai
left a comment
There was a problem hiding this comment.
Re-reviewed 3b2b4a9. The merge resolves the earlier conflicts while preserving Codex fail-closed handling, the host HTTP budget, and Claude Code's 0.1.4 User-Agent. I found no new correctness issue in those resolutions. The previous Kimi failure is no longer present in the current checks.
A different merge gate remains red: dsh-package fails two companion-memory cases at tests/companion-memory.spec.ts:63 and :72 (missing propagated trace parents, and unavailable instead of ready). The DSH implementation and related workflow are unchanged relative to the current base, so this is not established as a regression from this PR. Please resolve or rerun this check before merging: https://github.com/oceanbase/powercontext/actions/runs/44228500069/job/134589768367.
…ion-lifecycle-prompt-flow-v3
|
|
hidb4ai
left a comment
There was a problem hiding this comment.
Re-reviewed 8b95ebf. This is a clean merge of master; the previously reviewed lifecycle implementation is unchanged. The DSH companion fix is now included, so my previous comment about the old DSH failure should not be treated as an outstanding code finding on this head.
I confirmed the current blocker reported above: License Header preflight timed out while building license-eye (about 440 seconds), and downstream tests were skipped. The Upgrade release gate also failed because its upstream result was unavailable, not because an upgrade test demonstrated a failure. Please rerun CI to establish results for this head; I found no new code defect in this update. Run: https://github.com/oceanbase/powercontext/actions/runs/44372213191. Existing approval is left unchanged.
…ion-lifecycle-prompt-flow-v3
|
Merged current |
hireview001
left a comment
There was a problem hiding this comment.
- CI failed: CI result (failure).
- CI failed: Upgrade release gate (failure).
- CI failed: CI preflight (failure).
- CI failed: Main (failure). Failed steps: CI preflight / Run checks; Upgrade release gate / Require the selected parallel acceptance workflow; CI result / Require successful selected checks.
…ion-lifecycle-prompt-flow-v3
|
Post-merge follow-up on final head 5e3d1c3: I found no new correctness regression in the updates since 8b95ebf. The lifecycle implementation is unchanged; the added current-Scope binding for The final CI run still has unresolved validation failures: Python 3.11 unit tests failed in |
Which issue or RFC does this PR close?
Part of #2250, plan step 4: UserPromptSubmit on the shared package. Builds on #2550 (step 3), which moved the SessionStart flow, bootstrap receipts, the diagnostic throttle, bounded HTTP, and the Scope binding errors into
src/powercontext_integration_lifecycle/.Rationale for this change
Claude Code and Codex still carry two copies each of the same code:
scripts/workspace_scope.py,scripts/scope_binding.py): build the session and workspace binding keys, resolve them to a Scope, and bind or clear the workspace;hooks/user_prompt_submit.py,hooks/recall.py): resolve the Scope, take the session's bootstrap receipt, recall prepared context, capture the prompt, and flush, with the same HTTP helpers, failure classification, and diagnostics.The copies differ only in the integration name, the User-Agent, the diagnostic component, the metadata field for the host's prompt identifier, the payload fields they read, and the settings types. This PR moves both into the package and leaves the hooks and scripts as host shells.
What changes are included in this PR?
Four commits, each with the details in its message:
scope_binding.pyin the package.resolve_scope_id,bind_scope,clear_scope_binding, and the binding keys take theHostProfilefirst and plainScopeBindingSettings, which keep the credential out ofrepr. Each plugin's settings class gainsscope_binding_settings(); Codex unwraps itsSecretStrthere. Codex still binds the session throughpersist_session. The two scripts are command-line shells with the same paths, arguments, and output. The hooks and the status line import the client from the package and no longer putscripts/onsys.path, and ty no longer searches the twoscripts/directories. Before, the Claude Code directory came first, so ty resolved WorkBuddy's ownworkspace_scopeimport to the Claude Code script. fix(integrations): report Scope resolution failures from prompt hooks #2317's Scope client classification is in the package module: 503 is unavailable, other error statuses carry the Server's error code,HTTPExceptionis unavailable, undecodable JSON is invalid, and every read checks the declared length.user_prompt_submit.pyin the package.run_user_prompt_submit(host, event, settings, *, deadline)takes theHostProfile, aUserPromptEventthat the hook translates from the host payload, andPromptSettings, and returns aSubmittedPrompt, orNonewhen it skips.HostProfilegainsprompt_id_field(prompt_idfor Claude Code,turn_idfor Codex), and each settings class gainsprompt_settings().scope_resolvediagnostic through the throttle; the flow then sends no prepare or capture request, and the result has noscope_id.POWERCONTEXT_CODEX_PROMPT_RECALLfrom feat(codex): add a setting that turns prompt-time recall off #2453 moves too, asPromptSettings.prompt_recall. With it off, the flow sends no prepare request and injects nothing, and it still takes and clears the session's bootstrap receipt. With recall and capture both off, it returns before it looks at the event, so the hook sends no request and writes nothing. Claude Code has no such setting and passesprompt_recall=True.UserPromptEventkeeps the raw prompt and the working directory out of itsrepr, asScopeBindingSettingsdoes for the credential (fourth commit). A test checks thatrepr()of an event contains neither.tests/test_user_prompt_submit_shells.pyruns each prompt hook as a subprocess with a UserPromptSubmit payload recorded from Claude Code 2.1.277 (claude -p) and Codex 0.165.0-alpha.1.2 (codex exec --json). The recorded payload replaces the payload of the characterizedprompt-recalls-and-capturescase. The recorded fixtures are now grouped by hook event; the SessionStart payloads, Codexforkincluded, are unchanged. The test also passes on the tree before the move.The capability manifest counted a registered prompt hook as complete when its script named the prepare, capture, and flush endpoints. Those requests are now in the package, so
scripts/integration_manifest.pyalso reads the plugin module from which the hook importsrun_user_prompt_submit(), and no other import. A new case checks that registering Codex'stoken_savings.py, which imports helpers from the same module, for UserPromptSubmit still counts as incomplete.Not included: the SessionStart shells still pass the flow the Scope resolver and error-code reader through
BootstrapConnection. Both now come from the package client, so a later change can drop the two fields.Are there any user-facing changes?
One behavior changes, in Codex. When recall raised an error that the flow does not classify, the Codex hook ended before it captured the prompt. The Claude Code hook has captured the prompt in that case since #1237, and both hosts' docs say recall and capture fail independently. Codex lost the capture when #45 narrowed which recall errors it reports. Since #2317, responses that break off or cannot be decoded are classified, so no known Server response reaches this case. A Codex regression test covers it and fails against the previous hook.
Otherwise requests, output, and state are unchanged, and the characterization fixtures pass as recorded.
When a Scope command-line script fails, the traceback frames point at
powercontext_lifecycle/scope_binding.py; the last line, exit status, and stdout are unchanged.Codex's MCP headers helper,
mcp_headers.py, starts more slowly. It only reads the saved credential, but thesettingsmodule it imports now imports the package Scope client andPromptSettings. These loadurllib.requestandhttp.client, and importingtransport.pyrunsbuild_opener(), which creates the default SSL context. Measured on the first three commits before they were moved onto current master (those commits are unchanged), on an Apple M5 Pro with Python 3.13.7 in the plugin's own venv, warm bytecode caches, one-minute load average 5.1–6.5. The three figures in each line are the tree without these commits, after the first commit, and after all three:uv run; CPU time +15–16 ms;Almost all of it comes from the Scope client commit, mostly
transport.py(about 10 ms of import self time); the prompt flow commit adds 3 modules and about 1.3 ms. A follow-up can import lazily in Codex'ssettings.py, or create the opener on the first request.How was this change tested?
At the merge of upstream/master 437aa06 into the four commits (3b2b4a9):
uv run pytest -n 8 --require-claude-code-python-floor tests/test_user_prompt_submit_shells.py tests/test_session_start_shells.py tests/test_integration_lifecycle.py tests/test_hook_characterization.py tests/claude_code_plugin tests/codex_plugin tests/test_integration_manifest.py tests/test_integration_shared_files.py tests/test_hook_diagnostics.py tests/test_automatic_prompt_privacy.py: 813 passed, 4 skipped (by design intest_client_transport.py). The Python 3.9 tests ran on the macOS system Python 3.9.6, and all 57 Claude Code characterization cases also pass under/usr/bin/python3 -S -B.tests/test_ci_changes.py,tests/workbuddy_plugin, andtests/test_cli_workbuddy.py: 232 passed.tests/e2e/test_bootstrap_host_service_chain.py,tests/e2e/test_claude_code_service_chain.py, andtests/e2e/test_codex_service_chain.py, which run the hooks against a real local Server: 20 passed. The real-host cases intests/e2e/test_claude_code_host_service_chain.pyandtests/e2e/test_codex_host_service_chain.pyskip without a host CLI and run in CI'sclaude-code-hostandcodex-hostjobs.test_pre_tool_hook_denies_when_the_plugin_cannot_loadfails when the Scope client import inbind_tools.pyis moved out of its load guard.prompt-recall-can-be-disabledandprompt-recall-and-capture-can-be-disabledCodex cases pass as recorded. Each fails when the flow ignoresprompt_recall, when it skips the both-off check, or when Codex'sprompt_settings()does not pass the setting.make integration-lifecycleleaves no diff, andmake integration-lifecycle-checkpasses.make checkpasses,ty checkincluded.make unit-test: 9166 passed, 437 skipped, 12 failed. Four are intests/test_ci_installation_roles.py, which installs wheels and fails on macOS. Eight are intests/evaluation/test_jev_rerank_comparison.py, which fails with a local pydantic-ai configuration error; this PR changes no evaluation code.git archiveand run against a local SQLite Server with enforced authentication. The Scope holds a Memory tagged for bootstrap and one that only prompt recall can reach.claude -p, hooks on/usr/bin/python33.9.6:resolve_scope_binding,prepare_context, andcapture_content_source(202), and the bootstrap receipt was taken. Resume, fork, and compact injected the bootstrap package as before.systemMessagewas thescope_resolvediagnostic (invalid_response, 404,scope_not_found), which headless mode shows as a notice. The Server received only the two resolve requests, with no prepare or capture.scope_resolveserver_unavailable.CODEX_HOMEwith the plugin's hooks trusted:codex exec --json, asked for the recall-only marker: the model answered it. The rollout has one developer message with the bootstrap package and one with the recalled Memory. The Server recordedresolve_scope_binding,prepare_context, andcapture_content_source(202) for the prompt, then the Stop hook's twoget_stats. Resume and fork ran the same prompt requests.POWERCONTEXT_CODEX_PROMPT_RECALL=false: the prompt hook sent onlyresolve_scope_bindingandcapture_content_source(202), the rollout has no prepared context, and the session's bootstrap receipt was cleared. WithPOWERCONTEXT_CODEX_CAPTURE_PROMPTS=falseas well, the prompt hook sent no request, and the receipt stayed in place; the bootstrap package and the Stop hook's requests were unchanged.scope_resolvediagnostic (invalid_response, 404,scope_not_found) above the answer, and the model answeredNONE. The Server received only three resolve requests (SessionStart, prompt, Stop), all 404, with no prepare, capture, or stats.codex exec --jsonmade the same requests and wrote the diagnostic to the throttle, butexecdoes not show a hook'ssystemMessage.scope_resolveserver_unavailablewithpowercontext doctoras the recovery. Inexec, the throttle recordedserver_unavailable.Overlap with other PRs
hooks/bind_tools.pyfail closed. This PR keeps it as master has it: every import, now includingcodex_hostand the package Scope client, sits inside the load guard;settings.scope_binding_settings()andhost_bounded_http_budget()run inside thetrythat denies on any failure; the denial reasons, the nullscope_idandselectionrule for control views, and the pass-through for other tools are unchanged.hooks/token_savings.pykeepshost_bounded_http_budget(). Two of its tests follow the move: the plugin-cannot-load test now breakspowercontext_lifecycle/scope_binding.py, whichbind_tools.pyimports, and the binding-unavailable test takesScopeBindingErrorfrom that module.claude_code_host.py; the prompt hook and the Scope script no longer have request headers of their own, so every request, including Scope bind and clear, sendspowercontext-claude-code-plugin/0.1.4. Itsscripts/mcp_headers.pyandmcp_authorization()are unchanged.hooks/bind_tools.py,tests/claude_code_plugin/conftest.py, andtests/codex_plugin/test_scope_binding.py. After this PR, the check goes in each hook after it builds theUserPromptEventand before it callsrun_user_prompt_submit();resolve_scope_id()now takes theHostProfilefirst andsettings.scope_binding_settings().Whichever of this PR and #2651 merges second resolves that overlap.
Notes (non-blocking)
hooks/token_savings.pyimports private helpers (_decode_error_code,_HttpStatusError,_read_response,_remaining_time,_ServerUnavailableError) frompowercontext_lifecycle.user_prompt_submit. A rename there would break the Stop hook without failing the lifecycle drift check; onlytest_token_savings.pywould catch it.run_user_prompt_submitby name, whether or not it calls it. Thetoken_savings.pycase checks that an import of other helpers from the same module does not count.bind_tools.py, and both plugins'mcp_headers.py, loads it too. Claude Code's helper imports settings inside itstry, so a failure there still emits no header. Codex's helper importssettingsat module level, as it does on master, so a package module that fails to import now also fails that helper; the package copies are generated and checked, so this needs a broken copy to happen. The import-cost measurement under "Are there any user-facing changes?" covers this.Self-review against
REVIEW.mdand an independent Opus review, which compared every moved path side by side with upstream/master, found no defect. A second independent Opus review of the master merge found that #2641's fail-closed behavior and #2669's User-Agent are fully kept.AI usage statement
This change was written by Claude Code (Claude Opus 5.5). Claude Code wrote the change and the tests, ran the checks and the real-host runs listed above, had the diff reviewed by an independent Claude Code agent, and wrote this description.